Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Redesign the Open Knowledge workspace layout (#4891)

sarah77920573bc2b
diff --git a/.changeset/dark-surface-hierarchy.md b/.changeset/dark-surface-hierarchy.md
new file mode 100644
index 000000000..3f27a1d2e
--- /dev/null
+++ b/.changeset/dark-surface-hierarchy.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Default dark mode gives the app frame, sidebars, and editor distinct neutral shades, subtler file names and badges, and brighter header button hovers.
diff --git a/.changeset/editor-card-polish.md b/.changeset/editor-card-polish.md
new file mode 100644
index 000000000..31de44b36
--- /dev/null
+++ b/.changeset/editor-card-polish.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+The area behind the cards and app header is a step darker and follows your color theme, the cards cast a soft shadow with a gap at the sides and bottom, the desktop file list is now opaque, and resize grips appear only when you hover a divider.
diff --git a/.changeset/editor-card.md b/.changeset/editor-card.md
new file mode 100644
index 000000000..6701e3f5c
--- /dev/null
+++ b/.changeset/editor-card.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+The editor, its file list and document side panel now sit in one card, with the terminal and chat in their own cards. The side panel button moved to the end of the tab bar, and dragging the chat or right terminal divider keeps the side panel's width.
diff --git a/.changeset/floating-notification-cards.md b/.changeset/floating-notification-cards.md
new file mode 100644
index 000000000..2e49fb63d
--- /dev/null
+++ b/.changeset/floating-notification-cards.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Update notices and the feedback card now float in the window's bottom-left corner, so they stay visible when the editor is hidden or the file list is collapsed.
diff --git a/.changeset/full-width-app-header.md b/.changeset/full-width-app-header.md
new file mode 100644
index 000000000..86cbdfd40
--- /dev/null
+++ b/.changeset/full-width-app-header.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+A new header across the top of project windows keeps back, forward, search, the project switcher, Share, sync, settings and resources in one fixed place. The editor footer now shows the current checkout: its project folder and its branch or worktree.
diff --git a/.changeset/header-editor-button.md b/.changeset/header-editor-button.md
new file mode 100644
index 000000000..f670983c0
--- /dev/null
+++ b/.changeset/header-editor-button.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Project windows can now hide the editor from a new Editor header button or View › Show/Hide Editor, letting chat and the terminal fill the window. Opening a document brings the editor back.
diff --git a/.changeset/header-pane-buttons.md b/.changeset/header-pane-buttons.md
new file mode 100644
index 000000000..9d00eaaa4
--- /dev/null
+++ b/.changeset/header-pane-buttons.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Project and single-file windows now have Agents and Terminal buttons at the right of the header that show whether each panel is open and toggle it with one click. They replace the right-edge chat tab, its live-agent dot and the panels' collapse arrows.
diff --git a/.changeset/narrow-editor-groups.md b/.changeset/narrow-editor-groups.md
new file mode 100644
index 000000000..119e411d7
--- /dev/null
+++ b/.changeset/narrow-editor-groups.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+When the editor is too narrow for its split panes, it shows one pane at a time with an Editor pane selector, keeping each pane's tabs and reading position.
diff --git a/.changeset/narrow-one-component-workspace.md b/.changeset/narrow-one-component-workspace.md
new file mode 100644
index 000000000..d4464d831
--- /dev/null
+++ b/.changeset/narrow-one-component-workspace.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Windows narrower than 48rem show one of Editor, Agents and Terminal at a time, chosen from the header, keep the others running, and return to your full layout when widened.
diff --git a/.changeset/narrow-sidebar-covers.md b/.changeset/narrow-sidebar-covers.md
new file mode 100644
index 000000000..4ac1d4fe7
--- /dev/null
+++ b/.changeset/narrow-sidebar-covers.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+When the file sidebar or document panel cannot fit beside the document, it opens as a full-editor cover with Back to editor and Hide, and choosing a destination in it reveals the document.
diff --git a/.changeset/reveal-repeated-document-destinations.md b/.changeset/reveal-repeated-document-destinations.md
new file mode 100644
index 000000000..76447db04
--- /dev/null
+++ b/.changeset/reveal-repeated-document-destinations.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Choosing the same document heading again now scrolls to its destination.
diff --git a/.changeset/sidebar-choice-every-width.md b/.changeset/sidebar-choice-every-width.md
new file mode 100644
index 000000000..9323d2fde
--- /dev/null
+++ b/.changeset/sidebar-choice-every-width.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Showing or hiding Files or the document panel now applies at every window width, so a sidebar you hid stays hidden when the window widens.
diff --git a/.changeset/single-file-shared-shell.md b/.changeset/single-file-shared-shell.md
new file mode 100644
index 000000000..853734296
--- /dev/null
+++ b/.changeset/single-file-shared-shell.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Single-file windows now use the shared header and editor cards, with the document panel in the editor card.
diff --git a/.changeset/single-file-traffic-lights.md b/.changeset/single-file-traffic-lights.md
new file mode 100644
index 000000000..db7df847b
--- /dev/null
+++ b/.changeset/single-file-traffic-lights.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+On macOS, the window buttons in a single-file window now sit centered in its top bar instead of below the middle.
diff --git a/.changeset/terminal-settled-theme.md b/.changeset/terminal-settled-theme.md
new file mode 100644
index 000000000..df276a4c9
--- /dev/null
+++ b/.changeset/terminal-settled-theme.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Keep terminal text readable after changing themes while the terminal is closed.
diff --git a/docs/content/features/agent-activity.mdx b/docs/content/features/agent-activity.mdx
index b539d3a5c..d9c7f11c9 100644
--- a/docs/content/features/agent-activity.mdx
+++ b/docs/content/features/agent-activity.mdx
@@ -8,7 +8,7 @@ Agent activity shows all edits made by an agent during its current editing sessi
## Open agent activity
-Avatar icons will appear in the top right of the editor whenever an agent or a human has the document open. Agents working in other documents appear in an adjacent group. You can click on any agent's avatar icon to open the activity panel for that agent.
+Avatar icons will appear on the right of the header at the top of the window (in its [**More actions**](/docs/features/editor#when-the-header-runs-out-of-room) menu when the header is full) whenever an agent or a human has the document open. Agents working in other documents appear in an adjacent group. You can click on any agent's avatar icon to open the activity panel for that agent.
The activity panel displays the list of files that the agent has edited in the current session.
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 7bb0ceea5..7ace3bb1c 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -14,11 +14,11 @@ ok notes.md # open a single file in the editor
ok ./specs/foo/SPEC.md # a file inside a project opens that project, focused on the doc
```
-When the file is inside an existing OpenKnowledge project, this opens that project focused on the doc. When it's a loose file, it opens an **ephemeral single-file session**: a throwaway editor scoped to just that one file, with no project scaffolding, no agents, and no git. Your edits save straight back to the original file, and **nothing is written into the file's directory** — all session state lives in a temporary directory that's removed when you close the window. Opening a file you don't edit leaves it byte-for-byte unchanged.
+When the file is inside an existing OpenKnowledge project, this opens that project focused on the doc. When it's a loose file, it opens an **ephemeral single-file session**: a throwaway editor scoped to just that one file, with no project scaffolding or git. Your edits save straight back to the original file, and **nothing is written into the file's directory** — all session state lives in a temporary directory that's removed when you close the window. Opening a file you don't edit leaves it byte-for-byte unchanged.
Single-file sessions own only the selected file. Different-file previews can coexist, but an enclosing project cannot start until its overlapping preview closes. File uploads and project-wide configuration changes require opening a project; they cannot create files beside a loose preview. Appearance settings and document comments remain available. See [overlapping projects and previews](/docs/reference/cli#overlapping-projects-and-previews) for nested-project boundaries and restart requirements.
-It opens in the desktop app when it's installed, and falls back to your browser otherwise (press Ctrl-C in the terminal to end a browser session). Single-file sessions show just the file and the editor — no sidebar, tabs, or project switcher. Discover it any time with `ok --help`.
+It opens in the desktop app when it's installed, and falls back to your browser otherwise (press Ctrl-C in the terminal to end a browser session). Single-file sessions use the shared header and editor card without a project file sidebar, project tabs, or project switcher. At narrow widths, the header lets you choose Editor, Agents, or Terminal where available and return to Editor. Discover it any time with `ok --help`.
On Windows, you can also open `.md` and `.mdx` files from Explorer with **Open With → OpenKnowledge**, or double-click them when OpenKnowledge is their default app. With the desktop app installed, these actions open a project or a standalone file using the same rules as `ok <file>`; see [Windows file associations and changing the default app](/docs/reference/what-open-knowledge-writes#installing-and-launching-the-app).
@@ -127,7 +127,7 @@ Surfaces with their own specialized right-click menus — asset and wiki-link ch
## Ask AI
-An **Ask AI** composer is docked at the bottom of the editor — in the desktop app and in a regular browser — whenever a doc or folder view is open. It's a slim, single-line entry field that expands as you type to accept a fuller prompt (and `@`-mentions); in the desktop app, `Cmd+L` opens and focuses it. Its `@` picker opens with the document you're on first, ahead of the rest of the workspace. The Agents panel's own composer goes one step further and also lists what you've already attached earlier in that conversation. Type an instruction — "condense this doc", "research X", "make a spec from this user story" — and press Enter to hand it to an agent. `Shift+Enter` inserts a newline; the field clears once the prompt is sent.
+An **Ask AI** composer is docked at the bottom of the editor — in the desktop app and in a regular browser — whenever a doc or folder view is open and the editor isn't [hidden](#hide-the-editor). It's a slim, single-line entry field that expands as you type to accept a fuller prompt (and `@`-mentions); `Cmd+Shift+L` (`Ctrl+Shift+L` on Windows and Linux) opens and focuses it. Its `@` picker opens with the document you're on first, ahead of the rest of the workspace. The Agents panel's own composer goes one step further and also lists what you've already attached earlier in that conversation. Type an instruction — "condense this doc", "research X", "make a spec from this user story" — and press Enter to hand it to an agent. `Shift+Enter` inserts a newline; the field clears once the prompt is sent.
It's the primary in-editor way to hand work to an agent, and the freetext companion to the menu-driven [Open with AI](#open-with-ai) (whole file / folder / project). Submitting dispatches the typed prompt to your **default agent**, scoped to the current doc (or, in a folder view, the folder), which the agent receives as an `@`-mention. Until you pick something else, that default is an **In app** agent, so the conversation stays inside OpenKnowledge; it falls back to a **Terminal** CLI — preferring one detected on this machine — and then to an **External app**, when no higher option is available here. The agent picker beside the field overrides the default per send, listing In app agents first, then the [Terminal](#open-with-ai) CLIs available on this machine, then the external agent apps detected here. Whatever you pick is remembered on that machine and stays your default until you change it or turn it off in **Agent connections**. Success and failure use the same handoff toast as Open with AI.
@@ -135,7 +135,7 @@ New in-app agent sessions automatically receive the [OpenKnowledge project skill
The **Add to prompt (+)** menu beside the field is available for every selected target. It always offers **Mention a page** and, when selected comments are waiting to be attached, **Attach comments**. With an **In app** agent selected, it also offers **Attach files**; you can add files from the menu, drop a file on the field, or paste a screenshot into it. Each attachment appears as a removable chip above the input and travels with the prompt into the new conversation. Once the prompt is sent, the chip for a doc that's still in the project opens that doc. Images can come from anywhere. Other files inside the project are sent as a path reference that the agent reads itself. A text file from outside the project, or any text file attached in a browser (which can't see file paths), travels with the message instead. Other kinds of file can't travel with the message; mention them with @ once they're in the project. Images must be PNG, JPEG, GIF, or WebP, and the images and text files that travel with one message are capped at 700 KB combined; a larger text file has to be in the project, where you can mention it with @. An image too large for what's left of that budget, such as a full-screen Retina screenshot, is scaled down and re-encoded to fit when it can be, so the agent gets a smaller copy instead of a refusal. A GIF is never resized, since that would drop its animation, so one over 700 KB is still refused. Pick a **Terminal** CLI or an **External app** instead and the composer refuses the drop with the reason — those targets have no attachment channel — and if you attach first and switch afterwards, the send is blocked with the same explanation rather than silently dropping the file. Attachments aren't available in note windows yet, and whether an in-app agent can actually read an image is up to that agent: if it can't, OpenKnowledge shows a notification saying so once the agent's capabilities are known. The empty-state create composer on a fresh project takes attachments the same way — drop, paste, or the attach button while an **In app** agent is picked — and refuses them with the reason for **Terminal** and **External apps** targets.
-The composer stays out of the way where it doesn't belong: it's hidden inside an AI editor's embedded view, while the [docked terminal](#terminal) is open (the terminal is its own AI entry point), and when no doc or folder is open (the empty state's create composer offers the same handoff, attachments included). It's also dismissible — an **Ask AI** badge in the status bar brings it back.
+The composer stays out of the way where it doesn't belong: it's hidden inside an AI editor's embedded view, while the [docked terminal](#terminal) is open (the terminal is its own AI entry point), when no doc or folder is open (the empty state's create composer offers the same handoff, attachments included), and while the editor is hidden, including on the [Nothing open](#nothing-open) screen, where **Open agents** is the way to an agent. It's also dismissible — an **Ask AI** badge in the status bar brings it back.
### In-app agent release-date policies
@@ -183,9 +183,9 @@ 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), or with **View ▸ Show / Hide Terminal**. 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 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 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. With text selected in the editor, `Cmd+J` on macOS, `Ctrl+J` on Windows or Linux, and `` Ctrl+` `` on any desktop platform stage the passage into the active CLI's input (or open a new CLI tab when none is running) instead of toggling — they share one handler. `Cmd+Shift+J` on macOS or `Ctrl+Shift+J` on Windows or Linux always stages it into a new CLI tab; 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.
+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.
On Windows, type `wsl` in any terminal tab to enter your default WSL distribution; OpenKnowledge's CLI detection and bundled `ok` command stay Windows-side, so install agent CLIs on Windows for them to appear in the launcher.
@@ -193,7 +193,11 @@ Rename a tab by double-clicking it or pressing `F2`; the name you set pins over
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 Agents panel keeps its own open/closed memory: on the web it is remembered in your browser, on desktop with the project, where it also survives a full app restart and is restored at launch. A reload reopens the panel at that remembered state: threads already live at the reload never change it, so a panel you left closed stays closed, and a thread that goes live after the reload opens it. While the panel is closed, a dot on the **Open agents panel** tab marks live threads. A browser or a project with no recorded panel state starts with the panel closed and records the state from its first session onward.
+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.
+
+The **Editor** button comes first in the same group, before **Agents** and **Terminal**. It appears in project and single-file windows on desktop and on the web, but not in note windows, and is highlighted while the editor is shown. In a window narrower than 48rem it selects Editor, including when returning from Agents or Terminal; see [Narrow windows](#narrow-windows). Project windows can also hide Editor; see [Hide the editor](#hide-the-editor).
+
+The Agents panel keeps its own open/closed memory: on the web it is remembered in your browser, on desktop with the project, where it also survives a full app restart and is restored at launch. A reload reopens the panel at that remembered state: threads already live at the reload never change it, so a panel you left closed stays closed, and a thread that goes live after the reload opens it. A browser or a project with no recorded panel state starts with the panel closed and records the state from its first session onward.
The Agents panel's **Chat history** button opens every conversation the project has, live and closed alike, in one list. Type in its search box to filter by conversation title; the rows group into **Today** and **Older** by the local date of their last activity, newest first. Selecting a row activates that conversation's tab, and renaming or deleting a conversation works from the row's own controls, with deletion still requiring you to close an open archived chat's tab first.
@@ -203,10 +207,48 @@ 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.
-On a narrow window, 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.
+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 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.
+## Hide the editor
+
+In a project window you can hide the editor and give the window to the Agents panel and the terminal. At 48rem and wider, click the **Editor** button at the right end of the header; at any width, choose **View ▸ Show / Hide Editor** in the desktop app or search `editor` in the [command palette](#command-palette). Below 48rem the **Editor** button only selects Editor, and hiding it works as described in [Narrow windows](#narrow-windows). There is no keyboard shortcut for it. Single-file windows keep Editor available in the shared header but can show another supported component instead while narrow. Note windows remain editor-only.
+
+Hiding the editor hides all of it: the file sidebar, the tabs, the document, the document panel, the status bar with the checkout line (the project folder and the branch or worktree), and the bottom [Ask AI](#ask-ai) composer. Nothing reloads. Open documents, tabs, the file sidebar and the document panel stay loaded, and showing the editor brings them back as they were.
+
+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 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.
+
+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.
+
+While the editor is hidden, `Cmd+L` (`Ctrl+L` on Windows and Linux) only shows and hides the Agents panel and never sends the hidden editor's selection. `Cmd+Shift+J` (`Ctrl+Shift+J`) opens a new session the way the tab strip's **+** button does, a CLI chat or a plain shell, whichever you picked last, and stages nothing.
+
+Whether the editor is shown is remembered: in the desktop app per project, including across a full app restart, and on the web in your browser. A **Hide Editor** in a window narrower than 48rem lasts only for that window's session and does not change this setting.
+
+### Nothing open
+
+When the editor, the Agents panel and the terminal are all hidden, the main area shows **Nothing open** with **Open editor**, **Open agents** and **Open terminal** buttons. **Open terminal** appears only where the **Terminal** button would, so not on the web or in a project with the terminal turned off. The Ask AI composer is not shown on this screen. Quitting with every panel hidden reopens to **Nothing open**.
+
+## Narrow windows
+
+When a project or single-file window is narrower than 48rem (768px at the default text size), it shows one of Editor, Agents and Terminal at a time instead of side by side. The **Editor**, **Agents** and **Terminal** buttons in the header select which one you see; pressing the one already shown does nothing. The others keep running while hidden: chats keep streaming, shells keep their output, and drafts, tabs, scroll positions and undo history are kept for when you switch back.
+
+- The component you used last is selected when the window narrows. Opening a document from search, history, a link, the terminal or a chat selects Editor with that document.
+- **Hide Agents** or **Hide Terminal** (from the View menu, the command palette or `Cmd+L` for Agents) returns to Editor. **Hide Editor** shows an Agents or Terminal session that is already open, or **Nothing open** if none is.
+- Refreshing keeps the selection in the same window or tab. A new tab or window starts with Editor.
+- Widening the window restores the layout you had at full width. Choosing a component or hiding one while narrow does not change which panels open when the window is wide again, but closing a chat or terminal session closes it everywhere.
+
+When the editor is too narrow to show every [split pane](#tabs-and-split-panes) side by side, it shows one pane at a time, and an **Editor pane** selector in the editor header switches between them. Each pane keeps its own tabs and reading position.
+
## Properties
Every doc can carry a bit of structured information at the top: a `status`, an `owner`, a `tags` list, a date. OpenKnowledge calls these its **properties**.
@@ -217,7 +259,7 @@ A folder can describe itself (its own properties, just like a doc's) and offer t
## File sidebar
-The sidebar lists every file in your project on disk, including files excluded by `.gitignore` / `.okignore`, except dot-prefixed entries and tooling internals (`.git/`, `.ok/`, `node_modules/`). Turn on **Show Hidden Files** to reveal the dot-prefixed entries. Folder rows expand and collapse; file rows open in a tab on click. A file with validation problems shows a tinted row and a count badge, and clicking the badge (or tabbing to it and pressing Enter) opens that file with the Problems panel on it, see [Where problems show up](../advanced/content-rules/overview.mdx#where-problems-show-up). The toolbar at the top of the sidebar has buttons to create files, create folders, and search. At the bottom of the sidebar, the collapsible **Skills Studio** dock lists your skills next to your files, so a file and a skill can be open side by side; see [Skills Studio](./skills/index.mdx#where-to-find-skills-studio).
+The sidebar lists every file in your project on disk, including files excluded by `.gitignore` / `.okignore`, except dot-prefixed entries and tooling internals (`.git/`, `.ok/`, `node_modules/`). Turn on **Show Hidden Files** to reveal the dot-prefixed entries. Folder rows expand and collapse; file rows open in a tab on click. A file with validation problems shows a tinted row and a count badge, and clicking the badge (or tabbing to it and pressing Enter) opens that file with the Problems panel on it, see [Where problems show up](../advanced/content-rules/overview.mdx#where-problems-show-up). The project row at the top of the file list has buttons to create files and folders; search is in the header at the top of the window. At the bottom of the sidebar, the collapsible **Skills Studio** dock lists your skills next to your files, so a file and a skill can be open side by side; see [Skills Studio](./skills/index.mdx#where-to-find-skills-studio).
### Right-click context menus
@@ -245,7 +287,7 @@ Expand all and Collapse all only appear when they have work to do: Expand all is
### Creating files and folders
-Pick **New File**, **New from template**, or **New Folder** from any of the three menus. The sidebar shows an inline rename field at the target location; type a name and press Enter. **New from template** opens the [template picker](../advanced/folders-and-templates.mdx#templates) (the same dialog the toolbar's create buttons use) and respects the folder's `templates_available` cascade.
+Pick **New File**, **New from template**, or **New Folder** from any of the three menus. The sidebar shows an inline rename field at the target location; type a name and press Enter. **New from template** opens the [template picker](../advanced/folders-and-templates.mdx#templates) (the same dialog the project row's create buttons use) and respects the folder's `templates_available` cascade.
Right-click on empty space drops the new item at the project root. Right-click on a folder drops it inside that folder.
@@ -311,15 +353,15 @@ Tabs share the main editor header and shrink as the row fills, keeping every ope
To work side by side, drag any document, folder, or **New tab** to the left or right edge of the editor. The blue drop indicator shows where the new vertical pane will open. You can also right-click a tab and choose **Move to new pane left** or **Move to new pane right**; from the keyboard, focus the tab, press `Shift+F10` (or the Menu key), then choose the same command. Drag the divider to resize panes. Each pane keeps its own active tab, while the document panel follows the pane you most recently focused. Moving or closing a pane's last tab removes the pane automatically.
-Open tabs, pane order, sizes, and the focused pane are restored with the project after a clean restart.
+Open tabs, pane order, sizes, and the focused pane are restored with the project after a clean restart. In an editor too narrow for its panes, see [Narrow windows](#narrow-windows).
## Command palette
-`Cmd+K` opens the command palette in both the desktop app and the browser, and `Cmd+P` (`Ctrl+P` on Windows / Linux) does the same from anywhere — including while text is selected in the visual editor, where `Cmd+K` adds a link instead. Type to jump to any file or folder, run create commands, open the graph or settings, or dispatch to an agent; recently opened entries surface first. In the desktop app it also switches projects and worktrees.
+`Cmd+K` opens the command palette in both the desktop app and the browser, and `Cmd+P` (`Ctrl+P` on Windows / Linux) does the same from anywhere — including while text is selected in the visual editor, where `Cmd+K` adds a link instead. Type to jump to any file or folder, run create commands, open the graph or settings, or dispatch to an agent; recently opened entries surface first. In the desktop app it also switches projects and worktrees. In project windows, searching `editor` finds **Show Editor** or **Hide Editor**, whichever applies, the same toggle as the header's **Editor** button (see [Hide the editor](#hide-the-editor)).
In the browser, `Cmd+P` is normally the print shortcut; OpenKnowledge takes it for the palette, so print from the browser's own menu instead.
-Remove a recent project from the list by hovering its row and clicking the ×, or right-clicking for a **Remove from recent projects** menu — the same controls are on the sidebar's **Switch project** dropdown and in the Project Navigator. A recent whose folder was deleted or moved off disk isn't greyed out; it's cleared automatically the next time you open it, with a brief notice, instead of opening a broken window.
+Remove a recent project from the list by hovering its row and clicking the ×, or right-clicking for a **Remove from recent projects** menu — the same controls are on the **Switch project** dropdown in the header at the top of the window and in the Project Navigator. A recent whose folder was deleted or moved off disk isn't greyed out; it's cleared automatically the next time you open it, with a brief notice, instead of opening a broken window.
Every word you type has to appear somewhere in a command's name or its search terms, but the order does not matter and the words do not have to sit next to each other: `branch switch` and `switch branch` both reach **Switch worktree**. Commands also carry the words people search by rather than only the words in their names, so `delete file` reaches **Move to Trash** and `open settings` reaches **Settings**. Because commands are listed above file results, a query that matches both will highlight the command — arrow down to reach the file, or keep typing to narrow.
@@ -327,14 +369,14 @@ A `tag:` prefix searches by tag: `tag:` alone lists every tag, `tag:fr` narrows
## Sidebars and window width
-The editor has two sidebars: the file sidebar on the left and the document panel on the right (Outline, Links, Properties, Timeline). Both adapt to the window:
+The editor has two sidebars: the file sidebar on the left and the document panel on the right (Outline, Links, Graph, Timeline, Problems and Comments; single-file windows show Outline, Problems and Comments). Both adapt to the window:
- At comfortable widths (1280px and up) both sidebars open by default.
- Between 1024px and 1279px the document panel defaults to collapsed so the editor keeps its breathing room; the file sidebar stays open.
- Below 1024px both default to collapsed so the editor canvas isn't squeezed off-screen.
- When OpenKnowledge is opened inside an AI editor's webview (Cursor, Codex, Claude Desktop), both sidebars start collapsed regardless of width; the embedded view is for reading the content you were sent, not for file management.
-The defaults only apply until you toggle. OpenKnowledge remembers your most recent Show / Hide for each sidebar in your browser and survives reloads. When you come back to the same layout context (narrow window, comfortable window, or embedded view) you used last, your toggle is what you'll see. Toggling in a different context replaces that memory; only your most recent choice sticks, so a stale preference from a wide-monitor session can't quietly override what you just chose on a narrow screen.
+OpenKnowledge remembers your explicit Show / Hide choice for each sidebar across reloads, at every window width. When there is not enough room to dock a sidebar beside a usable document, OpenKnowledge temporarily hides it without changing that choice. Requesting the sidebar while it cannot dock opens it as a full-editor cover. **Back to editor** returns to the document without turning the sidebar off. **Hide panel** in the document panel cover's header, or **Hide Files** in the file sidebar's **Tree view options** menu, closes it explicitly, so widening does not reopen it. As space returns, a sidebar hidden only for fit can dock again.
Keyboard shortcuts (on Windows / Linux, use `Ctrl` in place of `Cmd` and `Alt` in place of `Option`; rows that already use `Ctrl` are unchanged):
@@ -351,11 +393,12 @@ Keyboard shortcuts (on Windows / Linux, use `Ctrl` in place of `Cmd` and `Alt` i
| `Cmd+Option+B` | Show / Hide the document panel (right). Matches VS Code's Secondary Side Bar accelerator. |
| `Cmd+Option+M` | Toggle between the visual and source editors, keeping your place. |
| `Cmd+Option+E` | **View in source** — jump from the visual editor to the Markdown for the block at the cursor, centered and highlighted (visual editor only). |
-| `Cmd+J` / `Ctrl+J` | Show / Hide the Terminal in its current placement (macOS / Windows and Linux desktop apps). With text selected, stages the passage into the AI CLI's input instead — nothing runs until you press Enter. |
-| `` Ctrl+` `` | Show / Hide the Terminal too — the VS Code / Zed chord, literal `Ctrl` (desktop app). Works even while a terminal holds focus. With text selected it stages the passage like `Cmd+J` instead of toggling. |
-| `Cmd+Shift+J` / `Ctrl+Shift+J` | Open an additional terminal tab (macOS / Windows and Linux desktop apps). With text selected, stages the passage into the new tab's AI CLI input. |
+| `Cmd+J` / `Ctrl+J` | Show / Hide the Terminal in its current placement (macOS / Windows and Linux desktop apps). |
+| `` Ctrl+` `` | Show / Hide the Terminal too — the VS Code / Zed chord, literal `Ctrl` (desktop app). Works even while a terminal holds focus. |
+| `Cmd+Shift+J` / `Ctrl+Shift+J` | Open a new session the way the tab strip's **+** button does (macOS / Windows and Linux desktop apps): a CLI chat or a plain shell, whichever you picked last, or an agent chat for an in-app agent. With text selected in the editor, stages the passage in a new session with your preferred AI, never a plain shell; while the editor is [hidden](#hide-the-editor) nothing is staged. |
| `Cmd+P` | Open the [command palette](#command-palette) from anywhere — unlike `Cmd+K`, it opens the palette even while text is selected in the visual editor. |
-| `Cmd+L` | Open and focus the [Ask AI](#ask-ai) composer (desktop app). |
+| `Cmd+L` | Show / Hide the Agents panel. With text selected in the editor, stages the passage in the Agents panel instead (**Ask AI about selection**), ready to add to and send. While the editor is [hidden](#hide-the-editor) it only shows and hides the panel. |
+| `Cmd+Shift+L` | Open and focus the [Ask AI](#ask-ai) composer. |
| `Cmd+Shift+D` / `Ctrl+Shift+D` | Start a bug report (desktop app). The screenshot it attaches is the screen exactly as it looks when you press the chord — open menus, tooltips and hover states included — plus a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker appears if the pointer has not moved since the window loaded, or has since left the window. Nothing is sent until you press Send. |
| `Cmd+Shift+M` | [Comment](/docs/features/comments) on the selected text (visual editor). |
| `Cmd+Shift+Enter` | Send the checked comments the open **Comments** tab is showing to an agent. Does nothing while that tab is closed. |
@@ -367,6 +410,10 @@ In the desktop app the sidebar and terminal toggles also live in the **View** me
Inside an AI editor's embedded view, the **Open with AI** menus, the bottom Ask AI composer, and the empty-state agent grid are hidden; you're already inside an agent, so the handoff would loop back into the same surface. OpenKnowledge's MCP tools and the document itself stay fully available; only the launchers are gone.
+### When the header runs out of room
+
+At any window width, when the header has no room for all of its controls, the presence avatars for agents and collaborators, **Share**, sync, settings and resources move into a **More actions** menu. The menu sits on the right side of the header, just before the **Editor**, **Agents** and **Terminal** buttons, which always stay outside it. Pages that point to those controls on the right of the header mean this menu while it is showing.
+
## Application menus
The OpenKnowledge desktop app keeps its menu bar in sync with the active editor target: File menu items enable / disable based on whether a doc, folder, or nothing is currently selected. On macOS this is the system menu bar; on Windows and Linux the same menus live in the app window's title bar, with `Ctrl` in place of `Cmd`.
@@ -405,7 +452,9 @@ Before the existing Zoom and Toggle Fullscreen items, the View menu gets:
| --- | --- | --- |
| **Show / Hide Sidebar** | `Cmd+Option+S` | Toggles the file sidebar (left). Label flips between Show and Hide based on current state, matching Finder. |
| **Show / Hide Document Panel** | `Cmd+Option+B` | Toggles the document panel (right). |
-| **Show / Hide Terminal** | `Cmd+J` / `Ctrl+J` | Toggles the Terminal in its current placement. With editor text selected, stages the selection into the AI CLI's input instead of toggling. (`` Ctrl+` `` toggles it too, though that chord has no menu accelerator.) |
+| **Show / Hide Editor** | (none) | Toggles the editor, in project windows only (see [Hide the editor](#hide-the-editor)). Label flips between Show and Hide like the other toggles. |
+| **Show / Hide Terminal** | `Cmd+J` / `Ctrl+J` | Toggles the Terminal in its current placement. (`` Ctrl+` `` toggles it too, though that chord has no menu accelerator.) |
+| **Show / Hide Agents** | `Cmd+L` | macOS View menu only: the Windows and Linux title-bar menus have no Agents item, so there use `Ctrl+L`, the header **Agents** button or the command palette. Toggles the Agents panel. With text selected in the editor, and the editor shown, the item reads **Ask AI About Selection** and stages the selection in the Agents panel instead. |
| **Show Hidden Files** | `Cmd+Shift+.` | `appearance.sidebar.showHiddenFiles`; same toggle as the sidebar's right-click menu. |
| **Expand All** | (none) | Expands every folder in the tree. Hidden when nothing is collapsed. |
| **Collapse All** | (none) | Collapses every folder in the tree. Hidden when nothing is expanded. |
@@ -423,7 +472,7 @@ Toggling the menu checkboxes flips the underlying config field, which propagates
## Real-time collaboration
-Everything in the editor (body, frontmatter, sidebar toggles) is backed by a CRDT. You and multiple AI agents writing through MCP can edit the same doc concurrently. Per-user presence is shown in the editor header; the **agent activity** view ([Agent activity](./agent-activity.mdx)) groups every burst of agent edits with per-burst diffs and selective undo.
+Everything in the editor (body, frontmatter, sidebar toggles) is backed by a CRDT. You and multiple AI agents writing through MCP can edit the same doc concurrently. Per-user presence is shown on the right of the header at the top of the window; the **agent activity** view ([Agent activity](./agent-activity.mdx)) groups every burst of agent edits with per-burst diffs and selective undo.
For recovery + history, see [Timeline and recovery](./timeline-and-recovery.mdx).
diff --git a/docs/content/features/git/github.mdx b/docs/content/features/git/github.mdx
index c00a33817..25773469f 100644
--- a/docs/content/features/git/github.mdx
+++ b/docs/content/features/git/github.mdx
@@ -14,7 +14,7 @@ These steps use the desktop app; from a terminal, [`ok clone`](/docs/reference/c
<Step>
### Open the clone dialog
- From the Navigator window, click **Clone from GitHub**. You can open the Navigator window from the editor by clicking on your project name in the bottom left and then clicking **Switch project**.
+ From the Navigator window, click **Clone from GitHub**. You can open the Navigator window from the editor by clicking the project switcher in the middle of the header at the top of the window and then clicking **Switch project**.
</Step>
<Step>
@@ -34,13 +34,13 @@ These steps use the desktop app; from a terminal, [`ok clone`](/docs/reference/c
<Step>
### Open the project
- When the clone completes, the cloned project opens in a new editor window and the Navigator closes. Re-summon the Navigator from inside the editor via the sidebar Switch Project pill, the File menu, or the Command Palette.
+ When the clone completes, the cloned project opens in a new editor window and the Navigator closes. Re-summon the Navigator from inside the editor via **Switch project** in the project switcher at the top of the window, the File menu, or the Command Palette.
</Step>
</Steps>
## Publish a local project to GitHub
-You can publish your local project to GitHub directly from the OpenKnowledge app by opening a folder or file and clicking the **Share** button in the top right of the editor.
+You can publish your local project to GitHub directly from the OpenKnowledge app by opening a folder or file and clicking the **Share** button on the right of the header at the top of the window (in its [**More actions**](/docs/features/editor#when-the-header-runs-out-of-room) menu when the header is full).
This will open a dialog where you can choose an owner and repository name. You can also choose to make the repository public or private.
diff --git a/docs/content/features/git/sync.mdx b/docs/content/features/git/sync.mdx
index ab8f0ce80..8c93aa4fd 100644
--- a/docs/content/features/git/sync.mdx
+++ b/docs/content/features/git/sync.mdx
@@ -61,7 +61,7 @@ After repeated failures, OpenKnowledge slows each direction down independently:
## Sync status and conflicts
-Click the <Cloud role="img" aria-label="Sync" className="inline size-4 align-text-bottom" /> icon in the top right to open the sync menu. The **Status** section shows how many commits you are ahead of or behind the remote, which files the next pull or push would include, and when sync last ran. Opening the menu only fetches; nothing in your copy changes until you press a button.
+Click the <Cloud role="img" aria-label="Sync" className="inline size-4 align-text-bottom" /> icon on the right of the header, at the top of the window, to open the sync menu; when the header is full it is in the [**More actions**](/docs/features/editor#when-the-header-runs-out-of-room) menu. The **Status** section shows how many commits you are ahead of or behind the remote, which files the next pull or push would include, and when sync last ran. Opening the menu only fetches; nothing in your copy changes until you press a button.
If an incoming update conflicts with your edits, sync pauses and the menu lists the conflicted files. Open one to [choose which version to keep](#resolving-a-conflict); every other file stays editable in the meantime. Uncommitted changes that an update would overwrite appear under **Changed here and on the remote**, where **Commit and sync** commits them and resumes.
@@ -81,7 +81,7 @@ Another app can also save an exact older copy over an edit OpenKnowledge already
## Work on multiple branches
-In the desktop app you can open several branches of the same project at once, each in its own window. Click your project name in the bottom left and pick a branch or worktree from the project switcher (open worktrees also appear in the Command Palette); **New worktree** starts a fresh branch or checks out an existing one. The switcher discovers Git's complete local worktree list when you open a repository, including checkouts that have never been opened in OpenKnowledge. Each checkout shows its path and a location label: **primary** is the original clone, **internal** is beneath that clone's `.ok/worktrees/` directory, and **external** is anywhere else. A generic **worktree** label means the location could not be resolved yet, such as a recent checkout shown before its inventory loads or a checkout whose directory is unavailable. These labels describe location only.
+In the desktop app you can open several branches of the same project at once, each in its own window. Click the project switcher in the middle of the header at the top of the window, which shows the repository's name, and pick a branch or worktree (open worktrees also appear in the Command Palette); **New worktree** starts a fresh branch or checks out an existing one. The footer at the bottom of the editor shows which checkout a window has open: the project's folder when the project sits inside the repository rather than at its root, then the branch, or the worktree's folder name when no branch is checked out. The switcher discovers Git's complete local worktree list when you open a repository, including checkouts that have never been opened in OpenKnowledge. Each checkout shows its path and a location label: **primary** is the original clone, **internal** is beneath that clone's `.ok/worktrees/` directory, and **external** is anywhere else. A generic **worktree** label means the location could not be resolved yet, such as a recent checkout shown before its inventory loads or a checkout whose directory is unavailable. These labels describe location only.
Opening a branch that has no worktree yet creates one on demand under `.ok/worktrees/`, kept out of `git status`, so each window runs its own editor and server without touching your main working copy. Detached and Git-locked worktrees remain available. A row marked **project missing**, **path unreadable**, or **stale Git entry** is shown for diagnosis but cannot be opened until its filesystem or Git state is repaired.
diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdx
index e3a328299..cb5e9d9ba 100644
--- a/docs/content/features/share.mdx
+++ b/docs/content/features/share.mdx
@@ -4,7 +4,7 @@ icon: LuShare2
description: Copy a link to any doc or folder and send it to a teammate. OpenKnowledge handles the GitHub round-trip, the deep link, and the branch on the other end.
---
-OpenKnowledge has a Share button in the editor toolbar. Click it and the app copies a `https://openknowledge.ai/d/…` URL to your clipboard. Anyone you send it to lands on a splash page that knows the project and target, and a single click opens it in their copy of OpenKnowledge.
+OpenKnowledge has a Share button on the right of the header at the top of the window, in its [**More actions**](/docs/features/editor#when-the-header-runs-out-of-room) menu when the header is full. Click it and the app copies a `https://openknowledge.ai/d/…` URL to your clipboard. Anyone you send it to lands on a splash page that knows the project and target, and a single click opens it in their copy of OpenKnowledge.
Share links give each recipient their own copy, kept in sync through GitHub. For real-time editing where everyone works on one live server instead, see the [Remote Control overview](/docs/remote-control/overview).
diff --git a/docs/content/get-started/quickstart.mdx b/docs/content/get-started/quickstart.mdx
index 731c15fa5..97a225e8f 100644
--- a/docs/content/get-started/quickstart.mdx
+++ b/docs/content/get-started/quickstart.mdx
@@ -80,7 +80,7 @@ Not sure what to write? Paste this into the input box (or use a topic of your ch
An in-app agent works in OpenKnowledge's Agents panel, which opens beside the editor. If you handed the project to an external app instead — Cursor, Codex, or Claude Desktop — that agent opens the OpenKnowledge editor in an embedded window.
-You will see your agent's icon in the top right of the editor window. Click on the icon to see the agent's [activity](/docs/features/agent-activity) across files in the knowledge base.
+You will see your agent's icon on the right of the header at the top of the window, or in its [**More actions**](/docs/features/editor#when-the-header-runs-out-of-room) menu when the header is full. Click on the icon to see the agent's [activity](/docs/features/agent-activity) across files in the knowledge base.
If the agent icon is greyed out, your agent may not have started writing yet. Wait a few seconds and check again.
@@ -174,7 +174,7 @@ In the agent's chat window, add the following to get started or use a topic of y
### Watch your agent work
-You will see your agent's icon in the top right of the editor window. Click on the icon to see the agent's [activity](/docs/features/agent-activity) across files in the knowledge base.
+You will see your agent's icon on the right of the header at the top of the window, or in its [**More actions**](/docs/features/editor#when-the-header-runs-out-of-room) menu when the header is full. Click on the icon to see the agent's [activity](/docs/features/agent-activity) across files in the knowledge base.
If the agent icon is greyed out, your agent may not have started writing yet. Wait a few seconds and check again.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 4f022b8a9..0443e0da1 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -411,7 +411,7 @@ None of your content, by default. Everything above is written to your own disk.
| Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first). On macOS it also carries the crash reports the OS recorded for this app and its helper processes (listed above), which are machine-wide rather than project-scoped; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the summary printed before the zip is written says what that search found even when the answer is nothing. On every platform it also carries the past week of the operating system's records of this app being ended from outside (listed above), and the same summary says what that read found | Wherever you send it |
| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog, or the `Cmd+Shift+D` / `Ctrl+Shift+D` shortcut that opens the same dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. The zip carries a picture of the app window unless you uncheck **Screenshot** in that dialog, and the preview there is the picture that would be sent. You can also attach up to three images by dropping them on the **What happened?** box, pasting them anywhere in the dialog (`Cmd+V` / `Ctrl+V`), or browsing with the paperclip in that box. Neither these images nor the screenshot are scanned or redacted, so review them before sending. A report started from an agent chat's **Report a problem with this chat…** also carries, unless you uncheck **This conversation**, the newest 4 MB of that chat's messages, tool calls, and their output, and the chat's metadata file, which names the chat's title, the project folder's path, the document the chat started from, and the agent and its settings. Known secrets are scrubbed from both. Images and other binary content in the chat, including images pasted into a message, are replaced by a note of their type and size, while text files attached to a message are included and scrubbed the same way. If the chat's messages can't be added, the review step says so and the report goes without the conversation. If only the metadata file can't be read, the report carries the messages without it, and the review step doesn't say so. A report reached through a surface you opened only to get to the reporter — the command palette, the Help popover, the Windows and Linux menu bar, or an agent chat's **Settings** menu — waits for that surface to close first, and carries no marker, because the row it would point at has already gone. Every other report you start yourself photographs the screen as it is, so an open menu or another person's document visible at the time is in the picture, and carries a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker is drawn either if the pointer has not moved since the window loaded, or has since left the window. The invitation that appears on its own after a crash is the exception to all of this: it carries no picture at all. When the app holds a crash dump, the same dialog adds a **Crash dump** checkbox. It starts checked on the invitation that follows a crash with a dump available, and unchecked on a report you open yourself. A crash dump is a memory snapshot that can contain document content and can't be redacted, so it is attached only if that box is checked when you create the report, and you review the result before anything is sent. The invitation attaches the dump of the crash it was raised for, never a newer one; if that dump can't be added, the review step says so and the report goes without it. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. At the **Detailed diagnostics** level — pre-checked on the invitation that follows a crash — it additionally carries the crash reports macOS itself recorded for this app and its helpers (also listed above), which are machine-wide for the same reason and named in the same README; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the zip always says what that search found even when the answer is nothing. On every platform the same level also adds the past week of the operating system's records of this app being ended from outside (also listed above), listed in `manifest.json` for a project's zip and named in the same README for a system-wide zip whenever records were kept. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | Send uploads the zip to the bug-report intake: `openknowledge.ai` unless [`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables) points elsewhere. If the upload fails, Send falls back to a prefilled email draft to [email protected] that you send yourself, naming the zip to attach |
| Uninstall feedback | Only if you answer the optional "Before you go" screen or prompt. The macOS desktop asks after you confirm removal, before the app quits and cleanup starts; feedback can be sent even if cleanup later fails. Interactive `ok uninstall` asks only after successful cleanup. Skipping sends nothing; CLI runs with `--yes`, `--json`, or non-interactive input never ask | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included |
-| Feedback form | Only when you click **Send** in the feedback form, opened from **Help → Send feedback**, the command palette's **Send feedback** command, or the feedback card in the sidebar. Images you drop on, paste into, or attach to the message box go with it; like bug report images, they are not scanned or redacted | `openknowledge.ai/api/feedback` — your rating, the reasons you picked, your note, your email address if you gave one, up to three attached images, plus the app version and platform. In the desktop app the images upload first to the bug-report intake (`openknowledge.ai` unless [`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables) points elsewhere) and the feedback carries links to them. If an image upload fails, the images go inline with the feedback to `openknowledge.ai/api/feedback` instead |
+| Feedback form | Only when you click **Send** in the feedback form, opened from **Help → Send feedback**, the command palette's **Send feedback** command, or the feedback card in the window's bottom-left corner. Images you drop on, paste into, or attach to the message box go with it; like bug report images, they are not scanned or redacted | `openknowledge.ai/api/feedback` — your rating, the reasons you picked, your note, your email address if you gave one, up to three attached images, plus the app version and platform. In the desktop app the images upload first to the bug-report intake (`openknowledge.ai` unless [`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables) points elsewhere) and the feedback carries links to them. If an image upload fails, the images go inline with the feedback to `openknowledge.ai/api/feedback` instead |
| Semantic search embeddings | Only when you enable [semantic search](./configuration.mdx#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) |
| GitHub sync / share | When you sync, clone, publish, or share | GitHub |
| Update check | Automatically — on launch and periodically while the desktop app runs | OpenKnowledge update service (`openknowledge.ai/updates`), which redirects to GitHub; sends the app version and channel |
diff --git a/docs/src/components/html-preview.test.ts b/docs/src/components/html-preview.test.ts
index e665c6d01..84ca646ed 100644
--- a/docs/src/components/html-preview.test.ts
+++ b/docs/src/components/html-preview.test.ts
@@ -176,8 +176,6 @@ describe('HtmlPreview space reservation', () => {
describe('preview theme tokens track the editor', () => {
const DARK_OVERRIDES = new Map([
- ['--background', 'sits on the docs card surface, not the editor canvas'],
- ['--card', 'sits on the docs card surface, not the editor canvas'],
['--border', 'docs card is lighter, so its border runs 14% alpha against the editor 10%'],
]);
diff --git a/docs/src/components/html-preview.tsx b/docs/src/components/html-preview.tsx
index 009c8c5ce..98c8b9a88 100644
--- a/docs/src/components/html-preview.tsx
+++ b/docs/src/components/html-preview.tsx
@@ -17,7 +17,7 @@ const LIGHT =
'--background:oklch(1 0 0);--foreground:oklch(0.145 0 0);--card:oklch(1 0 0);--card-foreground:oklch(0.145 0 0);--muted:oklch(0.97 0 0);--muted-foreground:oklch(0.556 0 0);--border:oklch(0.922 0 0);--primary:oklch(0.5621 0.1983 259.59);--accent-soft:#e6efff;--accent-ink:#00245d;--chart-1:oklch(0.62 0.19 259);--chart-2:oklch(0.58 0.14 145);--chart-3:oklch(0.62 0.15 70);--chart-4:oklch(0.55 0.18 290);--chart-5:oklch(0.58 0.21 25);--radius:0.625rem;color-scheme:light';
const DARK =
- '--background:oklch(0.205 0 0);--foreground:oklch(0.985 0 0);--card:oklch(0.245 0 0);--card-foreground:oklch(0.985 0 0);--muted:oklch(0.3 0 0);--muted-foreground:oklch(0.708 0 0);--border:oklch(1 0 0 / 0.14);--primary:#69a3ff;--accent-soft:#12233f;--accent-ink:#9ec3ff;--chart-1:oklch(0.72 0.14 259);--chart-2:oklch(0.73 0.13 145);--chart-3:oklch(0.77 0.14 70);--chart-4:oklch(0.72 0.16 290);--chart-5:oklch(0.72 0.2 25);--radius:0.625rem;color-scheme:dark';
+ '--background:oklch(0.195 0 0);--foreground:oklch(0.985 0 0);--card:oklch(0.245 0 0);--card-foreground:oklch(0.985 0 0);--muted:oklch(0.3 0 0);--muted-foreground:oklch(0.708 0 0);--border:oklch(1 0 0 / 0.14);--primary:#69a3ff;--accent-soft:#12233f;--accent-ink:#9ec3ff;--chart-1:oklch(0.72 0.14 259);--chart-2:oklch(0.73 0.13 145);--chart-3:oklch(0.77 0.14 70);--chart-4:oklch(0.72 0.16 290);--chart-5:oklch(0.72 0.2 25);--radius:0.625rem;color-scheme:dark';
const THEME_CSS = `:root{${LIGHT}}@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){${DARK}}}:root[data-theme="dark"]{${DARK}}:root[data-theme="light"]{${LIGHT}}`;
diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.md
index 4d5a0bac7..dd7047c55 100644
--- a/packages/app/BUNDLE-SIZE.md
+++ b/packages/app/BUNDLE-SIZE.md
@@ -105,3 +105,11 @@ Combined-chunks 8.89->8.90 MB after merging the comments-panel layout and select
Combined-chunks 8.89->8.9 MB for PowerShell path quoting: `psQuoteArg` now doubles all five characters PowerShell reads as a single quote (U+0027 and U+2018-U+201B), not only the ASCII apostrophe, so a dropped file whose name contains a curly quote gives a working command. CI measured the pull request at 8,890,002 B, 2 B over the prior 8,890,000 B ceiling. Clean local builds of the same tree measured 8,889,973 B with the previous `psQuoteArg` and 8,890,002 B with the change, so it adds 29 B. The main app bundle measured 441.88 kB before the change and 441.87 kB with it, against its 487 kB limit, and CSS stayed at 8.36 kB against 59 kB, so neither eager budget moves. The 10 kB ratchet leaves 9,998 B of headroom over the local build.
Combined-chunks 8.9->9.15 MB for Polish (`pl`), the thirteenth supported locale. Base-vs-branch was measured rather than assumed: with `pl` removed from the locale tuples and rebuilt on this branch, combined chunks measured exactly 8.9 MB — on its ceiling with no headroom left — so the whole overage is this branch's. With `pl` enumerated the same build measures 8.99 MB, 94.09 kB over the 8,900,000 B ceiling, and the Polish catalog's own on-demand chunk measures 96,360 B gzipped, which accounts for the increase. The main app bundle is byte-comparable between the two builds at 443.24 vs 443.25 kB against its 487 kB limit, and CSS at 8.36 kB against 59 kB, so this is chunk inventory rather than eager weight: a reader who never selects polski never fetches it. The new ceiling leaves about 156 kB (1.7%) of headroom, in line with the 1.4% local-to-CI ratio and the ~1.9% recorded on the `ko` raise above.
+
+Combined-chunks 8.9->8.91 MB for the header pane buttons: the Editor, Agents and Terminal toggles, the Nothing open screen, the reveal-on-deliberate-open plumbing, the Show/Hide Editor command, and their strings compiled into every locale catalog. CI measured the pull request at 8,902,839 B, 2,839 B over the prior 8,900,000 B ceiling, which the base `feat/layout-redesign` already sat on. The main app bundle grew from 448.28 kB on the base to 453.01 kB against its 487 kB limit, because the header buttons, the pane store and the reveal helpers load eagerly with the shell; CSS stayed at 8.36 kB against 59 kB. The 10 kB ratchet leaves 7,161 B of headroom over the CI measurement. Removed on the same branch: the right-edge agents tab and the in-pane collapse chevrons, which is why the combined growth is smaller than the eager growth. No reclamation lever beyond the lazy-load levers above.
+
+Combined-chunks 8.91->8.92 MB for the corner card stack that floats update and feedback cards in the window's bottom-left corner. CI measured the pull request at 8,911,181 B, 1,181 B over the 8,910,000 B ceiling; the same job on the base `feat/layout-redesign` head `0c8e62f` measured 8,910,714 B, already 714 B over, so this branch adds 467 B. The main app bundle measured 453.61 kB on the base and 453.8 kB on the branch against its 487 kB limit, and CSS stayed at 8.36 kB against 59 kB. The 10 kB ratchet leaves 8,819 B of headroom over the CI measurement. No reclamation lever beyond the lazy-load levers above.
+
+Combined-chunks 8.92->8.93 MB for the responsive single-pane workspace: one selected component in narrow windows, the sidebar covers over the editor card, the shared sidebar fit budget, the narrow editor group selector, the single-file shared shell, and their strings compiled into every locale catalog. CI measured the pull request 8.48 kB over the 8,920,000 B ceiling, about 8,928,480 B. The main app bundle measured 467.58 kB against its 487 kB limit, up from 453.8 kB on the base, because the narrow layout state and the cover controls load eagerly with the shell; CSS stayed at 8.36 kB against 59 kB. The 10 kB ratchet leaves about 1.5 kB of headroom over the CI measurement. No reclamation lever beyond the lazy-load levers above.
+
+Combined-chunks stays at 9.15 MB after merging `feat/layout-redesign` into `main`. The three raises above (8.9->8.93 MB) were set on that integration branch while `main` raised the same ceiling to 9.15 MB for Polish, so the enforced limit is `main`'s and the 8.91, 8.92 and 8.93 MB ceilings never applied there; their headroom figures describe the branch, not the merged tree. A clean local build of the merged tree measured 9,144,866 B combined, 5,134 B under the 9,150,000 B ceiling, with the main app bundle at 477.79 kB against its 487 kB limit and CSS at 8.36 kB against 59 kB. CI's size job passed on the first merged head. No reclamation lever beyond the lazy-load levers above.
diff --git a/packages/app/index.html b/packages/app/index.html
index 6f4bc82d5..efda82f2b 100644
--- a/packages/app/index.html
+++ b/packages/app/index.html
@@ -28,14 +28,6 @@
<ThemeProvider storageKey='ok-theme-v1'> in `src/main.tsx` — keep keys
in sync. next-themes stores the value as a plain string, not JSON.
- The inline <style> below paints the html background to match the
- body's resolved background (body uses `bg-sidebar` per globals.css).
- The placeholders __OK_CHROME_BG_LIGHT__ / __OK_CHROME_BG_DARK__ are
- substituted at build time by chromeTokensVitePlugin (resolves the
- Tailwind v4 `--sidebar` OKLCH values to sRGB hex via culori). Single
- source of truth for chrome bg — no hand-maintained drift between
- this file and packages/core/src/constants/chrome.ts.
-
The `electron-mode` class is added when `window.okDesktop` is
present (preload bridge runs before any inline page script). Paired
consumer: globals.css `html.electron-mode` rules — render the outer
@@ -93,7 +85,7 @@
FOUC scripts above.
-->
<script>(() => { try { const raw = localStorage.getItem('ok-language-v1'); if (!raw) return; const o = JSON.parse(raw); if (typeof o?.locale !== 'string' || !/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{2,8})*$/.test(o.locale)) return; document.documentElement.lang = o.locale; document.documentElement.dir = o.dir === 'rtl' ? 'rtl' : 'ltr'; } catch {} })();</script>
- <style>html { background-color: __OK_CHROME_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style>
+ <style>html { background-color: __OK_SIDEBAR_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style>
</head>
<body class="antialiased">
diff --git a/packages/app/package.json b/packages/app/package.json
index 31c793181..932a81fac 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -41,7 +41,7 @@
"measure:stress": "bash scripts/measure-stress.sh",
"measure:sweep": "bash scripts/measure-sweep.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/empty-bullet-before-link.e2e.ts tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/external-link-cue.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/settings-close-button.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/nested-component-sibling-edit-bytes.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/harness-port-ownership.e2e.ts tests/stress/server-reuse-admission.e2e.ts tests/stress/server-reuse-reset.e2e.ts tests/stress/prebuilt-dev-serving.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts tests/stress/assertion-timeout.e2e.ts tests/stress/loop-markers.e2e.ts tests/stress/template-admission-detail.e2e.ts",
+ "test:e2e": "playwright test tests/stress/empty-bullet-before-link.e2e.ts tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/external-link-cue.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/header-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/settings-close-button.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/nested-component-sibling-edit-bytes.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/harness-port-ownership.e2e.ts tests/stress/server-reuse-admission.e2e.ts tests/stress/server-reuse-reset.e2e.ts tests/stress/prebuilt-dev-serving.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/hidden-chat-activity.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/editor-card-side-panel-width.e2e.ts tests/stress/editor-card-file-list-drag.e2e.ts tests/stress/editor-pane-cards.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/app-header-layout.e2e.ts tests/stress/app-header-locales.e2e.ts tests/stress/app-header-fit.e2e.ts tests/stress/header-pane-buttons.e2e.ts tests/stress/editor-pane-button.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts tests/stress/chat-shortcut-collapsed-thread.e2e.ts tests/stress/chat-explicit-hide-late-restore.e2e.ts tests/stress/information-cover-retention.e2e.ts tests/stress/information-cover-doc-panel-host.e2e.ts tests/stress/responsive-cycles-release-editor-callback-contexts.e2e.ts tests/stress/constrained-sidebar-request-routes.e2e.ts tests/stress/editor-group-switch-immediate-selection.e2e.ts tests/stress/corner-stack-feedback.e2e.ts tests/stress/corner-stack-notices.e2e.ts tests/stress/corner-stack-layouts.e2e.ts tests/stress/corner-stack-survival.e2e.ts tests/stress/corner-stack-geometry.e2e.ts tests/stress/corner-stack-layering.e2e.ts tests/stress/corner-stack-surface.e2e.ts tests/stress/corner-stack-already-seen.e2e.ts tests/stress/assertion-timeout.e2e.ts tests/stress/loop-markers.e2e.ts tests/stress/template-admission-detail.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:perf": "vitest run tests/stress/component-blocks.perf.test.ts",
"test:a11y": "playwright test --config playwright.a11y.config.ts",
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index 7c9e2f0ef..1feb5f4f2 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -1,17 +1,28 @@
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import { hashFromDocName, pushHashWithoutNavigation } from '@/lib/doc-hash';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import {
+ hashFromDocName,
+ pushHashWithoutNavigation,
+ replaceHashWithoutNavigation,
+} from '@/lib/doc-hash';
import { matchesKeyboardShortcut, type ShortcutEventLike } from '@/lib/keyboard-shortcuts';
import {
__resetLocalMenuActionBusForTests,
emitLocalMenuAction,
} from '@/lib/local-menu-action-bus';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import {
consumeHashNavigationSuppression,
recordAppShellCrashTrip,
resetTabSessionRestoreSuppression,
} from '@/lib/tab-session-restore-suppression';
+import { noteWorkspaceHashWrite } from '@/lib/workspace-hash-writes';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
@@ -230,28 +241,39 @@ vi.doMock('@/components/NewItemDialog', () => ({
}));
vi.doMock('@/components/FileSidebar', () => ({
- FileSidebar: ({ onOpenSearch }: { onOpenSearch: () => void }) => (
- <button type="button" data-testid="file-sidebar" onClick={onOpenSearch}>
- Sidebar
- </button>
- ),
+ FileSidebar: () => <div data-testid="file-sidebar">Sidebar</div>,
+}));
+
+vi.doMock('@/components/UpdateNotices', () => ({
+ UpdateNotices: () => <div data-testid="update-notices" />,
}));
-vi.doMock('@/components/EditorPane', () => ({
- EditorPane: () => <main data-testid="editor-pane" />,
+vi.doMock('@/components/FeedbackCard', () => ({
+ FeedbackCardMount: () => <div data-testid="feedback-card-mount" />,
}));
+vi.doMock('@/components/EditorPane', async () => {
+ const { useState } = await import('react');
+ const { useAttachFileListHost, useFileListHost } = await import('@/components/FileListHost');
+ function EditorPane() {
+ const host = useFileListHost();
+ const [slot, setSlot] = useState<HTMLDivElement | null>(null);
+ useAttachFileListHost(host, slot);
+ return (
+ <div data-testid="editor-pane">
+ <div data-testid="editor-file-list-slot" ref={setSlot} />
+ </div>
+ );
+ }
+ return { EditorPane };
+});
+
vi.doMock('@/components/ui/sidebar', () => ({
SidebarProvider: ({ children, className }: { children: ReactNode; className?: string }) => (
<section data-testid="sidebar-provider" className={className}>
{children}
</section>
),
- SidebarInset: ({ children, className }: { children: ReactNode; className?: string }) => (
- <section data-testid="sidebar-inset" className={className}>
- {children}
- </section>
- ),
}));
vi.doMock('@/components/ShareReceiveDialog', () => ({
@@ -281,6 +303,9 @@ function createBridge({ ptyAvailable = true }: { ptyAvailable?: boolean } = {})
mode: 'editor' as const,
ptyAvailable,
},
+ state: {
+ query: () => Promise.resolve({ channel: 'latest' as const }),
+ },
};
}
@@ -288,6 +313,14 @@ function createNoteWindowBridge() {
return { ...createBridge(), config: { mode: 'note' as const, ptyAvailable: true } };
}
+function appMain(): HTMLElement {
+ const main = document.querySelector<HTMLElement>('[data-app-main]');
+ if (main == null) throw new Error('the app content wrapper is missing');
+ expect(main.getAttribute('role')).toBeNull();
+ expect(main.tagName).toBe('DIV');
+ return main;
+}
+
function renderApp({ bridge = null }: { bridge?: ReturnType<typeof createBridge> | null } = {}) {
if (bridge) {
Object.defineProperty(window, 'okDesktop', {
@@ -295,7 +328,7 @@ function renderApp({ bridge = null }: { bridge?: ReturnType<typeof createBridge>
value: bridge,
});
}
- return render(<App />);
+ return render(<App />, { wrapper: TooltipProvider });
}
function setHash(hash: string) {
@@ -362,21 +395,21 @@ describe('App runtime wiring', () => {
expect(screen.queryByTestId('file-sidebar')).toBeNull();
expect(screen.queryByTestId('command-palette')).toBeNull();
expect(screen.queryByTestId('system-doc-subscriber')).toBeNull();
- expectVisualClassTokens(screen.getByTestId('sidebar-inset').className, ['h-screen']);
- expectVisualClassTokensAbsent(screen.getByTestId('sidebar-inset').className, [
+ expectVisualClassTokens(appMain().className, ['h-screen']);
+ expectVisualClassTokensAbsent(appMain().className, [
'h-[calc(100vh-var(--layout-inset-offset))]',
]);
});
- test('single-file windows fill the available height', () => {
+ test('single-file windows reserve the shared header height like ordinary windows', () => {
singleFileMode = true;
renderApp({ bridge: createBridge() });
expect(screen.queryByTestId('file-sidebar')).toBeNull();
- expectVisualClassTokens(screen.getByTestId('sidebar-inset').className, ['h-screen']);
- expectVisualClassTokensAbsent(screen.getByTestId('sidebar-inset').className, [
- 'h-[calc(100vh-var(--layout-inset-offset))]',
+ expectVisualClassTokens(appMain().className, [
+ 'h-[calc(100vh-var(--ok-app-header-height,0px))]',
]);
+ expectVisualClassTokensAbsent(appMain().className, ['h-screen']);
});
test('keeps the editor and the connecting banner', () => {
@@ -393,10 +426,10 @@ describe('App runtime wiring', () => {
expect(screen.getByTestId('command-palette')).not.toBeNull();
expect(screen.getByTestId('system-doc-subscriber')).not.toBeNull();
expect(screen.getByTestId('editor-pane')).not.toBeNull();
- expectVisualClassTokens(screen.getByTestId('sidebar-inset').className, [
- 'h-[calc(100vh-var(--layout-inset-offset))]',
+ expectVisualClassTokens(appMain().className, [
+ 'h-[calc(100vh-var(--ok-app-header-height,0px))]',
]);
- expectVisualClassTokensAbsent(screen.getByTestId('sidebar-inset').className, ['h-screen']);
+ expectVisualClassTokensAbsent(appMain().className, ['h-screen']);
});
});
@@ -409,6 +442,9 @@ describe('App runtime wiring', () => {
expect(screen.getByTestId('system-doc-subscriber')).not.toBeNull();
expect(screen.getByTestId('file-sidebar')).not.toBeNull();
expect(screen.getByTestId('editor-pane')).not.toBeNull();
+ expect(
+ screen.getByTestId('editor-file-list-slot').contains(screen.getByTestId('file-sidebar')),
+ ).toBe(true);
});
test('a desktop host without PTY capability keeps terminal launching disabled', () => {
@@ -500,6 +536,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(downgradeFolderIndexForHashNavMock).toHaveBeenCalledWith(resolved);
expect(openTargetTransitionMock).toHaveBeenCalledWith(downgraded, {
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
});
@@ -532,6 +569,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(openTargetTransitionMock).toHaveBeenCalledWith(missing, {
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
});
@@ -552,6 +590,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(resolveNavigationTargetMock).toHaveBeenCalledWith('# 2 - Tokens', expect.anything());
expect(openTargetTransitionMock).toHaveBeenCalledWith(target, {
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
});
@@ -578,6 +617,7 @@ describe('App runtime wiring', () => {
docName: 'docs/guide.mdx',
},
{
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
},
@@ -606,6 +646,7 @@ describe('App runtime wiring', () => {
expect(openTargetTransitionMock).toHaveBeenCalledWith(
{ kind: 'doc', target: 'page-a', docName: 'page-a' },
{
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
},
@@ -633,6 +674,7 @@ describe('App runtime wiring', () => {
docName: '.editorconfig',
},
{
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
},
@@ -668,6 +710,7 @@ describe('App runtime wiring', () => {
docName: 'page-a',
},
{
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
},
@@ -688,7 +731,11 @@ describe('App runtime wiring', () => {
target: 'page-b',
docName: 'page-b',
},
- expect.objectContaining({ disposition: 'preview', consumeActiveNewTab: true }),
+ expect.objectContaining({
+ deliberate: true,
+ disposition: 'preview',
+ consumeActiveNewTab: true,
+ }),
);
});
@@ -703,7 +750,11 @@ describe('App runtime wiring', () => {
target: 'page-a',
docName: 'page-a',
},
- expect.objectContaining({ disposition: 'preview', consumeActiveNewTab: true }),
+ expect.objectContaining({
+ deliberate: true,
+ disposition: 'preview',
+ consumeActiveNewTab: true,
+ }),
);
});
@@ -718,7 +769,11 @@ describe('App runtime wiring', () => {
target: 'page-b',
docName: 'page-b',
},
- expect.objectContaining({ disposition: 'preview', consumeActiveNewTab: true }),
+ expect.objectContaining({
+ deliberate: true,
+ disposition: 'preview',
+ consumeActiveNewTab: true,
+ }),
);
});
});
@@ -735,6 +790,7 @@ describe('App runtime wiring', () => {
docName: 'page-a',
},
{
+ deliberate: false,
disposition: 'permanent',
consumeActiveNewTab: true,
},
@@ -754,6 +810,7 @@ describe('App runtime wiring', () => {
docName: 'page-b',
},
{
+ deliberate: true,
disposition: 'permanent',
consumeActiveNewTab: true,
},
@@ -761,6 +818,148 @@ describe('App runtime wiring', () => {
});
});
+ async function renderOnPageA() {
+ setHash('#/page-a');
+ renderApp();
+ await waitFor(() => {
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ { kind: 'doc', target: 'page-a', docName: 'page-a' },
+ expect.objectContaining({ deliberate: false }),
+ );
+ });
+ openTargetTransitionMock.mockClear();
+ }
+
+ test('a document opened from inside Settings is a deliberate open', async () => {
+ await renderOnPageA();
+
+ window.location.hash = '#settings';
+ await waitFor(() => expect(window.location.hash).toBe('#settings'));
+ window.location.hash = '#/page-b';
+
+ await waitFor(() => {
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ { kind: 'doc', target: 'page-b', docName: 'page-b' },
+ expect.objectContaining({ deliberate: true }),
+ );
+ });
+ });
+
+ test('closing Settings back to the document is not a deliberate open', async () => {
+ await renderOnPageA();
+
+ window.location.hash = '#settings';
+ await waitFor(() => expect(window.location.hash).toBe('#settings'));
+ window.history.back();
+
+ await waitFor(() => {
+ expect(window.location.hash).toBe('#/page-a');
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ { kind: 'doc', target: 'page-a', docName: 'page-a' },
+ expect.objectContaining({ deliberate: false }),
+ );
+ });
+ });
+
+ test('a document opened after the install dialog closes is a deliberate open', async () => {
+ await renderOnPageA();
+
+ window.location.hash = '#install-claude-desktop';
+ await waitFor(() => expect(window.location.hash).toBe('#install-claude-desktop'));
+ replaceHashWithoutNavigation('');
+ window.location.hash = '#/page-b';
+
+ await waitFor(() => {
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ { kind: 'doc', target: 'page-b', docName: 'page-b' },
+ expect.objectContaining({ deliberate: true }),
+ );
+ });
+ });
+
+ test('the first Back after the install dialog closes is a deliberate open', async () => {
+ await renderOnPageA();
+ pushHashWithoutNavigation('#/page-b');
+
+ window.location.hash = '#install-claude-desktop';
+ await waitFor(() => expect(window.location.hash).toBe('#install-claude-desktop'));
+ replaceHashWithoutNavigation('');
+ window.history.back();
+
+ await waitFor(() => {
+ expect(window.location.hash).toBe('#/page-b');
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ { kind: 'doc', target: 'page-b', docName: 'page-b' },
+ expect.objectContaining({ deliberate: true }),
+ );
+ });
+ });
+
+ function editorRequestsFromClick(
+ href: string,
+ init: MouseEventInit = {},
+ options: { readonly alreadyPrevented?: boolean } = {},
+ ): PaneVisibilityRequest[] {
+ renderApp();
+ __resetPaneVisibilityStoreForTests();
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ const link = document.createElement('a');
+ link.setAttribute('href', href);
+ const label = document.createElement('span');
+ link.append(label);
+ document.body.append(link);
+ if (options.alreadyPrevented) link.addEventListener('click', (event) => event.preventDefault());
+
+ fireEvent.click(label, init);
+
+ link.remove();
+ __resetPaneVisibilityStoreForTests();
+ return requests;
+ }
+
+ test('a plain click on an in-app document link asks a hidden editor to show', () => {
+ expect(editorRequestsFromClick('#/page-a')).toEqual([{ pane: 'editor', open: true }]);
+ });
+
+ test.each<[string, string, MouseEventInit, boolean]>([
+ ['a Cmd click', '#/page-a', { metaKey: true }, false],
+ ['a Ctrl click', '#/page-a', { ctrlKey: true }, false],
+ ['a Shift click', '#/page-a', { shiftKey: true }, false],
+ ['an Alt click', '#/page-a', { altKey: true }, false],
+ ['a middle-button click', '#/page-a', { button: 1 }, false],
+ ['a click something already handled', '#/page-a', {}, true],
+ ['a click on a web link', 'https://example.com/docs', {}, false],
+ ['a click on an email link', 'mailto:[email protected]', {}, false],
+ ['a click on an in-page fragment', '#section', {}, false],
+ ])('%s leaves a hidden editor hidden', (_label, href, init, alreadyPrevented) => {
+ expect(editorRequestsFromClick(href, init, { alreadyPrevented })).toEqual([]);
+ });
+
+ test('an address change to the document already open shows a hidden editor unless the workspace wrote it', async () => {
+ activeTarget = { kind: 'doc', target: 'page-a', docName: 'page-a' };
+ setHash('#/page-a');
+ renderApp();
+ await Promise.resolve();
+ __resetPaneVisibilityStoreForTests();
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+
+ noteWorkspaceHashWrite('#/page-a');
+ window.dispatchEvent(new HashChangeEvent('hashchange'));
+ expect(requests).toEqual([]);
+
+ window.dispatchEvent(new HashChangeEvent('hashchange'));
+ expect(requests).toEqual([{ pane: 'editor', open: true }]);
+ expect(openTargetTransitionMock).not.toHaveBeenCalled();
+ __resetPaneVisibilityStoreForTests();
+ });
+
test('active doc and folder targets are pushed to the desktop bridge', async () => {
const bridge = createBridge();
activeTarget = { kind: 'doc', target: 'docs/readme', docName: 'docs/readme' };
@@ -825,8 +1024,8 @@ describe('App runtime wiring', () => {
expect(screen.queryByTestId('share-receive-dialog')).toBeNull();
});
- test('Electron host renders the drag strip with fixed 8px chrome geometry', () => {
- renderApp({ bridge: createBridge() });
+ test('a note window keeps the drag strip with fixed 8px chrome geometry', () => {
+ renderApp({ bridge: createNoteWindowBridge() as ReturnType<typeof createBridge> });
const strip = screen.getByTestId('editor-window-chrome-drag-strip');
expect(strip.getAttribute('aria-hidden')).toBe('true');
@@ -842,6 +1041,13 @@ describe('App runtime wiring', () => {
]);
});
+ test('the app header supersedes the drag strip in an ordinary editor window', () => {
+ renderApp({ bridge: createBridge() });
+
+ expect(screen.getByRole('banner')).not.toBeNull();
+ expect(screen.queryByTestId('editor-window-chrome-drag-strip')).toBeNull();
+ });
+
test('web host does not render Electron-only drag or share-receive surfaces', () => {
renderApp();
@@ -849,6 +1055,125 @@ describe('App runtime wiring', () => {
expect(screen.queryByTestId('share-receive-dialog')).toBeNull();
});
+ describe('application header placement', () => {
+ test('paints above both the file list and the editor, in document order', () => {
+ renderApp();
+
+ const header = screen.getByRole('banner');
+ const shell = screen.getByTestId('sidebar-provider');
+ expect(header.compareDocumentPosition(shell) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(
+ header.compareDocumentPosition(screen.getByTestId('file-sidebar')) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ header.compareDocumentPosition(screen.getByTestId('editor-pane')) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ test('takes its height out of the shell below it so nothing overflows the viewport', () => {
+ renderApp();
+
+ const shellRoot = document.querySelector<HTMLElement>('[data-app-shell]');
+ expect(shellRoot?.style.getPropertyValue('--ok-app-header-height')).toBe('2.75rem');
+ expectVisualClassTokens(screen.getByTestId('sidebar-provider').className, [
+ 'h-[calc(100vh-var(--ok-app-header-height,0px))]',
+ 'min-h-[calc(100svh-var(--ok-app-header-height,0px))]',
+ ]);
+ expectVisualClassTokens(appMain().className, [
+ 'ps-2',
+ 'pb-2',
+ 'pe-2',
+ 'h-[calc(100vh-var(--ok-app-header-height,0px))]',
+ ]);
+ expectVisualClassTokensAbsent(appMain().className, ['overflow-hidden', 'rounded-e-xl']);
+ });
+
+ test('a note window has no application header and no header height to subtract', () => {
+ renderApp({ bridge: createNoteWindowBridge() as ReturnType<typeof createBridge> });
+
+ expect(screen.queryByRole('banner')).toBeNull();
+ const shellRoot = document.querySelector<HTMLElement>('[data-app-shell]');
+ expect(shellRoot?.style.getPropertyValue('--ok-app-header-height')).toBe('');
+ expectVisualClassTokens(appMain().className, ['h-screen']);
+ expectVisualClassTokensAbsent(appMain().className, [
+ 'h-[calc(100vh-var(--ok-app-header-height,0px))]',
+ ]);
+ });
+
+ test('a single-file window shows the shared application header', () => {
+ singleFileMode = true;
+
+ renderApp({ bridge: createBridge() });
+
+ expect(screen.getByRole('banner')).not.toBeNull();
+ });
+
+ test('its search button opens the command palette', () => {
+ renderApp();
+
+ expect(screen.getByTestId('command-palette').getAttribute('data-open')).toBe('false');
+ fireEvent.click(within(screen.getByRole('banner')).getByRole('button', { name: 'Search' }));
+ expect(screen.getByTestId('command-palette').getAttribute('data-open')).toBe('true');
+ });
+ });
+
+ describe('corner card stack', () => {
+ function expectNoCornerStack() {
+ expect(screen.getByTestId('editor-pane')).not.toBeNull();
+ expect(screen.queryByTestId('corner-card-stack')).toBeNull();
+ expect(screen.queryByRole('region', { name: 'Updates and feedback' })).toBeNull();
+ expect(screen.queryByTestId('update-notices')).toBeNull();
+ expect(screen.queryByTestId('feedback-card-mount')).toBeNull();
+ }
+
+ test('a desktop project window holds the update notice above the feedback card in one stack after the panes', () => {
+ renderApp({ bridge: createBridge() });
+
+ expect(screen.getAllByTestId('corner-card-stack')).toHaveLength(1);
+ const stack = screen.getByRole('region', { name: 'Updates and feedback' });
+ expect(stack).toBe(screen.getByTestId('corner-card-stack'));
+ const column = within(stack).getByTestId('corner-card-stack-column');
+ expect(Array.from(column.children).map((child) => child.getAttribute('data-testid'))).toEqual(
+ ['update-notices', 'feedback-card-mount'],
+ );
+ expect(screen.getAllByTestId('update-notices')).toHaveLength(1);
+ expect(screen.getAllByTestId('feedback-card-mount')).toHaveLength(1);
+
+ expect(screen.getByTestId('page-list-provider').contains(stack)).toBe(true);
+ expect(screen.getByTestId('editor-file-list-slot').contains(stack)).toBe(false);
+ expect(screen.getByTestId('editor-pane').contains(stack)).toBe(false);
+ expect(screen.getByTestId('sidebar-provider').contains(stack)).toBe(false);
+ expect(
+ screen.getByTestId('editor-pane').compareDocumentPosition(stack) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ test('a web project window has the same stack', () => {
+ renderApp();
+
+ const stack = screen.getByRole('region', { name: 'Updates and feedback' });
+ expect(screen.getAllByTestId('corner-card-stack')).toHaveLength(1);
+ expect(within(stack).getByTestId('feedback-card-mount')).not.toBeNull();
+ });
+
+ test('a note window has no stack and no cards', () => {
+ renderApp({ bridge: createNoteWindowBridge() as ReturnType<typeof createBridge> });
+
+ expectNoCornerStack();
+ });
+
+ test('a single-file window has no stack and no cards', () => {
+ singleFileMode = true;
+
+ renderApp({ bridge: createBridge() });
+
+ expectNoCornerStack();
+ });
+ });
+
describe('repeat-crash recovery hash suppression', () => {
afterEach(() => {
resetTabSessionRestoreSuppression();
@@ -899,7 +1224,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(openTargetTransitionMock).toHaveBeenCalledWith(
{ kind: 'doc', target: 'other-doc', docName: 'other-doc' },
- { disposition: 'permanent', consumeActiveNewTab: true },
+ { deliberate: true, disposition: 'permanent', consumeActiveNewTab: true },
);
});
});
@@ -913,7 +1238,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(openTargetTransitionMock).toHaveBeenCalledWith(
{ kind: 'doc', target: 'kept-doc', docName: 'kept-doc' },
- { disposition: 'permanent', consumeActiveNewTab: true },
+ { deliberate: false, disposition: 'permanent', consumeActiveNewTab: true },
);
});
expect(window.location.hash).toBe('#/kept-doc');
@@ -936,7 +1261,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(openTargetTransitionMock).toHaveBeenCalledWith(
{ kind: 'doc', target: 'kept-doc', docName: 'kept-doc' },
- { disposition: 'permanent', consumeActiveNewTab: true },
+ { deliberate: false, disposition: 'permanent', consumeActiveNewTab: true },
);
});
expect(window.location.hash).toBe('#/kept-doc');
@@ -956,7 +1281,7 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(openTargetTransitionMock).toHaveBeenCalledWith(
{ kind: 'doc', target: 'poison-doc', docName: 'poison-doc' },
- { disposition: 'permanent', consumeActiveNewTab: true },
+ { deliberate: false, disposition: 'permanent', consumeActiveNewTab: true },
);
});
});
diff --git a/packages/app/src/App.history-traversal.dom.test.tsx b/packages/app/src/App.history-traversal.dom.test.tsx
index d1cf4f415..fa6cc85e3 100644
--- a/packages/app/src/App.history-traversal.dom.test.tsx
+++ b/packages/app/src/App.history-traversal.dom.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, render, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
+import { TooltipProvider } from '@/components/ui/tooltip';
import {
createEmptyEditorWorkspace,
type EditorWorkspaceState,
@@ -236,7 +237,7 @@ describe('history traversal and the preview tab slot', () => {
});
test('three sidebar preview clicks keep the strip at one tab', async () => {
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
for (const doc of ['page-a', 'page-b', 'page-c']) {
clickDocRow(doc, true);
view.rerender(<App />);
@@ -248,7 +249,7 @@ describe('history traversal and the preview tab slot', () => {
});
test('back to a doc opened as a preview reuses the preview slot instead of appending', async () => {
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
for (const doc of ['page-a', 'page-b', 'page-c']) {
clickDocRow(doc, true);
view.rerender(<App />);
@@ -271,7 +272,7 @@ describe('history traversal and the preview tab slot', () => {
});
test('a re-render between a traversal popstate and its hashchange reuses the preview slot', async () => {
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
for (const doc of ['page-a', 'page-b', 'page-c']) {
clickDocRow(doc, true);
view.rerender(<App />);
@@ -297,7 +298,7 @@ describe('history traversal and the preview tab slot', () => {
});
test('a skill preview stays one reusable tab across a click away and back', async () => {
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
clickSkillPreviewRow(SKILL_PREVIEW, true);
view.rerender(<App />);
@@ -316,7 +317,7 @@ describe('history traversal and the preview tab slot', () => {
});
test('a bundle file clicked inside a preview moves the selection on the same tab', async () => {
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
clickSkillPreviewRow(EXPLORE_PREVIEW, true);
view.rerender(<App />);
@@ -335,7 +336,7 @@ describe('history traversal and the preview tab slot', () => {
test('back to a doc whose tab is still open activates it without appending', async () => {
mergedConfig = { editor: { previewTabs: false } };
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
clickDocRow('page-a', false);
view.rerender(<App />);
@@ -351,7 +352,7 @@ describe('history traversal and the preview tab slot', () => {
});
test('with preview tabs off, back to a closed doc appends instead of taking a slot', async () => {
- const view = render(<App />);
+ const view = render(<App />, { wrapper: TooltipProvider });
clickDocRow('page-a', true);
view.rerender(<App />);
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index f5eb24955..dfb9d990d 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -1,14 +1,25 @@
import { SHOW_INSTALL_SKILL } from '@inkeep/open-knowledge-core/constants/feature-flags';
import { mediaKindForSidebarAssetExtension } from '@inkeep/open-knowledge-core/constants/upload';
-import { lazy, type ReactNode, Suspense, useEffect, useRef, useState } from 'react';
+import {
+ type CSSProperties,
+ lazy,
+ type ReactNode,
+ Suspense,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
import { toast } from 'sonner';
import { CommentQueueShortcut } from '@/comments/CommentQueueShortcut';
+import { APP_HEADER_HEIGHT, AppHeader } from '@/components/AppHeader';
import { BranchRecycleBanner } from '@/components/BranchRecycleBanner';
import { CommandPalette } from '@/components/CommandPalette';
import { ConnectingBanner } from '@/components/ConnectingBanner';
+import { CornerCardStack } from '@/components/CornerCardStack';
import { CreateProjectMenuTrigger } from '@/components/CreateProjectMenuTrigger';
import { EditorPane } from '@/components/EditorPane';
import { FeedbackMenuTrigger } from '@/components/FeedbackMenuTrigger';
+import { FileListHostProvider } from '@/components/FileListHost';
import { FileSidebar } from '@/components/FileSidebar';
import { defaultInitialDir } from '@/components/file-tree-utils';
import { ExternalHandoffGateProvider } from '@/components/handoff/ExternalHandoffGate';
@@ -32,7 +43,7 @@ import { PageListProvider, usePageList } from '@/components/PageListContext';
import { ReportBugMenuTrigger } from '@/components/ReportBugMenuTrigger';
import { SkillTrackInGitDialog } from '@/components/SkillTrackInGitDialog';
import { SystemDocSubscriber } from '@/components/SystemDocSubscriber';
-import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
+import { SidebarProvider } from '@/components/ui/sidebar';
import { ValidationFreshness } from '@/components/ValidationFreshness';
import { BackgroundThrottleReporter } from '@/editor/BackgroundThrottleReporter';
import {
@@ -63,13 +74,17 @@ import {
skillsFromHash,
} from '@/lib/doc-hash';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isExplicitInitialDocumentNavigation } from '@/lib/narrow-workspace-session';
import { isNoteWindow } from '@/lib/note-window-mode';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { mark, ProfilerBoundary } from '@/lib/perf';
+import { revealEditor } from '@/lib/reveal-editor';
import { SingleFileModeProvider, useSingleFileMode } from '@/lib/single-file-mode';
import { consumeHashNavigationSuppression } from '@/lib/tab-session-restore-suppression';
import { useServerKeepalive } from '@/lib/use-server-keepalive';
import { isSettingsHashOpen, isSettingsShortcut, openSettings } from '@/lib/use-settings-route';
+import { cn } from '@/lib/utils';
+import { consumeWorkspaceHashWrite } from '@/lib/workspace-hash-writes';
const ShareBranchSwitchDialog = lazy(() =>
import('@/components/ShareBranchSwitchDialog').then((m) => ({
@@ -156,9 +171,21 @@ function NavigationHandler() {
const previewTabsEnabled = merged?.editor?.previewTabs ?? true;
const lastSyncedTargetsSignatureRef = useRef<string | null>(null);
const historyTraversalUrlRef = useRef<string | null>(null);
+ const initialDocumentNavigationRef = useRef(isExplicitInitialDocumentNavigation());
const lastResolvedSurfaceHashRef = useRef<string | null>(null);
const targetsSignature = knownTargetsSignature(pages, folderPaths, assetPaths, filePaths);
+ useEffect(() => {
+ function revealEditorForDocumentLink(event: MouseEvent) {
+ if (event.defaultPrevented || event.button !== 0) return;
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+ if (!(event.target instanceof Element)) return;
+ if (event.target.closest('a[href^="#/"]') != null) revealEditor();
+ }
+ document.addEventListener('click', revealEditorForDocumentLink);
+ return () => document.removeEventListener('click', revealEditorForDocumentLink);
+ }, []);
+
useEffect(
() =>
subscribeLocalMenuAction((action) => {
@@ -201,7 +228,11 @@ function NavigationHandler() {
useEffect(() => {
if (!tabSessionLoaded && window.okDesktop?.config.mode === 'editor') return;
- syncTargetFromHash(historyTraversalUrlRef.current);
+ if (initialDocumentNavigationRef.current) {
+ initialDocumentNavigationRef.current = false;
+ revealEditor();
+ }
+ syncTargetFromHash(historyTraversalUrlRef.current, false);
function onPopState(event: PopStateEvent) {
historyTraversalUrlRef.current = isManagedHashHistoryState(event.state)
@@ -209,13 +240,17 @@ function NavigationHandler() {
: null;
}
- function onHashChange() {
+ function onHashChange(event: HashChangeEvent) {
const traversedUrl = historyTraversalUrlRef.current;
historyTraversalUrlRef.current = null;
- syncTargetFromHash(traversedUrl);
+ const previousHash = event.oldURL === '' ? '' : new URL(event.oldURL).hash;
+ const workspaceWrote = consumeWorkspaceHashWrite(window.location.hash);
+ const returnedFromDialog =
+ isAuxiliaryDialogHash(previousHash) && traversedUrl === window.location.href;
+ syncTargetFromHash(traversedUrl, !workspaceWrote && !returnedFromDialog);
}
- function syncTargetFromHash(traversedUrl: string | null) {
+ function syncTargetFromHash(traversedUrl: string | null, deliberate: boolean) {
const isHistoryTraversal = traversedUrl === window.location.href;
markCurrentHashHistoryEntry();
const isSurfaceHashRepeat = lastResolvedSurfaceHashRef.current === window.location.hash;
@@ -233,9 +268,11 @@ function NavigationHandler() {
activeTarget.target === target.target &&
selectedPathForNavigationTarget(activeTarget) === selectedPathForNavigationTarget(target)
) {
+ if (deliberate) revealEditor();
return;
}
openTargetTransition(target, {
+ deliberate,
disposition: isHistoryTraversal
? previewOpenDisposition(previewTabsEnabled)
: 'permanent',
@@ -283,7 +320,7 @@ function NavigationHandler() {
}
if (isSurfaceHashRepeat) return;
mark('ok/nav/hash-change', { docName: null, kind: 'skills' });
- openTargetTransition({ kind: 'skills', target: 'skills' });
+ openTargetTransition({ kind: 'skills', target: 'skills' }, { deliberate });
return;
}
const skillPreview = skillPreviewFromHash(window.location.hash);
@@ -562,7 +599,11 @@ function AppBody() {
const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
const singleFile = useSingleFileMode();
const noteWindow = isNoteWindow();
- const showFileSidebar = !singleFile && !noteWindow;
+
+ const showAppHeader = !noteWindow;
+ const appHeaderStyle: CSSProperties | undefined = showAppHeader
+ ? ({ '--ok-app-header-height': APP_HEADER_HEIGHT } as CSSProperties)
+ : undefined;
const installedClis = useInstalledClis();
const terminalLaunch: TerminalLaunchContextValue | null =
@@ -576,7 +617,7 @@ function AppBody() {
: null;
return (
- <>
+ <div data-app-shell="" className="contents" style={appHeaderStyle}>
<ConnectingBanner />
<BranchRecycleBanner />
<PageListProvider>
@@ -616,7 +657,7 @@ function AppBody() {
/>
)}
{}
- {isElectronHost && (
+ {isElectronHost && !showAppHeader && (
<div
aria-hidden="true"
data-testid="editor-window-chrome-drag-strip"
@@ -628,21 +669,25 @@ function AppBody() {
<TerminalLaunchProvider value={terminalLaunch}>
{}
<CommentQueueShortcut />
- <SidebarProvider className="h-screen overflow-hidden">
- {}
- {showFileSidebar && <FileSidebar onOpenSearch={() => setCommandPaletteOpen(true)} />}
- <SidebarInset
- className={
- showFileSidebar
- ? 'h-[calc(100vh-var(--layout-inset-offset))] overflow-hidden'
- : 'h-screen overflow-hidden'
- }
- >
- <EditorPane onOpenSearch={() => setCommandPaletteOpen(true)} />
- </SidebarInset>
+ {showAppHeader && <AppHeader onOpenSearch={() => setCommandPaletteOpen(true)} />}
+ <SidebarProvider className="h-[calc(100vh-var(--ok-app-header-height,0px))] min-h-[calc(100svh-var(--ok-app-header-height,0px))]">
+ <FileListHostProvider enabled={showAppHeader && !singleFile} fileList={<FileSidebar />}>
+ <div
+ data-app-main=""
+ className={cn(
+ 'relative flex w-full flex-1 flex-col',
+ showAppHeader
+ ? 'ps-2 pe-2 pb-2 h-[calc(100vh-var(--ok-app-header-height,0px))]'
+ : 'h-screen overflow-hidden bg-background',
+ )}
+ >
+ <EditorPane />
+ </div>
+ </FileListHostProvider>
</SidebarProvider>
</TerminalLaunchProvider>
+ {showAppHeader && !singleFile && <CornerCardStack />}
</PageListProvider>
- </>
+ </div>
);
}
diff --git a/packages/app/src/build/chrome-tokens-vite-plugin.test.ts b/packages/app/src/build/chrome-tokens-vite-plugin.test.ts
index 03e1e5d01..aeaede2ac 100644
--- a/packages/app/src/build/chrome-tokens-vite-plugin.test.ts
+++ b/packages/app/src/build/chrome-tokens-vite-plugin.test.ts
@@ -1,9 +1,14 @@
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'vitest';
-import { CHROME_BG_DARK, CHROME_BG_LIGHT } from '../../../core/src/constants/chrome.ts';
+import {
+ CANVAS_BG_DARK,
+ CHROME_BG_DARK,
+ CHROME_BG_LIGHT,
+ SIDEBAR_BG_LIGHT,
+} from '../../../core/src/constants/chrome.ts';
import { chromeTokensVitePlugin } from './chrome-tokens-vite-plugin.ts';
const HERE = dirname(fileURLToPath(import.meta.url));
@@ -22,14 +27,14 @@ describe('chromeTokensVitePlugin', () => {
test('transformIndexHtml substitutes both placeholders with the resolved hex', () => {
const html =
- '<style>html { background-color: __OK_CHROME_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style>';
+ '<style>html { background-color: __OK_SIDEBAR_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style>';
const transform = plugin.transformIndexHtml as {
handler: (html: string) => string;
};
const out = transform.handler(html);
- expect(out).toContain(`background-color: ${CHROME_BG_LIGHT}`);
+ expect(out).toContain(`background-color: ${SIDEBAR_BG_LIGHT}`);
expect(out).toContain(`background-color: ${CHROME_BG_DARK}`);
- expect(out).not.toContain('__OK_CHROME_BG_LIGHT__');
+ expect(out).not.toContain('__OK_SIDEBAR_BG_LIGHT__');
expect(out).not.toContain('__OK_CHROME_BG_DARK__');
});
@@ -41,17 +46,51 @@ describe('chromeTokensVitePlugin', () => {
expect(transform.handler(html)).toBe(html);
});
+ test('uninstall page pre-paints its dark canvas rather than the main window frame', () => {
+ const html = readFileSync(resolve(HERE, '../../uninstall.html'), 'utf8');
+ const transform = plugin.transformIndexHtml as {
+ handler: (html: string) => string;
+ };
+ const out = transform.handler(html);
+ expect(out).toContain(`html.dark { background-color: ${CANVAS_BG_DARK} }`);
+ expect(out).not.toContain('__OK_CANVAS_BG_DARK__');
+ expect(CANVAS_BG_DARK).not.toBe(CHROME_BG_DARK);
+ });
+
+ test('the web pre-paint uses the light sidebar while the light frame uses the desk', () => {
+ const html = readFileSync(resolve(HERE, '../../index.html'), 'utf8');
+ const transform = plugin.transformIndexHtml as {
+ handler: (html: string) => string;
+ };
+ const out = transform.handler(html);
+ expect(out).toContain(`html { background-color: ${SIDEBAR_BG_LIGHT} }`);
+ expect(out).toContain(`html.dark { background-color: ${CHROME_BG_DARK} }`);
+ expect(out).not.toMatch(/__OK_[A-Z_]+_BG_[A-Z]+__/);
+ expect(SIDEBAR_BG_LIGHT).toBe('#fafafa');
+ expect(CHROME_BG_LIGHT).toBe('#f5f5f5');
+ });
+
+ test('uninstall page pre-paints the light sidebar', () => {
+ const html = readFileSync(resolve(HERE, '../../uninstall.html'), 'utf8');
+ const transform = plugin.transformIndexHtml as {
+ handler: (html: string) => string;
+ };
+ expect(transform.handler(html)).toContain(`html { background-color: ${SIDEBAR_BG_LIGHT} }`);
+ });
+
test('multiple occurrences of the same placeholder are all replaced', () => {
- const html = '__OK_CHROME_BG_LIGHT__/__OK_CHROME_BG_LIGHT__/__OK_CHROME_BG_DARK__';
+ const html = '__OK_SIDEBAR_BG_LIGHT__/__OK_SIDEBAR_BG_LIGHT__/__OK_CHROME_BG_DARK__';
const transform = plugin.transformIndexHtml as {
handler: (html: string) => string;
};
- expect(transform.handler(html)).toBe(`${CHROME_BG_LIGHT}/${CHROME_BG_LIGHT}/${CHROME_BG_DARK}`);
+ expect(transform.handler(html)).toBe(
+ `${SIDEBAR_BG_LIGHT}/${SIDEBAR_BG_LIGHT}/${CHROME_BG_DARK}`,
+ );
});
});
function sidebarCss(light: string, dark: string): string {
- return `:root {\n --sidebar: ${light};\n}\n.dark {\n --sidebar: ${dark};\n}\n`;
+ return `:root {\n --desk: oklch(from var(--sidebar) calc(l - 0.015) c h);\n --sidebar: ${light};\n}\n.dark {\n --sidebar: ${dark};\n --background: ${dark};\n}\nhtml.dark:not([data-color-theme]) {\n --desk: ${dark};\n}\n`;
}
test('a running dev server serves the --sidebar token the stylesheet holds now, not the one it held at start', () => {
@@ -63,13 +102,13 @@ test('a running dev server serves the --sidebar token the stylesheet holds now,
const buildStart = plugin.buildStart as () => void;
const transform = plugin.transformIndexHtml as { handler: (html: string) => string };
buildStart();
- expect(transform.handler('__OK_CHROME_BG_LIGHT__ __OK_CHROME_BG_DARK__')).toBe(
+ expect(transform.handler('__OK_SIDEBAR_BG_LIGHT__ __OK_CHROME_BG_DARK__')).toBe(
'#fafafa #171717',
);
writeFileSync(cssPath, sidebarCss('oklch(0.9 0 0)', 'oklch(0.205 0 0)'));
- expect(transform.handler('__OK_CHROME_BG_LIGHT__ __OK_CHROME_BG_DARK__')).toBe(
+ expect(transform.handler('__OK_SIDEBAR_BG_LIGHT__ __OK_CHROME_BG_DARK__')).toBe(
'#dedede #171717',
);
} finally {
diff --git a/packages/app/src/build/chrome-tokens-vite-plugin.ts b/packages/app/src/build/chrome-tokens-vite-plugin.ts
index c078d58c2..5baf4049b 100644
--- a/packages/app/src/build/chrome-tokens-vite-plugin.ts
+++ b/packages/app/src/build/chrome-tokens-vite-plugin.ts
@@ -2,8 +2,9 @@ import { resolve } from 'node:path';
import type { Plugin } from 'vite';
import { resolveChromeTokensFromCss } from '../../../core/scripts/chrome-resolver.ts';
-const LIGHT_PLACEHOLDER = '__OK_CHROME_BG_LIGHT__';
+const SIDEBAR_LIGHT_PLACEHOLDER = '__OK_SIDEBAR_BG_LIGHT__';
const DARK_PLACEHOLDER = '__OK_CHROME_BG_DARK__';
+const CANVAS_DARK_PLACEHOLDER = '__OK_CANVAS_BG_DARK__';
interface ChromeTokensPluginOptions {
globalsCssPath?: string;
@@ -24,8 +25,9 @@ export function chromeTokensVitePlugin(options: ChromeTokensPluginOptions = {}):
handler(html: string): string {
const tokens = resolveChromeTokensFromCss(cssPath);
return html
- .replaceAll(LIGHT_PLACEHOLDER, tokens.light)
- .replaceAll(DARK_PLACEHOLDER, tokens.dark);
+ .replaceAll(SIDEBAR_LIGHT_PLACEHOLDER, tokens.lightSidebar)
+ .replaceAll(DARK_PLACEHOLDER, tokens.dark)
+ .replaceAll(CANVAS_DARK_PLACEHOLDER, tokens.darkCanvas);
},
},
};
diff --git a/packages/app/src/comments/CommentListPanel.tsx b/packages/app/src/comments/CommentListPanel.tsx
index 00cddfa13..9ac63d91f 100644
--- a/packages/app/src/comments/CommentListPanel.tsx
+++ b/packages/app/src/comments/CommentListPanel.tsx
@@ -76,12 +76,14 @@ export function CommentListPanel({
empty,
testIdPrefix,
scopeSwitch,
+ onDestinationComplete,
}: {
threads: readonly CommentThread[];
groupByDocument?: boolean;
empty: ReactNode;
testIdPrefix: string;
scopeSwitch?: ReactNode;
+ onDestinationComplete?: (target: HTMLElement) => void;
}) {
const { t } = useLingui();
const [showResolved, setShowResolved] = useState(false);
@@ -158,6 +160,7 @@ export function CommentListPanel({
active={activeId === thread.id}
focused={focusedId === thread.id}
layout={groupByDocument ? 'project' : 'doc'}
+ onDestinationComplete={onDestinationComplete}
cardRef={(el) => {
if (el) cardRefs.current.set(thread.id, el);
else cardRefs.current.delete(thread.id);
diff --git a/packages/app/src/comments/CommentMarginRail.tsx b/packages/app/src/comments/CommentMarginRail.tsx
index 5a8860623..20c94fb62 100644
--- a/packages/app/src/comments/CommentMarginRail.tsx
+++ b/packages/app/src/comments/CommentMarginRail.tsx
@@ -7,6 +7,7 @@ import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Button } from '@/components/ui/button';
import { getEditorView } from '@/editor/utils/get-editor-view';
+import { useEditorPaneOnScreen } from '@/lib/use-editor-pane-on-screen';
import { cn } from '@/lib/utils';
import { createAnchorResolver, findQuoteRange } from './anchor-search';
import {
@@ -90,6 +91,7 @@ export function CommentMarginRail({ editor, docName }: { editor: Editor; docName
const activeId = useOpenThread();
const [rail, setRail] = useState<RailBox | null>(null);
const [positions, setPositions] = useState<MarkerPosition[]>([]);
+ const editorPaneOnScreen = useEditorPaneOnScreen();
useEffect(() => {
const view = getEditorView(editor);
@@ -183,7 +185,7 @@ export function CommentMarginRail({ editor, docName }: { editor: Editor; docName
emitOpenThread(threadId);
}
- if (rail === null || positions.length === 0) return null;
+ if (!editorPaneOnScreen || rail === null || positions.length === 0) return null;
return createPortal(
<div
diff --git a/packages/app/src/comments/CommentProjectPanel.tsx b/packages/app/src/comments/CommentProjectPanel.tsx
index e9cd3477d..5684bfc53 100644
--- a/packages/app/src/comments/CommentProjectPanel.tsx
+++ b/packages/app/src/comments/CommentProjectPanel.tsx
@@ -3,7 +3,13 @@ import type { ReactNode } from 'react';
import { CommentListPanel } from './CommentListPanel';
import { useAllThreads } from './store';
-export function CommentProjectPanel({ scopeSwitch }: { scopeSwitch?: ReactNode }) {
+export function CommentProjectPanel({
+ scopeSwitch,
+ onDestinationComplete,
+}: {
+ scopeSwitch?: ReactNode;
+ onDestinationComplete?: (target: HTMLElement) => void;
+}) {
const threads = useAllThreads();
return (
<CommentListPanel
@@ -12,6 +18,7 @@ export function CommentProjectPanel({ scopeSwitch }: { scopeSwitch?: ReactNode }
empty={<Trans>No comments in this project yet. Comment on a passage to start one.</Trans>}
testIdPrefix="comment-queue"
scopeSwitch={scopeSwitch}
+ onDestinationComplete={onDestinationComplete}
/>
);
}
diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsx
index f695b6168..c14a5fd89 100644
--- a/packages/app/src/comments/CommentSelectionAffordance.tsx
+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx
@@ -19,7 +19,9 @@ import {
SELECTION_SURFACE_GAP_PX,
} from '@/editor/utils/editor-visible-region';
import { getEditorView } from '@/editor/utils/get-editor-view';
+import { focusAwayFromHiddenEditor } from '@/lib/editor-hidden-focus';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { useEditorPaneOnScreen } from '@/lib/use-editor-pane-on-screen';
import { cn } from '@/lib/utils';
import { setCommentDraftRange } from './anchor-decorations';
import { captureSelectionContext } from './anchor-search';
@@ -49,11 +51,12 @@ export function CommentSelectionAffordance({
const [captured, setCaptured] = useState<Captured | null>(null);
const [empty, setEmpty] = useState(true);
const commentsOnScreen = useCommentsPanelOnScreen();
+ const editorPaneOnScreen = useEditorPaneOnScreen();
const inputRef = useRef<ComposerMentionInputHandle>(null);
const floatingRef = useRef<HTMLDivElement>(null);
useEffect(() => {
- if (!shortcutEnabled) return;
+ if (!shortcutEnabled || !editorPaneOnScreen) return;
const onKeyDown = (event: KeyboardEvent): void => {
if (!matchesKeyboardShortcut(event, 'add-comment')) return;
const target = event.target;
@@ -64,7 +67,13 @@ export function CommentSelectionAffordance({
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, [shortcutEnabled, editor]);
+ }, [shortcutEnabled, editorPaneOnScreen, editor]);
+
+ useEffect(() => {
+ if (editorPaneOnScreen) return;
+ const floating = floatingRef.current;
+ if (floating?.contains(document.activeElement)) focusAwayFromHiddenEditor();
+ }, [editorPaneOnScreen]);
useEffect(() => {
return subscribeStartComment(() => {
@@ -170,7 +179,10 @@ export function CommentSelectionAffordance({
return createPortal(
<div
ref={floatingRef}
- className="z-[60] flex w-80 flex-col gap-2 rounded-lg border bg-popover p-3 text-popover-foreground shadow-md"
+ className={cn(
+ 'z-[60] flex w-80 flex-col gap-2 rounded-lg border bg-popover p-3 text-popover-foreground shadow-md',
+ !editorPaneOnScreen && 'hidden',
+ )}
style={{ position: 'fixed', top: 0, left: 0 }}
data-testid="comment-composer"
>
diff --git a/packages/app/src/comments/CommentsPanel.tsx b/packages/app/src/comments/CommentsPanel.tsx
index e0bab8ccd..5495bef1c 100644
--- a/packages/app/src/comments/CommentsPanel.tsx
+++ b/packages/app/src/comments/CommentsPanel.tsx
@@ -8,9 +8,11 @@ import { refresh, useCommentThreads } from './store';
function CommentsPanelInner({
docName,
scopeSwitch,
+ onDestinationComplete,
}: {
docName: string;
scopeSwitch?: ReactNode;
+ onDestinationComplete?: (target: HTMLElement) => void;
}) {
const threads = useCommentThreads(docName);
@@ -24,6 +26,7 @@ function CommentsPanelInner({
empty={<Trans>No comments yet. Select text in the document to add one.</Trans>}
testIdPrefix="comment-doc"
scopeSwitch={scopeSwitch}
+ onDestinationComplete={onDestinationComplete}
/>
);
}
@@ -31,13 +34,19 @@ function CommentsPanelInner({
export function CommentsPanel({
docName,
scopeSwitch,
+ onDestinationComplete,
}: {
docName: string;
scopeSwitch?: ReactNode;
+ onDestinationComplete?: (target: HTMLElement) => void;
}) {
return (
<ProfilerBoundary name="comments-panel">
- <CommentsPanelInner docName={docName} scopeSwitch={scopeSwitch} />
+ <CommentsPanelInner
+ docName={docName}
+ scopeSwitch={scopeSwitch}
+ onDestinationComplete={onDestinationComplete}
+ />
</ProfilerBoundary>
);
}
diff --git a/packages/app/src/comments/CommentsTab.tsx b/packages/app/src/comments/CommentsTab.tsx
index 140b24acb..651f57e85 100644
--- a/packages/app/src/comments/CommentsTab.tsx
+++ b/packages/app/src/comments/CommentsTab.tsx
@@ -6,7 +6,13 @@ import { CommentsPanel } from './CommentsPanel';
import { consumePendingCommentScope, subscribeCommentScopeRequests } from './reveal-queue';
import { setVisibleCommentScope } from './visible-scope';
-export function CommentsTab({ docName }: { docName: string }) {
+export function CommentsTab({
+ docName,
+ onDestinationComplete,
+}: {
+ docName: string;
+ onDestinationComplete?: (target: HTMLElement) => void;
+}) {
const [requestedScope, setRequestedScope] = useState<PanelScope>('doc');
const singleFile = useSingleFileMode();
const scope: PanelScope = singleFile ? 'doc' : requestedScope;
@@ -23,8 +29,12 @@ export function CommentsTab({ docName }: { docName: string }) {
<PanelScopeHeader scope={scope} onScopeChange={setRequestedScope} />
);
return scope === 'doc' ? (
- <CommentsPanel docName={docName} scopeSwitch={scopeSwitch} />
+ <CommentsPanel
+ docName={docName}
+ scopeSwitch={scopeSwitch}
+ onDestinationComplete={onDestinationComplete}
+ />
) : (
- <CommentProjectPanel scopeSwitch={scopeSwitch} />
+ <CommentProjectPanel scopeSwitch={scopeSwitch} onDestinationComplete={onDestinationComplete} />
);
}
diff --git a/packages/app/src/comments/ThreadCard.tsx b/packages/app/src/comments/ThreadCard.tsx
index c3dc6517a..392c1ad74 100644
--- a/packages/app/src/comments/ThreadCard.tsx
+++ b/packages/app/src/comments/ThreadCard.tsx
@@ -3,7 +3,9 @@
import { Trans, useLingui } from '@lingui/react/macro';
import { CheckCheck, MapPin, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
+import { toast } from 'sonner';
import type { PanelScope } from '@/components/PanelScopeHeader';
+import { getPropertiesCollapsed } from '@/components/properties-collapsed-store';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
@@ -13,6 +15,7 @@ import {
ComposerMentionInput,
type ComposerMentionInputHandle,
} from '@/editor/ComposerMentionInput';
+import { getEditorView } from '@/editor/utils/get-editor-view';
import { cn } from '@/lib/utils';
import { captureSelectionContext, findQuoteRange } from './anchor-search';
import { propertyAddress, revealThread } from './comment-chips';
@@ -60,6 +63,7 @@ export function ThreadCard({
active,
sending,
layout,
+ onDestinationComplete,
}: {
thread: CommentThread;
cardRef: (el: HTMLElement | null) => void;
@@ -67,6 +71,7 @@ export function ThreadCard({
active: boolean;
sending: boolean;
layout: PanelScope;
+ onDestinationComplete?: (target: HTMLElement) => void;
}) {
const { t } = useLingui();
const [renderedAt] = useState(() => Date.now());
@@ -122,29 +127,47 @@ export function ThreadCard({
};
}, [editing]);
+ function reportPassageMissing() {
+ toast.error(t`Couldn't find that passage — the text it was on may have changed.`);
+ }
+
function jumpToQuote(quote: string) {
if (thread.anchor === null) return;
if (getVisibleEditorForDoc(thread.docName) === null) {
- revealThread(thread);
+ revealThread(thread, onDestinationComplete);
return;
}
if (thread.target.kind === 'property') {
- revealPropertyValueRange({
+ const target = revealPropertyValueRange({
key: thread.target.key,
path: thread.target.path,
quote,
start: thread.anchor.start,
end: thread.anchor.end,
});
+ if (!target) {
+ if (getPropertiesCollapsed()) revealThread(thread, onDestinationComplete);
+ else reportPassageMissing();
+ return;
+ }
emitOpenThread(thread.id);
+ onDestinationComplete?.(target);
return;
}
const editor = getVisibleEditorForDoc(thread.docName);
if (!editor) return;
const range = findQuoteRange(editor.state.doc, quote, thread.anchor);
- if (!range) return;
- scrollAnchorIntoView(editor, range, thread.docName);
+ if (!range) {
+ reportPassageMissing();
+ return;
+ }
+ if (!scrollAnchorIntoView(editor, range, thread.docName)) {
+ revealThread(thread, onDestinationComplete);
+ return;
+ }
emitOpenThread(thread.id);
+ const target = getEditorView(editor)?.dom;
+ if (target) onDestinationComplete?.(target);
}
function rePlaceOnSelection() {
diff --git a/packages/app/src/comments/comment-chips.tsx b/packages/app/src/comments/comment-chips.tsx
index d1f1fa198..d13475496 100644
--- a/packages/app/src/comments/comment-chips.tsx
+++ b/packages/app/src/comments/comment-chips.tsx
@@ -3,6 +3,7 @@
import { graphemePrefix, graphemeSuffix } from '@inkeep/open-knowledge-core/utils/grapheme-clip';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { MessageSquare, X } from 'lucide-react';
+import { setPropertiesCollapsed } from '@/components/properties-collapsed-store';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
@@ -117,34 +118,33 @@ export function propertyAddress(key: string, path: readonly (string | number)[])
return out;
}
-export function revealThread(thread: CommentThread): void {
+export function revealThread(
+ thread: CommentThread,
+ onDestinationComplete?: (target: HTMLElement) => void,
+): void {
+ const { target, anchor } = thread;
+ if (target.kind === 'property') setPropertiesCollapsed(false);
+ const resolveTarget =
+ target.kind === 'property' && anchor !== null
+ ? () =>
+ revealPropertyValueRange({
+ key: target.key,
+ path: target.path,
+ quote: anchor.quote,
+ start: anchor.start,
+ end: anchor.end,
+ })
+ : undefined;
revealComment({
docName: thread.docName,
- quote: thread.target.kind === 'property' ? '' : (thread.anchor?.quote ?? ''),
+ quote: target.kind === 'property' ? '' : (anchor?.quote ?? ''),
threadId: thread.id,
- context: thread.anchor ?? undefined,
+ context: anchor ?? undefined,
+ onDestinationComplete,
+ resolveTarget,
});
- const { target, anchor } = thread;
- if (target.kind !== 'property' || anchor === null) return;
- let attempts = 0;
- const attempt = (): void => {
- const done = revealPropertyValueRange({
- key: target.key,
- path: target.path,
- quote: anchor.quote,
- start: anchor.start,
- end: anchor.end,
- });
- if (done) return;
- attempts += 1;
- if (attempts >= REVEAL_FRAME_BUDGET) return;
- requestAnimationFrame(attempt);
- };
- requestAnimationFrame(attempt);
}
-const REVEAL_FRAME_BUDGET = 30;
-
export interface CommentBatchItem {
docName: string;
body: string;
diff --git a/packages/app/src/comments/comment-composer-submit.dom.test.tsx b/packages/app/src/comments/comment-composer-submit.dom.test.tsx
index 2cdc172a0..8578fb59c 100644
--- a/packages/app/src/comments/comment-composer-submit.dom.test.tsx
+++ b/packages/app/src/comments/comment-composer-submit.dom.test.tsx
@@ -1,7 +1,7 @@
import * as actualLinguiMacro from '@lingui/react/macro';
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterEach, describe, expect, onTestFinished, test, vi } from 'vitest';
import { mentionRecencyAttribute } from '@/components/acp/composer-mention-input.test-helper';
vi.doMock('@lingui/react/macro', () => ({
@@ -83,6 +83,7 @@ vi.doMock('@/components/doc-panel-events', () => ({
vi.doMock('./store', () => ({
createThread: (args: CreateArgs) => captured.created.push(args),
+ emitStartComment: () => captured.startComment?.(),
subscribeStartComment: (cb: () => void) => {
captured.startComment = cb;
return () => {
@@ -264,3 +265,51 @@ describe('what the comment @ picker is told to list first', () => {
});
});
});
+
+describe('the comment composer while the editor is hidden', () => {
+ async function hideEditorPane() {
+ const { paneVisibilityStore } = await import('@/lib/pane-visibility-store');
+ act(() =>
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ }),
+ );
+ }
+
+ afterEach(async () => {
+ const { __resetPaneVisibilityStoreForTests } = await import('@/lib/pane-visibility-store');
+ __resetPaneVisibilityStoreForTests();
+ });
+
+ test('the comment shortcut starts no composer while the editor is off screen', async () => {
+ await hideEditorPane();
+ const { CommentSelectionAffordance } = await import('./CommentSelectionAffordance');
+ // biome-ignore lint/suspicious/noExplicitAny: structural editor double
+ const editor = fakeEditor() as any;
+ render(
+ <CommentSelectionAffordance editor={editor} docName="recipes/stir-fry" shortcutEnabled />,
+ );
+
+ fireEvent.keyDown(window, { key: 'm', ctrlKey: true, shiftKey: true });
+
+ expect(screen.queryByPlaceholderText('Add a comment')).toBeNull();
+ });
+
+ test('hiding the editor with focus in the composer moves focus to the Editor button', async () => {
+ const editorButton = document.createElement('button');
+ editorButton.setAttribute('data-header-pane-button', 'editor');
+ document.body.append(editorButton);
+ onTestFinished(() => editorButton.remove());
+ const field = await openComposer();
+ act(() => field.focus());
+ expect(document.activeElement).toBe(field);
+ expect(screen.getByTestId('comment-composer').classList.contains('hidden')).toBe(false);
+
+ await hideEditorPane();
+
+ expect(document.activeElement).toBe(editorButton);
+ expect(screen.getByTestId('comment-composer').classList.contains('hidden')).toBe(true);
+ });
+});
diff --git a/packages/app/src/comments/comment-hue-contrast.test.ts b/packages/app/src/comments/comment-hue-contrast.test.ts
index 47c997f27..61a3c753b 100644
--- a/packages/app/src/comments/comment-hue-contrast.test.ts
+++ b/packages/app/src/comments/comment-hue-contrast.test.ts
@@ -11,7 +11,7 @@ const RESTING_LINE_ALPHA = 0.7;
const CANVASES = {
light: { rgb: [255, 255, 255], decl: 'oklch(1 0 0)' },
- dark: { rgb: [10, 10, 10], decl: 'oklch(0.145 0 0)' },
+ dark: { rgb: [21, 21, 21], decl: 'oklch(0.195 0 0)' },
} as const;
type Rgb = readonly [number, number, number] | number[];
@@ -50,7 +50,7 @@ function hue(declaration: string): number[] {
}
describe('comment highlight hue', () => {
- test('canvas declarations are unchanged', () => {
+ test('canvas declarations match the contrast calculation', () => {
const backgrounds = declarations('--background');
expect(backgrounds[0]).toBe(CANVASES.light.decl);
expect(backgrounds[1]).toBe(CANVASES.dark.decl);
diff --git a/packages/app/src/comments/property-row-rect.ts b/packages/app/src/comments/property-row-rect.ts
index aae71f9e9..41a8a4c6a 100644
--- a/packages/app/src/comments/property-row-rect.ts
+++ b/packages/app/src/comments/property-row-rect.ts
@@ -30,8 +30,8 @@ export function revealPropertyValueRange(args: {
quote: string;
start?: number;
end?: number;
-}): boolean {
- if (args.quote === '') return false;
+}): HTMLElement | null {
+ if (args.quote === '') return null;
const lastStep = args.path.length === 0 ? args.key : args.path[args.path.length - 1];
const preferred = Array.from(
document.querySelectorAll<HTMLElement>(
@@ -48,9 +48,9 @@ export function revealPropertyValueRange(args: {
control.focus();
control.setSelectionRange(range.start, range.end);
paintRevealSelection(control);
- return true;
+ return control;
}
- return false;
+ return null;
}
export function locateInValue(
diff --git a/packages/app/src/comments/reveal-comment.dom.test.ts b/packages/app/src/comments/reveal-comment.dom.test.ts
index 18cb73916..e665fa2c2 100644
--- a/packages/app/src/comments/reveal-comment.dom.test.ts
+++ b/packages/app/src/comments/reveal-comment.dom.test.ts
@@ -192,6 +192,31 @@ describe('revealing a comment', () => {
expect(toasted[0]).toMatch(/passage/i);
});
+ test('a found passage whose scroll stays refused says it could not be reached, not that it changed', () => {
+ editor = makeEditor('press the tofu first');
+ scrollAllowed = false;
+
+ reveal();
+ expect(captured.focused).toEqual(['t1']);
+
+ vi.advanceTimersByTime(REVEAL_WAIT_MS + RETRY_MS);
+ expect(captured.opened).toEqual([]);
+ expect(toasted).toHaveLength(1);
+ expect(toasted[0]).toMatch(/scroll to that passage/i);
+ expect(toasted[0]).not.toMatch(/changed/i);
+ });
+
+ test('a passage that disappears after it was found is still reported missing', () => {
+ editor = makeEditor('press the tofu first');
+ scrollAllowed = false;
+
+ reveal();
+ if (editor) editor.state.doc.text = 'press it first';
+ vi.advanceTimersByTime(REVEAL_WAIT_MS + RETRY_MS);
+ expect(toasted).toHaveLength(1);
+ expect(toasted[0]).toMatch(/may have changed/i);
+ });
+
test('names the document, not the passage, when the document never came up', () => {
editor = makeEditor('press the tofu first');
editorVisible = false;
diff --git a/packages/app/src/comments/reveal-comment.ts b/packages/app/src/comments/reveal-comment.ts
index 0ff08d938..c8f776add 100644
--- a/packages/app/src/comments/reveal-comment.ts
+++ b/packages/app/src/comments/reveal-comment.ts
@@ -2,6 +2,7 @@ import { t } from '@lingui/core/macro';
import { toast } from 'sonner';
import { requestDocPanelTab } from '@/components/doc-panel-events';
import { getVisibleEditorForDoc, subscribeEditorRegistry } from '@/editor/active-editor';
+import { getEditorView } from '@/editor/utils/get-editor-view';
import { hashFromDocName } from '@/lib/doc-hash';
import { type AnchorContext, findQuoteRange } from './anchor-search';
import { scrollAnchorIntoView } from './scroll-to-anchor';
@@ -20,8 +21,11 @@ export function revealComment(input: {
quote: string;
threadId: string;
context?: AnchorContext;
+ onDestinationComplete?: (target: HTMLElement) => void;
+ resolveTarget?: () => HTMLElement | null;
}): void {
let announced = false;
+ let found = false;
let landedAt: number | null = null;
let range: { from: number; to: number } | null = null;
let sizeAtLastFind = -1;
@@ -34,10 +38,12 @@ export function revealComment(input: {
emitFocusThread(input.threadId);
}
if (input.quote === '') {
- if (landedAt === null) {
- landedAt = Date.now();
- emitOpenThread(input.threadId);
- }
+ if (landedAt !== null) return true;
+ const target = input.resolveTarget ? input.resolveTarget() : getEditorView(editor)?.dom;
+ if (input.resolveTarget && !target) return false;
+ landedAt = Date.now();
+ emitOpenThread(input.threadId);
+ if (target) input.onDestinationComplete?.(target);
return true;
}
const size = editor.state.doc.content.size;
@@ -45,11 +51,14 @@ export function revealComment(input: {
range = findQuoteRange(editor.state.doc, input.quote, input.context);
sizeAtLastFind = size;
}
+ found = range !== null;
if (!range) return false;
if (!scrollAnchorIntoView(editor, range, input.docName, { instant: true })) return false;
if (landedAt === null) {
landedAt = Date.now();
emitOpenThread(input.threadId);
+ const target = getEditorView(editor)?.dom;
+ if (target) input.onDestinationComplete?.(target);
}
return true;
};
@@ -58,7 +67,9 @@ export function revealComment(input: {
attempt();
if (getVisibleEditorForDoc(input.docName) === null) {
- window.location.assign(hashFromDocName(input.docName));
+ if (input.resolveTarget || input.onDestinationComplete) {
+ window.location.hash = hashFromDocName(input.docName);
+ } else window.location.assign(hashFromDocName(input.docName));
}
let settled = false;
@@ -79,9 +90,11 @@ export function revealComment(input: {
const deadline = window.setTimeout(() => {
if (landedAt === null) {
toast.error(
- announced
- ? t`Couldn't find that passage — the text it was on may have changed.`
- : t`That document didn't open in time. Try again once it has synced.`,
+ !announced
+ ? t`That document didn't open in time. Try again once it has synced.`
+ : found
+ ? t`Couldn't scroll to that passage. Try again.`
+ : t`Couldn't find that passage — the text it was on may have changed.`,
);
}
stop();
diff --git a/packages/app/src/comments/reveal-thread.dom.test.ts b/packages/app/src/comments/reveal-thread.dom.test.ts
new file mode 100644
index 000000000..c8673c59e
--- /dev/null
+++ b/packages/app/src/comments/reveal-thread.dom.test.ts
@@ -0,0 +1,49 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import type { CommentThread } from './types';
+
+const revealComment = vi.fn();
+
+vi.doMock('./reveal-comment', () => ({ revealComment }));
+
+const { revealThread } = await import('./comment-chips');
+const { __resetPropertiesCollapsedForTests, getPropertiesCollapsed, setPropertiesCollapsed } =
+ await import('@/components/properties-collapsed-store');
+
+const bodyThread: CommentThread = {
+ id: 't1',
+ docName: 'recipes/stir-fry',
+ target: { kind: 'body' },
+ anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },
+ status: 'open',
+ body: 'press it?',
+ createdAt: 1000,
+ updatedAt: 1000,
+ queued: true,
+};
+
+const propertyThread: CommentThread = {
+ ...bodyThread,
+ id: 't2',
+ target: { kind: 'property', key: 'servings', path: [] },
+};
+
+afterEach(() => {
+ revealComment.mockClear();
+ __resetPropertiesCollapsedForTests();
+});
+
+describe('revealing a comment thread', () => {
+ test('a property comment expands collapsed Properties before it resolves its row', () => {
+ setPropertiesCollapsed(true);
+ revealThread(propertyThread);
+ expect(getPropertiesCollapsed()).toBe(false);
+ expect(revealComment).toHaveBeenCalledTimes(1);
+ });
+
+ test('a body comment leaves Properties as they were', () => {
+ setPropertiesCollapsed(true);
+ revealThread(bodyThread);
+ expect(getPropertiesCollapsed()).toBe(true);
+ expect(revealComment).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/comments/thread-card-jump-miss.dom.test.tsx b/packages/app/src/comments/thread-card-jump-miss.dom.test.tsx
new file mode 100644
index 000000000..12d8b0511
--- /dev/null
+++ b/packages/app/src/comments/thread-card-jump-miss.dom.test.tsx
@@ -0,0 +1,123 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { CommentThread } from './types';
+
+const toastError = vi.fn();
+const scrolled = { result: true };
+const quoteRange = { value: null as { from: number; to: number } | null };
+const propertyTarget = { value: null as HTMLElement | null };
+const revealThread = vi.fn();
+
+vi.doMock('sonner', () => ({ toast: { error: toastError } }));
+
+vi.doMock('@/editor/active-editor', () => ({
+ getVisibleEditorForDoc: () => ({ state: { doc: {} } }),
+}));
+
+vi.doMock('./anchor-search', () => ({
+ captureSelectionContext: () => null,
+ findQuoteRange: () => quoteRange.value,
+}));
+
+vi.doMock('./scroll-to-anchor', () => ({
+ scrollAnchorIntoView: () => scrolled.result,
+}));
+
+vi.doMock('./property-row-rect', () => ({
+ revealPropertyValueRange: () => propertyTarget.value,
+}));
+
+vi.doMock('./comment-chips', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./comment-chips')>()),
+ revealThread,
+}));
+
+vi.doMock('./store', () => ({
+ clearActiveThread: () => {},
+ deleteThread: () => {},
+ editComment: () => {},
+ emitOpenThread: () => {},
+ reopenThread: () => {},
+ replaceOrphan: () => {},
+ setActiveThread: () => {},
+ toggleSending: () => {},
+}));
+
+const { ThreadCard } = await import('./ThreadCard');
+const { __resetPropertiesCollapsedForTests, setPropertiesCollapsed } = await import(
+ '@/components/properties-collapsed-store'
+);
+
+const thread: CommentThread = {
+ id: 't1',
+ docName: 'recipes/stir-fry',
+ target: { kind: 'body' },
+ anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },
+ status: 'open',
+ body: 'press it?',
+ createdAt: 1000,
+ updatedAt: 1000,
+ queued: true,
+};
+
+const propertyThread: CommentThread = {
+ ...thread,
+ id: 't2',
+ target: { kind: 'property', key: 'servings', path: [] },
+};
+
+function clickQuote(clicked: CommentThread = thread) {
+ render(
+ <TooltipProvider>
+ <ThreadCard
+ layout="doc"
+ thread={clicked}
+ cardRef={() => {}}
+ focused={false}
+ active={false}
+ sending={false}
+ />
+ </TooltipProvider>,
+ );
+ const row = screen.getByText(/the tofu/).closest('button');
+ expect(row).not.toBeNull();
+ if (row) fireEvent.click(row);
+}
+
+beforeEach(() => {
+ toastError.mockClear();
+ revealThread.mockClear();
+ scrolled.result = true;
+ quoteRange.value = null;
+ propertyTarget.value = null;
+});
+
+afterEach(() => {
+ cleanup();
+ __resetPropertiesCollapsedForTests();
+});
+
+describe('jumping to a comment quote in the open document', () => {
+ test('an unfound quote says so instead of doing nothing', () => {
+ clickQuote();
+ expect(toastError).toHaveBeenCalledWith(
+ "Couldn't find that passage — the text it was on may have changed.",
+ );
+ });
+
+ test('a found quote whose scroll is refused retries the reveal instead of saying it changed', () => {
+ quoteRange.value = { from: 1, to: 9 };
+ scrolled.result = false;
+ clickQuote();
+ expect(toastError).not.toHaveBeenCalled();
+ expect(revealThread).toHaveBeenCalledWith(thread, undefined);
+ });
+
+ test('a property quote under collapsed Properties retries the reveal instead of saying it changed', () => {
+ setPropertiesCollapsed(true);
+ clickQuote(propertyThread);
+ expect(toastError).not.toHaveBeenCalled();
+ expect(revealThread).toHaveBeenCalledWith(propertyThread, undefined);
+ });
+});
diff --git a/packages/app/src/comments/thread-card-property-miss.dom.test.tsx b/packages/app/src/comments/thread-card-property-miss.dom.test.tsx
new file mode 100644
index 000000000..de1d9a154
--- /dev/null
+++ b/packages/app/src/comments/thread-card-property-miss.dom.test.tsx
@@ -0,0 +1,110 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { CommentThread } from './types';
+
+const toastError = vi.fn();
+
+vi.doMock('sonner', () => ({ toast: { error: toastError } }));
+
+vi.doMock('@/components/doc-panel-events', () => ({ requestDocPanelTab: () => {} }));
+
+vi.doMock('@/editor/active-editor', () => ({
+ getVisibleEditorForDoc: () => ({ state: { doc: { content: { size: 0 } } }, isDestroyed: false }),
+ subscribeEditorRegistry: () => () => {},
+}));
+
+vi.doMock('./store', () => ({
+ clearActiveThread: () => {},
+ deleteThread: () => {},
+ editComment: () => {},
+ emitFocusThread: () => {},
+ emitOpenThread: () => {},
+ reopenThread: () => {},
+ replaceOrphan: () => {},
+ setActiveThread: () => {},
+ toggleSending: () => {},
+}));
+
+const { ThreadCard } = await import('./ThreadCard');
+const { __resetPropertiesCollapsedForTests, getPropertiesCollapsed, setPropertiesCollapsed } =
+ await import('@/components/properties-collapsed-store');
+
+const MISSING = "Couldn't find that passage — the text it was on may have changed.";
+
+const thread: CommentThread = {
+ id: 't2',
+ docName: 'recipes/stir-fry',
+ target: { kind: 'property', key: 'servings', path: [] },
+ anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },
+ status: 'open',
+ body: 'press it?',
+ createdAt: 1000,
+ updatedAt: 1000,
+ queued: true,
+};
+
+function renderPropertyRow(value: string): HTMLInputElement {
+ const row = document.createElement('div');
+ row.dataset.testid = 'property-row';
+ row.dataset.key = 'servings';
+ const input = document.createElement('input');
+ input.value = value;
+ row.append(input);
+ document.body.append(row);
+ return input;
+}
+
+function clickQuote() {
+ render(
+ <TooltipProvider>
+ <ThreadCard
+ layout="doc"
+ thread={thread}
+ cardRef={() => {}}
+ focused={false}
+ active={false}
+ sending={false}
+ />
+ </TooltipProvider>,
+ );
+ const row = screen.getByText(/the tofu/).closest('button');
+ expect(row).not.toBeNull();
+ if (row) fireEvent.click(row);
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ toastError.mockClear();
+});
+
+afterEach(() => {
+ cleanup();
+ for (const row of document.querySelectorAll('[data-testid="property-row"]')) row.remove();
+ __resetPropertiesCollapsedForTests();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('jumping to a property comment', () => {
+ test('a shown property whose value no longer holds the quote says so at once', () => {
+ const input = renderPropertyRow('4 people');
+ clickQuote();
+ expect(input.value).toBe('4 people');
+ expect(toastError).toHaveBeenCalledWith(MISSING);
+ });
+
+ test('expanded Properties with no rows left, after the last property was deleted, says so at once', () => {
+ setPropertiesCollapsed(false);
+ clickQuote();
+ expect(document.querySelector('[data-testid="property-row"]')).toBeNull();
+ expect(toastError).toHaveBeenCalledWith(MISSING);
+ });
+
+ test('collapsed Properties is expanded and revealed instead of reported missing', () => {
+ setPropertiesCollapsed(true);
+ clickQuote();
+ expect(getPropertiesCollapsed()).toBe(false);
+ expect(toastError).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/ActivityModeContent.tsx b/packages/app/src/components/ActivityModeContent.tsx
index 3702ee98a..1d662962d 100644
--- a/packages/app/src/components/ActivityModeContent.tsx
+++ b/packages/app/src/components/ActivityModeContent.tsx
@@ -297,8 +297,10 @@ function ActivityModeBody({
export function ActivityModeContent({
showBackButton = true,
+ onDestinationRequested,
}: {
showBackButton?: boolean;
+ onDestinationRequested?: (docName: string) => void;
} = {}): React.JSX.Element {
const { t } = useLingui();
const { docPanelAgentId, closeActivityPanel } = useDocumentContext();
@@ -318,6 +320,7 @@ export function ActivityModeContent({
}
const onNavigate = (docName: string): void => {
+ onDestinationRequested?.(docName);
openTargetTransition(
withLargeFileOpenGuard({ kind: 'doc', target: docName, docName }, pageMeta),
{ disposition: 'permanent', consumeActiveNewTab: true },
diff --git a/packages/app/src/components/AgentDiffPane.destination.dom.test.tsx b/packages/app/src/components/AgentDiffPane.destination.dom.test.tsx
new file mode 100644
index 000000000..490cb3eb0
--- /dev/null
+++ b/packages/app/src/components/AgentDiffPane.destination.dom.test.tsx
@@ -0,0 +1,84 @@
+// @vitest-environment jsdom
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+let releasePresent: (() => void) | undefined;
+
+const fetchAgentBurstDiff = vi.fn((agentId: string) => {
+ if (agentId === 'missing') return Promise.reject(new Error('burst diff unavailable'));
+ return new Promise((resolve) => {
+ releasePresent = () =>
+ resolve({
+ diff: '',
+ before: 'base line\n',
+ after: 'present line\n',
+ properties: { changes: [], unparseable: null },
+ });
+ });
+});
+
+vi.doMock('@/lib/use-activity-panel', () => ({ fetchAgentBurstDiff }));
+
+vi.doMock('@/components/RenderedDiffView', async (importOriginal) => {
+ const mod = await importOriginal<typeof import('@/components/RenderedDiffView')>();
+ return {
+ ...mod,
+ computeRenderedDiff: () => ({ ok: false as const }),
+ RenderedDiffView: () => null,
+ };
+});
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: (s: string) => s }),
+}));
+
+const { AgentDiffPane } = await import('@/components/AgentDiffPane');
+const { TooltipProvider } = await import('@/components/ui/tooltip');
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ releasePresent = undefined;
+});
+
+describe('AgentDiffPane destination settlement', () => {
+ test('a failed selection does not settle the next selection as failed', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onDestinationComplete = vi.fn();
+ const onDestinationFailed = vi.fn();
+ const pane = (agentId: string) => (
+ <TooltipProvider>
+ <AgentDiffPane
+ view={{
+ agentId,
+ agentName: 'Agent',
+ agentColor: '#888888',
+ docName: 'notes',
+ keptCount: 1,
+ maxVersions: 3,
+ }}
+ isPanelCollapsed={false}
+ onTogglePanel={() => {}}
+ onDestinationComplete={onDestinationComplete}
+ onDestinationFailed={onDestinationFailed}
+ />
+ </TooltipProvider>
+ );
+
+ const { rerender } = render(pane('missing'));
+ await waitFor(() => expect(onDestinationFailed).toHaveBeenCalledTimes(1));
+
+ rerender(pane('present'));
+ await waitFor(() => expect(releasePresent).toBeDefined());
+ expect(onDestinationFailed).toHaveBeenCalledTimes(1);
+ releasePresent?.();
+
+ await waitFor(() => expect(onDestinationComplete).toHaveBeenCalledTimes(1));
+ expect(onDestinationFailed).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/components/AgentDiffPane.tsx b/packages/app/src/components/AgentDiffPane.tsx
index ea32bcda1..f9c57958e 100644
--- a/packages/app/src/components/AgentDiffPane.tsx
+++ b/packages/app/src/components/AgentDiffPane.tsx
@@ -3,7 +3,7 @@
import type { FrontmatterDelta } from '@inkeep/open-knowledge-core/frontmatter-diff';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { PanelRightClose, PanelRightOpen, X } from 'lucide-react';
-import { lazy, Suspense, useEffect, useRef, useState } from 'react';
+import { lazy, Suspense, useEffect, useEffectEvent, useRef, useState } from 'react';
import { PropertyDiffBlock } from '@/components/PropertyDiffBlock';
import { computeRenderedDiff, RenderedDiffView } from '@/components/RenderedDiffView';
import { Button } from '@/components/ui/button';
@@ -36,25 +36,60 @@ interface AgentDiffPaneProps {
view: AgentDiffView;
isPanelCollapsed: boolean;
onTogglePanel: () => void;
+ onDestinationComplete?: (target?: HTMLElement) => void;
+ onDestinationFailed?: () => void;
}
-export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDiffPaneProps) {
+export function AgentDiffPane({
+ view,
+ isPanelCollapsed,
+ onTogglePanel,
+ onDestinationComplete,
+ onDestinationFailed,
+}: AgentDiffPaneProps) {
const { t } = useLingui();
const { agentId, agentName, agentColor, agentIcon, docName, keptCount } = view;
const [cache] = useState(() => new LruStringCache(VERSION_DIFF_CACHE_LIMIT));
const diffBodyRef = useRef<HTMLDivElement>(null);
+ const closeButtonRef = useRef<HTMLButtonElement>(null);
const [renderMode, setRenderMode] = useState<'rendered' | 'source'>('rendered');
const [result, setResult] = useState<{
status: 'loading' | 'ready' | 'error';
+ key: string | null;
diff: string;
before: string;
after: string;
properties: FrontmatterDelta;
- }>({ status: 'loading', diff: '', before: '', after: '', properties: EMPTY_DELTA });
+ }>({ status: 'loading', key: null, diff: '', before: '', after: '', properties: EMPTY_DELTA });
+
+ const currentKey = `${agentId}\0${docName}\0${keptCount}`;
+ const completeDestination = useEffectEvent(() => {
+ onDestinationComplete?.(closeButtonRef.current ?? undefined);
+ });
+ const failDestination = useEffectEvent(() => onDestinationFailed?.());
+ const settledRequestRef = useRef<AgentDiffView | null>(null);
+ useEffect(() => {
+ if (settledRequestRef.current === view) return;
+ if (result.key !== currentKey) return;
+ if (result.status === 'ready') {
+ settledRequestRef.current = view;
+ completeDestination();
+ } else if (result.status === 'error') {
+ settledRequestRef.current = view;
+ failDestination();
+ }
+ }, [result, currentKey, view]);
useEffect(() => {
let cancelled = false;
- setResult({ status: 'loading', diff: '', before: '', after: '', properties: EMPTY_DELTA });
+ setResult({
+ status: 'loading',
+ key: null,
+ diff: '',
+ before: '',
+ after: '',
+ properties: EMPTY_DELTA,
+ });
const key = `${agentId}\0${docName}\0${keptCount}`;
const cached = cache.get(key);
if (cached !== undefined) {
@@ -64,14 +99,14 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDi
after: string;
properties: FrontmatterDelta;
};
- setResult({ status: 'ready', ...parsed });
+ setResult({ status: 'ready', key, ...parsed });
return;
}
fetchAgentBurstDiff(agentId, docName, keptCount)
.then((data) => {
if (cancelled) return;
cache.set(key, JSON.stringify(data));
- setResult({ status: 'ready', ...data });
+ setResult({ status: 'ready', key, ...data });
})
.catch((err) => {
if (!cancelled) {
@@ -81,7 +116,14 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDi
keptCount,
err,
});
- setResult({ status: 'error', diff: '', before: '', after: '', properties: EMPTY_DELTA });
+ setResult({
+ status: 'error',
+ key,
+ diff: '',
+ before: '',
+ after: '',
+ properties: EMPTY_DELTA,
+ });
}
});
return () => {
@@ -190,6 +232,7 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDi
<Tooltip>
<TooltipTrigger asChild>
<Button
+ ref={closeButtonRef}
variant="ghost"
size="icon"
className="size-7 shrink-0"
diff --git a/packages/app/src/components/AppHeader.auth-prompt.dom.test.tsx b/packages/app/src/components/AppHeader.auth-prompt.dom.test.tsx
new file mode 100644
index 000000000..f6350aba7
--- /dev/null
+++ b/packages/app/src/components/AppHeader.auth-prompt.dom.test.tsx
@@ -0,0 +1,108 @@
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { AppHeader } from '@/components/AppHeader';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
+import { authPromptStore } from '@/lib/auth-prompt-store';
+
+const sync = vi.hoisted(() => ({ status: null as GitSyncStatus | null }));
+
+vi.mock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName: 'docs/notes',
+ activeTarget: { kind: 'doc' },
+ activeProvider: null,
+ }),
+}));
+
+vi.mock('@/hooks/use-git-sync-status', () => ({
+ useGitSyncStatusDetailed: () => ({ status: sync.status, fetchError: null }),
+ useGitSyncStatus: () => sync.status,
+}));
+
+vi.mock('@/hooks/use-conflicts', () => ({
+ useConflicts: () => ({ conflicts: [], loading: false, error: null, refresh: () => {} }),
+}));
+
+vi.mock('@/hooks/use-git-worktree-status', () => ({
+ useGitWorktreeStatus: () => ({
+ status: null,
+ loading: false,
+ unreadable: true,
+ stale: false,
+ lastReadAt: null,
+ }),
+}));
+
+vi.mock('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ projectLocalConfig: { autoSync: { enabled: false } },
+ projectLocalSynced: true,
+ projectLocalBinding: { patch: () => ({ ok: true as const }) },
+ }),
+}));
+
+vi.mock('@/presence/PresenceBar', () => ({
+ PresenceBar: () => null,
+}));
+
+vi.mock('@/presence/use-sync-toasts', () => ({
+ useSyncToasts: () => {},
+}));
+
+vi.mock('@/components/HelpPopover', () => ({
+ HelpPopover: () => null,
+}));
+
+vi.mock('@/components/PublishToGitHubDialog', () => ({
+ PublishToGitHubDialog: () => null,
+}));
+
+const connectedStatus: GitSyncStatus = {
+ state: 'idle',
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ ahead: 0,
+ behind: 0,
+ conflictCount: 0,
+ hasRemote: true,
+ syncEnabled: true,
+ remote: { label: 'inkeep/open-knowledge', webUrl: 'https://github.com/inkeep/open-knowledge' },
+};
+
+async function openSyncPopover() {
+ render(<AppHeader onOpenSearch={() => {}} />, { wrapper: TooltipProvider });
+ await userEvent.click(screen.getByRole('button', { name: /^Sync status:/ }));
+}
+
+afterEach(() => {
+ cleanup();
+ authPromptStore.clear();
+ sync.status = null;
+});
+
+describe('AppHeader sync prompts', () => {
+ test('Sign in from the header sync popover asks for the sign-in step', async () => {
+ sync.status = {
+ ...connectedStatus,
+ state: 'auth-error',
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-401',
+ };
+ await openSyncPopover();
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Sign in' }));
+
+ expect(authPromptStore.getSnapshot()).toBe('auth');
+ });
+
+ test('Set identity from the header sync popover asks for the identity step', async () => {
+ sync.status = { ...connectedStatus, identityUnresolved: true };
+ await openSyncPopover();
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Set identity' }));
+
+ expect(authPromptStore.getSnapshot()).toBe('identity');
+ });
+});
diff --git a/packages/app/src/components/AppHeader.dom.test.tsx b/packages/app/src/components/AppHeader.dom.test.tsx
new file mode 100644
index 000000000..5c6aa60a2
--- /dev/null
+++ b/packages/app/src/components/AppHeader.dom.test.tsx
@@ -0,0 +1,1416 @@
+import { getParseHealth, resetParseHealth } from '@inkeep/open-knowledge-core';
+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ComponentProps, ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { APP_HEADER_HEIGHT, AppHeader } from '@/components/AppHeader';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
+import { ConfigContext } from '@/lib/config-context';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibility,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
+import {
+ configContextWithTerminal,
+ type ProjectTerminalSetting,
+ TERMINAL_SETTING_UNSET,
+} from '@/test-utils/config-context';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const searchRender = vi.hoisted(() => ({ throws: false }));
+const shell = vi.hoisted(() => ({
+ singleFile: false,
+ activeDocName: 'docs/notes' as string | null,
+ activeTarget: { kind: 'doc' } as unknown,
+ syncStatus: null as Partial<GitSyncStatus> | null,
+ syncToastHosts: 0,
+}));
+
+vi.mock('@/lib/single-file-mode', () => ({
+ useSingleFileMode: () => shell.singleFile,
+}));
+
+vi.mock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName: shell.activeDocName,
+ activeTarget: shell.activeTarget,
+ activeProvider: null,
+ }),
+}));
+
+vi.mock('@/hooks/use-git-sync-status', () => ({
+ useGitSyncStatusDetailed: () => ({ status: shell.syncStatus, fetchError: null }),
+ useGitSyncStatus: () => shell.syncStatus,
+}));
+
+vi.mock('@/presence/use-sync-toasts', async () => {
+ const { useEffect } = await vi.importActual<typeof import('react')>('react');
+ return {
+ useSyncToasts: () => {
+ useEffect(() => {
+ shell.syncToastHosts += 1;
+ return () => {
+ shell.syncToastHosts -= 1;
+ };
+ }, []);
+ },
+ };
+});
+
+vi.mock('@/presence/PresenceBar', () => ({
+ PresenceBar: () => <div data-testid="presence-bar" />,
+}));
+
+vi.mock('@/components/SyncStatusBadge', async () => ({
+ ...(await vi.importActual<typeof import('@/components/SyncStatusBadge')>(
+ '@/components/SyncStatusBadge',
+ )),
+ SyncStatusBadge: () => <div data-testid="sync-status-badge" />,
+}));
+
+vi.mock('@/components/HelpPopover', () => ({
+ HelpPopover: () => <button type="button">Resources</button>,
+}));
+
+vi.mock('@/components/PublishToGitHubDialog', () => ({
+ PublishToGitHubDialog: ({ open }: { open: boolean }) => (
+ <div data-testid="publish-dialog" data-open={String(open)} />
+ ),
+}));
+
+vi.mock('@/components/HeaderSearchBar', async () => {
+ const actual = await vi.importActual<typeof import('@/components/HeaderSearchBar')>(
+ '@/components/HeaderSearchBar',
+ );
+ return {
+ ...actual,
+ HeaderSearchBar: (props: ComponentProps<typeof actual.HeaderSearchBar>) => {
+ if (searchRender.throws) throw new Error('search button render failed');
+ return <actual.HeaderSearchBar {...props} />;
+ },
+ };
+});
+
+interface DesktopHostOptions {
+ platform?: string;
+ channel?: 'latest' | 'beta';
+ instanceLabel?: string;
+ menu?: { dispatch: (request: { kind: string }) => Promise<unknown> };
+}
+
+function setElectronHost(
+ enabled: boolean,
+ { platform, channel = 'latest', instanceLabel, menu }: DesktopHostOptions = {},
+) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: enabled
+ ? {
+ platform,
+ instanceLabel,
+ menu,
+ config: {
+ mode: 'editor',
+ projectName: 'Field Notes',
+ projectPath: '/projects/field-notes',
+ },
+ state: { query: () => Promise.resolve({ channel }) },
+ project: { listRecent: () => Promise.resolve([]) },
+ worktree: { list: () => Promise.resolve({ ok: false, reason: 'no-git' }) },
+ }
+ : undefined,
+ });
+}
+
+const onOpenSearch = vi.fn(() => {});
+
+let projectTerminal: ProjectTerminalSetting = TERMINAL_SETTING_UNSET;
+
+function HeaderProviders({ children }: { children: ReactNode }) {
+ return (
+ <ConfigContext value={configContextWithTerminal(projectTerminal)}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </ConfigContext>
+ );
+}
+
+function renderHeader() {
+ return render(<AppHeader onOpenSearch={onOpenSearch} />, { wrapper: HeaderProviders });
+}
+
+function centreGroup(): HTMLElement {
+ return screen.getByRole('banner').querySelector('[data-app-header-center]') as HTMLElement;
+}
+
+function leadingGroup(): HTMLElement {
+ return screen.getByRole('banner').querySelector('[data-app-header-leading]') as HTMLElement;
+}
+
+function trailingGroup(): HTMLElement {
+ return screen.getByRole('banner').querySelector('[data-app-header-trailing]') as HTMLElement;
+}
+
+interface HeaderMetrics {
+ header: number;
+ leading: number;
+ compactBadgeLeading?: number;
+ badgeLabel?: number;
+ badges?: { beta?: number; instance?: number };
+ trailing: number;
+ collapsedTrailing?: number;
+ paneButton?: number;
+ switcher?: number;
+ switcherName?: number;
+}
+
+function mockHeaderMetrics(source: HeaderMetrics | (() => HeaderMetrics)) {
+ const read = typeof source === 'function' ? source : () => source;
+ const scrollWidth = vi
+ .spyOn(Element.prototype, 'scrollWidth', 'get')
+ .mockImplementation(function (this: Element) {
+ const metrics = read();
+ return this.hasAttribute('data-instance-badge-label') ? (metrics.badgeLabel ?? 0) : 0;
+ });
+ const offsetWidth = vi
+ .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
+ .mockImplementation(function (this: HTMLElement) {
+ const metrics = read();
+ if (this.hasAttribute('data-app-header')) return metrics.header;
+ if (this.hasAttribute('data-app-header-leading')) {
+ const badgeCompact = this.querySelector('[data-instance-badge-label].sr-only') !== null;
+ const width =
+ badgeCompact && metrics.compactBadgeLeading !== undefined
+ ? metrics.compactBadgeLeading
+ : metrics.leading;
+ let foldedAway = 0;
+ if (this.querySelector('[data-testid="beta-badge"]') === null) {
+ foldedAway += metrics.badges?.beta ?? 0;
+ }
+ if (this.querySelector('[data-testid="instance-badge"]') === null) {
+ foldedAway += metrics.badges?.instance ?? 0;
+ }
+ return width - foldedAway;
+ }
+ if (this.hasAttribute('data-app-header-badges')) {
+ let width = 0;
+ if (this.querySelector('[data-testid="beta-badge"]') !== null) {
+ width += metrics.badges?.beta ?? 0;
+ }
+ if (this.querySelector('[data-testid="instance-badge"]') !== null) {
+ const compact = this.querySelector('[data-instance-badge-label].sr-only') !== null;
+ width += (metrics.badges?.instance ?? 0) - (compact ? (metrics.badgeLabel ?? 0) : 0);
+ }
+ return width;
+ }
+ if (this.hasAttribute('data-app-header-trailing')) {
+ const collapsed =
+ this.querySelector('[data-testid="header-overflow-actions-trigger"]') !== null;
+ const paneRow =
+ this.querySelectorAll('[data-testid^="header-pane-button-"]').length *
+ (metrics.paneButton ?? 0);
+ return (
+ (collapsed && metrics.collapsedTrailing !== undefined
+ ? metrics.collapsedTrailing
+ : metrics.trailing) + paneRow
+ );
+ }
+ if (this.getAttribute('data-testid') === 'project-switcher-trigger') {
+ return metrics.switcher ?? 0;
+ }
+ if (this.getAttribute('data-testid') === 'project-switcher-name') {
+ return metrics.switcherName ?? 0;
+ }
+ return 0;
+ });
+ return () => {
+ offsetWidth.mockRestore();
+ scrollWidth.mockRestore();
+ };
+}
+
+function captureResizeObserver() {
+ const observers: Array<{ callback: ResizeObserverCallback; targets: Set<Element> }> = [];
+ const original = globalThis.ResizeObserver;
+ class CapturingResizeObserver {
+ private readonly entry: { callback: ResizeObserverCallback; targets: Set<Element> };
+ constructor(callback: ResizeObserverCallback) {
+ this.entry = { callback, targets: new Set<Element>() };
+ observers.push(this.entry);
+ }
+ observe(target: Element) {
+ this.entry.targets.add(target);
+ }
+ unobserve(target: Element) {
+ this.entry.targets.delete(target);
+ }
+ disconnect() {
+ this.entry.targets.clear();
+ }
+ }
+ globalThis.ResizeObserver = CapturingResizeObserver as unknown as typeof ResizeObserver;
+ return {
+ flush(target?: Element) {
+ for (const { callback, targets } of observers) {
+ if (target !== undefined && !targets.has(target)) continue;
+ act(() => {
+ callback([], {} as ResizeObserver);
+ });
+ }
+ },
+ restore() {
+ globalThis.ResizeObserver = original;
+ },
+ };
+}
+
+function overflowTrigger(): HTMLElement | null {
+ return screen.queryByTestId('header-overflow-actions-trigger');
+}
+
+async function openOverflowPanel(): Promise<HTMLElement> {
+ await userEvent.click(screen.getByTestId('header-overflow-actions-trigger'));
+ return await waitFor(() => {
+ const panel = document.querySelector('[data-header-overflow-actions]');
+ expect(panel, 'the overflow trigger must open a panel').not.toBeNull();
+ return panel as HTMLElement;
+ });
+}
+
+const TRAILING_ACTION_QUERIES = [
+ () => screen.queryByTestId('presence-bar'),
+ () => screen.queryByRole('button', { name: /^Share / }),
+ () => screen.queryByTestId('sync-status-badge'),
+ () => screen.queryByRole('button', { name: 'Settings' }),
+ () => screen.queryByRole('button', { name: 'Resources' }),
+] as const;
+
+const FOLDING_BADGES = '[data-testid="beta-badge"], [data-testid="instance-badge"]';
+
+const PANE_HIDDEN: PaneVisibility = { open: false, onScreen: false };
+
+function publishPanes({ terminal = true }: { terminal?: boolean } = {}) {
+ act(() => {
+ paneVisibilityStore.publish({
+ editor: null,
+ agents: PANE_HIDDEN,
+ terminal: terminal ? PANE_HIDDEN : null,
+ });
+ });
+}
+
+function paneControls(): HTMLElement[] {
+ return [
+ screen.getByTestId('header-pane-divider'),
+ screen.getByRole('button', { name: 'Agents' }),
+ screen.getByRole('button', { name: 'Terminal' }),
+ ];
+}
+
+const CRAMPED: HeaderMetrics = { header: 600, leading: 220, trailing: 420, collapsedTrailing: 44 };
+const ROOMY: HeaderMetrics = { header: 1_280, leading: 220, trailing: 420 };
+const BADGES_FOLD: HeaderMetrics = {
+ header: 600,
+ leading: 300,
+ compactBadgeLeading: 200,
+ badgeLabel: 100,
+ badges: { beta: 40, instance: 150 },
+ trailing: 480,
+ collapsedTrailing: 44,
+};
+const BADGE_CRAMPED: HeaderMetrics = {
+ header: 700,
+ leading: 300,
+ compactBadgeLeading: 200,
+ badgeLabel: 100,
+ trailing: 420,
+};
+
+function follows(earlier: Element, later: Element): boolean {
+ return (earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
+}
+
+afterEach(() => {
+ cleanup();
+ setElectronHost(false);
+ onOpenSearch.mockClear();
+ searchRender.throws = false;
+ shell.activeDocName = 'docs/notes';
+ shell.activeTarget = { kind: 'doc' };
+ shell.syncStatus = null;
+ shell.syncToastHosts = 0;
+ shell.singleFile = false;
+ __resetPaneVisibilityStoreForTests();
+ projectTerminal = TERMINAL_SETTING_UNSET;
+ vi.unstubAllGlobals();
+});
+
+describe('AppHeader', () => {
+ test('a single-file window keeps global actions and the component selector above its cards', async () => {
+ shell.singleFile = true;
+ setElectronHost(true, { platform: 'win32', menu: { dispatch: async () => null } });
+ act(() => {
+ paneVisibilityStore.publish({
+ editor: { open: true, onScreen: true },
+ agents: PANE_HIDDEN,
+ terminal: PANE_HIDDEN,
+ });
+ });
+ renderHeader();
+
+ expect(screen.getByRole('banner', { name: 'Application' })).toBeTruthy();
+ expect(screen.getByTestId('presence-bar')).toBeTruthy();
+ expect(screen.getByTestId('sync-status-badge')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Resources' })).toBeTruthy();
+ expect(await screen.findByTestId('app-menubar')).toBeTruthy();
+ expect(screen.getByRole('group', { name: 'Panels' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Editor' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Agents' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Terminal' })).toBeTruthy();
+ expect(screen.queryByTestId('project-switcher-trigger')).toBeNull();
+ expect(screen.queryByRole('button', { name: /^Search/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: /^Share/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Settings' })).toBeNull();
+ expect(screen.queryByTestId('publish-dialog')).toBeNull();
+ expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
+ });
+
+ test('a narrow single-file header folds secondary actions while keeping the selector visible', async () => {
+ shell.singleFile = true;
+ setElectronHost(true, { platform: 'win32' });
+ publishPanes();
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+ const trailing = trailingGroup();
+ const trigger = screen.getByTestId('header-overflow-actions-trigger');
+ const selector = screen.getByRole('group', { name: 'Panels' });
+ expect(trailing.contains(selector)).toBe(true);
+ expect(follows(trigger, selector)).toBe(true);
+ const panel = await openOverflowPanel();
+ expect(panel.contains(screen.getByRole('button', { name: 'Resources' }))).toBe(true);
+ expect(panel.querySelector('[data-testid="presence-bar"]')).not.toBeNull();
+ expect(panel.querySelector('[data-testid="sync-status-badge"]')).not.toBeNull();
+ expect(panel.contains(selector)).toBe(false);
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('exposes a single banner landmark with an accessible name', () => {
+ renderHeader();
+
+ const banners = screen.getAllByRole('banner');
+ expect(banners).toHaveLength(1);
+ expect(screen.getByRole('banner', { name: 'Application' })).toBe(banners[0]);
+ });
+
+ test('lays out a leading, centre and trailing group in reading order', () => {
+ renderHeader();
+
+ const header = screen.getByRole('banner');
+ const groups = Array.from(header.children).map((child) =>
+ child.getAttributeNames().find((name) => name.startsWith('data-app-header-')),
+ );
+
+ expect(groups).toEqual([
+ 'data-app-header-leading',
+ 'data-app-header-center',
+ 'data-app-header-trailing',
+ ]);
+ });
+
+ test('takes its height from the app-header height property the shell publishes', () => {
+ renderHeader();
+
+ expectVisualClassTokens(screen.getByRole('banner').className, [
+ `h-[var(--ok-app-header-height,${APP_HEADER_HEIGHT})]`,
+ ]);
+ });
+
+ test('paints the shell chrome surface with no rule under it', () => {
+ renderHeader();
+
+ const header = screen.getByRole('banner');
+ expectVisualClassTokens(header.className, ['bg-desk']);
+ expectVisualClassTokensAbsent(header.className, [
+ 'bg-background',
+ 'shadow-[inset_0_-1px_0_var(--border)]',
+ ]);
+ });
+
+ test('reserves the macOS window buttons plus a 10px gap at its leading edge', () => {
+ renderHeader();
+
+ expectVisualClassTokens(leadingGroup().className, [
+ 'ps-[calc(var(--ok-titlebar-reserve-left,0px)+0.625rem)]',
+ ]);
+ });
+
+ test('is a window-drag region on Electron and opts its controls out of dragging', () => {
+ setElectronHost(true);
+ renderHeader();
+
+ const header = screen.getByRole('banner');
+ expect(header.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(header.className, [
+ '[-webkit-app-region:drag]',
+ '[&_button]:[-webkit-app-region:no-drag]',
+ '[&_a]:[-webkit-app-region:no-drag]',
+ ]);
+ });
+
+ test('on Electron the pane buttons opt out of dragging and the divider beside them stays draggable', () => {
+ setElectronHost(true);
+ publishPanes();
+ renderHeader();
+
+ const header = screen.getByRole('banner');
+ for (const name of ['Agents', 'Terminal']) {
+ const button = screen.getByRole('button', { name });
+ expect(header.contains(button)).toBe(true);
+ expect(button.tagName, `${name} must be a <button> for the header's no-drag rule`).toBe(
+ 'BUTTON',
+ );
+ }
+ const divider = screen.getByTestId('header-pane-divider');
+ expect(header.contains(divider)).toBe(true);
+ for (
+ let node: HTMLElement | null = divider;
+ node && node !== header;
+ node = node.parentElement
+ ) {
+ expect(['BUTTON', 'A']).not.toContain(node.tagName);
+ expectVisualClassTokensAbsent(node.className, ['[-webkit-app-region:no-drag]']);
+ }
+ });
+
+ test('reserves the Windows caption-button inset at its trailing edge on Electron', () => {
+ setElectronHost(true, { platform: 'win32' });
+ renderHeader();
+
+ const trailing = screen.getByRole('banner').querySelector('[data-app-header-trailing]');
+ expectVisualClassTokens(trailing?.className, ['me-[var(--ok-titlebar-reserve-right,0px)]']);
+ });
+
+ test('claims no drag region on a web host', () => {
+ renderHeader();
+
+ const header = screen.getByRole('banner');
+ expect(header.getAttribute('data-electron-drag')).toBeNull();
+ expectVisualClassTokensAbsent(header.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokensAbsent(header.querySelector('[data-app-header-trailing]')?.className, [
+ 'me-[var(--ok-titlebar-reserve-right,0px)]',
+ ]);
+ });
+
+ describe('leading group', () => {
+ test('puts back, forward and search in the leading group, in that order, on desktop', () => {
+ setElectronHost(true);
+ renderHeader();
+
+ const leading = leadingGroup();
+ const back = screen.getByRole('button', { name: 'Back' });
+ const forward = screen.getByRole('button', { name: 'Forward' });
+ const search = screen.getByRole('button', { name: 'Search' });
+
+ expect(leading.contains(back)).toBe(true);
+ expect(leading.contains(forward)).toBe(true);
+ expect(leading.contains(search)).toBe(true);
+ expect(follows(back, forward)).toBe(true);
+ expect(follows(forward, search)).toBe(true);
+ });
+
+ test('a web host gets search alone, with no navigation history', () => {
+ renderHeader();
+
+ expect(leadingGroup().contains(screen.getByRole('button', { name: 'Search' }))).toBe(true);
+ expect(screen.queryByRole('button', { name: 'Back' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Forward' })).toBeNull();
+ });
+
+ test('search opens the command palette and keeps its shortcut hint', async () => {
+ const user = userEvent.setup();
+ renderHeader();
+
+ const search = screen.getByRole('button', { name: 'Search' });
+ await user.hover(search);
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.querySelector('[data-slot="kbd"]')).not.toBeNull();
+
+ await user.click(search);
+ expect(onOpenSearch).toHaveBeenCalledTimes(1);
+ });
+
+ test.each([
+ { channel: 'latest', instanceLabel: undefined, expected: [] },
+ { channel: 'beta', instanceLabel: undefined, expected: ['beta-badge'] },
+ { channel: 'latest', instanceLabel: 'wt-header', expected: ['instance-badge'] },
+ { channel: 'beta', instanceLabel: 'wt-header', expected: ['beta-badge', 'instance-badge'] },
+ ] as const)(
+ 'channel $channel with instance label $instanceLabel shows $expected after search',
+ async ({ channel, instanceLabel, expected }) => {
+ setElectronHost(true, { channel, instanceLabel });
+ renderHeader();
+
+ const search = screen.getByRole('button', { name: 'Search' });
+ const searchSlot = Array.from(leadingGroup().children).find((child) =>
+ child.contains(search),
+ ) as Element;
+ await waitFor(() => {
+ const badges = Array.from(leadingGroup().querySelectorAll('[data-testid$="-badge"]'));
+ expect(badges.map((badge) => badge.getAttribute('data-testid'))).toEqual(expected);
+ });
+ const badgeGroup = searchSlot.nextElementSibling;
+ expect(badgeGroup, 'the badge group must follow search').not.toBeNull();
+ expect(badgeGroup?.nextElementSibling ?? null).toBeNull();
+ expect(
+ Array.from(badgeGroup?.children ?? []).map((badge) => badge.getAttribute('data-testid')),
+ ).toEqual(expected);
+ },
+ );
+
+ test('on Windows the app menu leads the header, before search and the badges, and opens from it', async () => {
+ const user = userEvent.setup();
+ const dispatch = vi.fn((request: { kind: string }) =>
+ Promise.resolve(request.kind === 'query' ? null : undefined),
+ );
+ setElectronHost(true, {
+ platform: 'win32',
+ channel: 'beta',
+ instanceLabel: 'wt-header',
+ menu: { dispatch },
+ });
+ renderHeader();
+
+ const menubar = await screen.findByTestId('app-menubar');
+ expect(leadingGroup().firstElementChild).toBe(menubar);
+ expect(follows(menubar, screen.getByRole('button', { name: 'Search' }))).toBe(true);
+ expect(follows(menubar, await screen.findByTestId('beta-badge'))).toBe(true);
+ expect(follows(menubar, screen.getByTestId('instance-badge'))).toBe(true);
+
+ await user.click(screen.getByRole('menuitem', { name: 'File' }));
+ expect(await screen.findByRole('menuitem', { name: /^New file/ })).toBeTruthy();
+ expect(dispatch).toHaveBeenCalledWith({ kind: 'query' });
+ });
+
+ test('macOS leaves the app menu to the native menu bar', async () => {
+ setElectronHost(true, {
+ platform: 'darwin',
+ menu: { dispatch: () => Promise.resolve(null) },
+ });
+ renderHeader();
+
+ await screen.findByRole('button', { name: 'Search' });
+ expect(screen.queryByTestId('app-menubar')).toBeNull();
+ });
+
+ test('a search button render failure is counted and leaves the rest of the header standing', () => {
+ resetParseHealth();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ searchRender.throws = true;
+ setElectronHost(true);
+ try {
+ renderHeader();
+
+ expect(screen.queryByRole('button', { name: 'Search' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'Back' })).toBeTruthy();
+ expect(screen.getByRole('banner', { name: 'Application' })).toBeTruthy();
+ expect(getParseHealth().jsxRenderFailure.headerSearchPill).toBe(1);
+ } finally {
+ consoleError.mockRestore();
+ consoleWarn.mockRestore();
+ }
+ });
+
+ test('the search button comes back once the open document changes', () => {
+ resetParseHealth();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ searchRender.throws = true;
+ setElectronHost(true);
+ try {
+ const rendered = renderHeader();
+ expect(screen.queryByRole('button', { name: 'Search' })).toBeNull();
+
+ searchRender.throws = false;
+ shell.activeDocName = 'docs/other';
+ rendered.rerender(<AppHeader onOpenSearch={onOpenSearch} />);
+
+ expect(
+ screen.queryByRole('button', { name: 'Search' }),
+ 'one render failure removed the search button for the life of the window',
+ ).not.toBeNull();
+ } finally {
+ consoleError.mockRestore();
+ consoleWarn.mockRestore();
+ }
+ });
+ });
+
+ describe('centre track', () => {
+ test('holds the project switcher, named for the open project, on desktop', () => {
+ setElectronHost(true);
+ renderHeader();
+
+ const trigger = screen.getByRole('button', { name: 'Open project menu' });
+ expect(centreGroup().contains(trigger)).toBe(true);
+ expect(trigger.textContent).toContain('Field Notes');
+ });
+
+ test('stays empty on a web host', () => {
+ renderHeader();
+
+ expect(centreGroup().children).toHaveLength(0);
+ expect(screen.queryByRole('button', { name: 'Open project menu' })).toBeNull();
+ });
+ });
+
+ describe('trailing group', () => {
+ test('holds presence, Share, sync, settings and resources, then a divider and the Agents and Terminal buttons, in that order', () => {
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ publishPanes();
+ renderHeader();
+
+ const controls = [...TRAILING_ACTION_QUERIES.map((query) => query()), ...paneControls()];
+ for (const control of controls) {
+ expect(control).not.toBeNull();
+ expect(trailingGroup().contains(control)).toBe(true);
+ }
+ for (let index = 1; index < controls.length; index += 1) {
+ expect(follows(controls[index - 1] as Element, controls[index] as Element)).toBe(true);
+ }
+ });
+
+ test('Share opens the publish dialog from the header when the project has no remote', async () => {
+ const user = userEvent.setup();
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: false };
+ renderHeader();
+
+ expect(screen.getByTestId('publish-dialog').getAttribute('data-open')).toBe('false');
+ await user.click(screen.getByRole('button', { name: 'Share doc' }));
+
+ expect(screen.getByTestId('publish-dialog').getAttribute('data-open')).toBe('true');
+ expect(trailingGroup().contains(screen.getByTestId('publish-dialog'))).toBe(true);
+ });
+
+ test.each([
+ {
+ target: 'an open doc',
+ activeDocName: 'docs/notes',
+ activeTarget: { kind: 'doc' },
+ button: 'Share doc',
+ request: { kind: 'doc', docPath: 'docs/notes.md' },
+ },
+ {
+ target: 'a selected folder',
+ activeDocName: null,
+ activeTarget: { kind: 'folder', folderPath: 'guides' },
+ button: 'Share folder',
+ request: { kind: 'folder', folderPath: 'guides' },
+ },
+ {
+ target: 'nothing open or selected',
+ activeDocName: null,
+ activeTarget: null,
+ button: 'Share folder',
+ request: { kind: 'folder', folderPath: '' },
+ },
+ ])(
+ 'Share asks for a link to $target',
+ async ({ activeDocName, activeTarget, button, request }) => {
+ const user = userEvent.setup();
+ const requests: unknown[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_url: string, init?: RequestInit) => {
+ requests.push(JSON.parse(String(init?.body)));
+ return new Response('unavailable', { status: 503 });
+ }),
+ );
+ shell.activeDocName = activeDocName;
+ shell.activeTarget = activeTarget;
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ renderHeader();
+
+ await user.click(screen.getByRole('button', { name: button }));
+
+ await waitFor(() => expect(requests).toEqual([request]));
+ },
+ );
+
+ test.each([
+ {
+ target: 'a skill or template',
+ activeDocName: '__skill__/project/my-skill',
+ activeTarget: { kind: 'doc' },
+ },
+ {
+ target: 'an asset',
+ activeDocName: null,
+ activeTarget: { kind: 'asset', assetPath: 'img/logo.png' },
+ },
+ ])('Share stays disabled for $target', ({ activeDocName, activeTarget }) => {
+ shell.activeDocName = activeDocName;
+ shell.activeTarget = activeTarget;
+ renderHeader();
+
+ const share = within(trailingGroup()).getByRole('button', { name: /^Share / });
+ expect((share as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ test('mounts the sync-toast machine exactly once, outside the collapsible group', () => {
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).not.toBeNull();
+ expect(screen.queryByTestId('presence-bar')).toBeNull();
+ expect(shell.syncToastHosts).toBe(1);
+ } finally {
+ restoreMetrics();
+ }
+ });
+ });
+
+ describe('collapse', () => {
+ test('when the trailing group does not fit, its five controls go behind "More actions" and the leading group keeps everything but the BETA and instance badges', async () => {
+ setElectronHost(true, {
+ platform: 'win32',
+ channel: 'beta',
+ instanceLabel: 'wt-header',
+ menu: { dispatch: () => Promise.resolve(null) },
+ });
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ const trigger = overflowTrigger();
+ expect(trigger).not.toBeNull();
+ expect(trailingGroup().contains(trigger)).toBe(true);
+ for (const query of TRAILING_ACTION_QUERIES) expect(query()).toBeNull();
+ const staying = [
+ await screen.findByTestId('app-menubar'),
+ ...['Back', 'Forward', 'Search'].map((name) => screen.getByRole('button', { name })),
+ ];
+ for (const control of staying) expect(leadingGroup().contains(control)).toBe(true);
+
+ const panel = await openOverflowPanel();
+ for (const query of TRAILING_ACTION_QUERIES) {
+ expect(panel.contains(query())).toBe(true);
+ }
+ expect(panel.contains(await screen.findByTestId('beta-badge'))).toBe(true);
+ expect(panel.contains(screen.getByTestId('instance-badge'))).toBe(true);
+ for (const control of staying) {
+ expect(panel.contains(control)).toBe(false);
+ expect(leadingGroup().contains(control)).toBe(true);
+ }
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('the panel behind "More actions" is a dialog announced by that name, even while sync needs attention', async () => {
+ shell.syncStatus = { state: 'conflict', conflictCount: 1, hasRemote: true };
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ const panel = await openOverflowPanel();
+ expect(screen.getByRole('dialog', { name: 'More actions' })).toBe(panel);
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('when folded, the divider and the pane buttons stay in the header after "More actions" and out of its panel, and keep their place when room returns', async () => {
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ publishPanes();
+ const observer = captureResizeObserver();
+ let restoreMetrics = mockHeaderMetrics({ ...CRAMPED, paneButton: 28 });
+ try {
+ renderHeader();
+
+ const trigger = overflowTrigger() as HTMLElement;
+ expect(trigger).not.toBeNull();
+ for (const control of paneControls()) {
+ expect(trailingGroup().contains(control)).toBe(true);
+ expect(follows(trigger, control)).toBe(true);
+ }
+ const panel = await openOverflowPanel();
+ for (const query of TRAILING_ACTION_QUERIES) {
+ expect(panel.contains(query())).toBe(true);
+ }
+ for (const control of paneControls()) {
+ expect(panel.contains(control)).toBe(false);
+ }
+
+ restoreMetrics();
+ restoreMetrics = mockHeaderMetrics({ ...ROOMY, paneButton: 28 });
+ observer.flush();
+
+ expect(overflowTrigger()).toBeNull();
+ const controls = [...TRAILING_ACTION_QUERIES.map((query) => query()), ...paneControls()];
+ for (const control of controls) {
+ expect(trailingGroup().contains(control)).toBe(true);
+ }
+ for (let index = 1; index < controls.length; index += 1) {
+ expect(follows(controls[index - 1] as Element, controls[index] as Element)).toBe(true);
+ }
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test.each(['win32', 'linux'] as const)(
+ 'on %s a folded header moves the BETA and instance badges into "More actions", and they return to the leading group when room returns',
+ async (platform) => {
+ setElectronHost(true, { platform, channel: 'beta', instanceLabel: 'wt-header' });
+ const observer = captureResizeObserver();
+ let restoreMetrics = mockHeaderMetrics(BADGES_FOLD);
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).not.toBeNull();
+ expect(leadingGroup().querySelector(FOLDING_BADGES)).toBeNull();
+ const panel = await openOverflowPanel();
+ expect(panel.contains(await screen.findByTestId('beta-badge'))).toBe(true);
+ const folded = screen.getByTestId('instance-badge');
+ expect(panel.contains(folded)).toBe(true);
+ expectVisualClassTokensAbsent(
+ folded.querySelector('[data-instance-badge-label]')?.className,
+ ['sr-only'],
+ );
+
+ restoreMetrics();
+ restoreMetrics = mockHeaderMetrics({ ...BADGES_FOLD, header: 1_280 });
+ observer.flush();
+
+ expect(overflowTrigger()).toBeNull();
+ const beta = await screen.findByTestId('beta-badge');
+ const instance = screen.getByTestId('instance-badge');
+ expect(leadingGroup().contains(beta)).toBe(true);
+ expect(leadingGroup().contains(instance)).toBe(true);
+ expect(follows(screen.getByRole('button', { name: 'Search' }), beta)).toBe(true);
+ expect(follows(beta, instance)).toBe(true);
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ },
+ );
+
+ test('on macOS a folded header keeps the BETA and instance badges in the leading group', async () => {
+ setElectronHost(true, { platform: 'darwin', channel: 'beta', instanceLabel: 'wt-header' });
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).not.toBeNull();
+ const beta = await screen.findByTestId('beta-badge');
+ expect(leadingGroup().contains(beta)).toBe(true);
+ expect(leadingGroup().contains(screen.getByTestId('instance-badge'))).toBe(true);
+ const panel = await openOverflowPanel();
+ expect(panel.querySelector(FOLDING_BADGES)).toBeNull();
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('on macOS a folded single-file header moves the BETA and instance badges into its overflow', async () => {
+ shell.singleFile = true;
+ setElectronHost(true, { platform: 'darwin', channel: 'beta', instanceLabel: 'wt-header' });
+ publishPanes();
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).not.toBeNull();
+ const panel = await openOverflowPanel();
+ expect(panel.contains(await screen.findByTestId('beta-badge'))).toBe(true);
+ expect(panel.contains(screen.getByTestId('instance-badge'))).toBe(true);
+ expect(leadingGroup().querySelector(FOLDING_BADGES)).toBeNull();
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test.each([
+ { path: 'straight from a roomy header', widths: [600] },
+ { path: 'after the instance badge shrank to its icon', widths: [680, 600] },
+ ])(
+ 'with the badges folded out of the leading group $path, the fold holds though the leading group got narrower',
+ async ({ widths }) => {
+ setElectronHost(true, { platform: 'win32', channel: 'beta', instanceLabel: 'wt-header' });
+ const observer = captureResizeObserver();
+ let headerWidth = 1_280;
+ const restoreMetrics = mockHeaderMetrics(() => ({
+ ...BADGES_FOLD,
+ header: headerWidth,
+ trailing: 420,
+ }));
+ try {
+ renderHeader();
+ await waitFor(() =>
+ expect(leadingGroup().contains(screen.queryByTestId('beta-badge'))).toBe(true),
+ );
+ observer.flush();
+ expect(overflowTrigger()).toBeNull();
+
+ for (const width of widths) {
+ headerWidth = width;
+ observer.flush();
+ }
+ expect(overflowTrigger()).not.toBeNull();
+ expect(leadingGroup().querySelector(FOLDING_BADGES)).toBeNull();
+
+ for (const pass of [1, 2, 3]) {
+ observer.flush();
+ expect(
+ overflowTrigger(),
+ `re-measurement pass ${pass} unfolded the header because the folded badges no longer counted against the room`,
+ ).not.toBeNull();
+ }
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ },
+ );
+
+ test('when room returns the five come back out and the trigger goes', () => {
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ const observer = captureResizeObserver();
+ let restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+ expect(overflowTrigger()).not.toBeNull();
+
+ restoreMetrics();
+ restoreMetrics = mockHeaderMetrics(ROOMY);
+ observer.flush();
+
+ expect(overflowTrigger()).toBeNull();
+ for (const query of TRAILING_ACTION_QUERIES) {
+ expect(trailingGroup().contains(query())).toBe(true);
+ }
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('keeps the trailing group inline when it fits', () => {
+ const restoreMetrics = mockHeaderMetrics(ROOMY);
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).toBeNull();
+ expect(trailingGroup().contains(screen.getByRole('button', { name: 'Settings' }))).toBe(
+ true,
+ );
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('never collapses while the header is unmeasured', () => {
+ const restoreMetrics = mockHeaderMetrics({ ...CRAMPED, header: 0 });
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).toBeNull();
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('the room left for the trailing group keeps the project switcher its icons, whatever the project is called', () => {
+ setElectronHost(true);
+ const verdicts = [110, 400].map((switcherName) => {
+ const restoreMetrics = mockHeaderMetrics({
+ header: 700,
+ leading: 220,
+ trailing: 420,
+ switcher: switcherName + 64,
+ switcherName,
+ });
+ try {
+ renderHeader();
+ return overflowTrigger() !== null;
+ } finally {
+ restoreMetrics();
+ cleanup();
+ }
+ });
+
+ expect(
+ verdicts,
+ 'reserving the switcher icons leaves 416px, too little for a 420px group',
+ ).toEqual([true, true]);
+ });
+
+ test('a group that fits beside the leading group and the switcher icons stays inline', () => {
+ setElectronHost(true);
+ const restoreMetrics = mockHeaderMetrics({
+ header: 760,
+ leading: 220,
+ trailing: 420,
+ switcher: 464,
+ switcherName: 400,
+ });
+ try {
+ renderHeader();
+
+ expect(overflowTrigger()).toBeNull();
+ } finally {
+ restoreMetrics();
+ }
+ });
+
+ test('counts the Windows caption-button inset against the room', () => {
+ setElectronHost(true, { platform: 'win32' });
+ const realGetComputedStyle = window.getComputedStyle.bind(window);
+ const computedStyle = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((element: Element, pseudo?: string | null) => {
+ const style = realGetComputedStyle(element, pseudo);
+ if (element instanceof HTMLElement && element.hasAttribute('data-app-header-trailing')) {
+ return new Proxy(style, {
+ get: (target, property) =>
+ property === 'marginInlineEnd' ? '138px' : Reflect.get(target, property),
+ }) as CSSStyleDeclaration;
+ }
+ return style;
+ });
+ const restoreMetrics = mockHeaderMetrics({ header: 760, leading: 220, trailing: 420 });
+ try {
+ renderHeader();
+
+ expect(
+ overflowTrigger(),
+ '420px of controls plus a 138px caption-button inset does not fit in 540px',
+ ).not.toBeNull();
+ } finally {
+ restoreMetrics();
+ computedStyle.mockRestore();
+ }
+ });
+
+ test('an Electron host keeps the build label hoverable inside the draggable header', () => {
+ setElectronHost(true, { instanceLabel: 'wt-header' });
+ renderHeader();
+ const header = screen.getByRole('banner');
+ const badge = screen.getByTestId('instance-badge');
+
+ expect(header.contains(badge)).toBe(true);
+ expectVisualClassTokens(header.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokens(badge.className, ['[-webkit-app-region:no-drag]']);
+ });
+
+ test('when only the instance badge does not fit, it shrinks to its icon and the trailing group stays inline', () => {
+ setElectronHost(true, { instanceLabel: 'wt-header' });
+ const observer = captureResizeObserver();
+ const restoreMetrics = mockHeaderMetrics(BADGE_CRAMPED);
+ try {
+ renderHeader();
+ const badge = screen.getByTestId('instance-badge');
+
+ for (const pass of [1, 2, 3]) {
+ observer.flush();
+ expectVisualClassTokens(badge.querySelector('[data-instance-badge-label]')?.className, [
+ 'sr-only',
+ ]);
+ expect(
+ overflowTrigger(),
+ `re-measurement pass ${pass} folded the trailing group though the compact badge left room for it`,
+ ).toBeNull();
+ }
+ expect(within(badge).getByText('App instance: wt-header').classList).toContain('sr-only');
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('the pass that shrinks the instance badge already counts the room it frees', () => {
+ setElectronHost(true, { instanceLabel: 'wt-header' });
+ const observer = captureResizeObserver();
+ const restoreMetrics = mockHeaderMetrics(BADGE_CRAMPED);
+ try {
+ renderHeader();
+
+ expectVisualClassTokens(
+ screen.getByTestId('instance-badge').querySelector('[data-instance-badge-label]')
+ ?.className,
+ ['sr-only'],
+ );
+ expect(
+ overflowTrigger(),
+ 'the first paint folded the trailing group at a width where the compact badge leaves room for it',
+ ).toBeNull();
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('a centre that fills in after mount re-drives the collapse verdict', () => {
+ setElectronHost(true);
+ const observer = captureResizeObserver();
+ let centreWidth = 0;
+ const restoreMetrics = mockHeaderMetrics(() => ({
+ header: 700,
+ leading: 220,
+ trailing: 420,
+ collapsedTrailing: 44,
+ switcher: centreWidth,
+ switcherName: centreWidth > 0 ? 100 : 0,
+ }));
+ try {
+ renderHeader();
+ expect(overflowTrigger()).toBeNull();
+
+ centreWidth = 300;
+ observer.flush(centreGroup());
+
+ expect(
+ overflowTrigger(),
+ 'the centre grew after mount and nothing re-measured, so the header kept the verdict it computed for an empty centre',
+ ).not.toBeNull();
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('the instance badge keeps its name while the header has room for it', () => {
+ setElectronHost(true, { instanceLabel: 'wt-header' });
+ const observer = captureResizeObserver();
+ const restoreMetrics = mockHeaderMetrics({ ...BADGE_CRAMPED, header: 1_280 });
+ try {
+ renderHeader();
+ observer.flush();
+
+ expectVisualClassTokensAbsent(
+ screen.getByTestId('instance-badge').querySelector('[data-instance-badge-label]')
+ ?.className,
+ ['sr-only'],
+ );
+ expect(overflowTrigger()).toBeNull();
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('a collapsed group stays collapsed when its own collapsed width is re-measured', () => {
+ const observer = captureResizeObserver();
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+ expect(overflowTrigger()).not.toBeNull();
+
+ for (const pass of [1, 2, 3]) {
+ observer.flush();
+ expect(
+ overflowTrigger(),
+ `re-measurement pass ${pass} re-expanded the group though the room never changed`,
+ ).not.toBeNull();
+ }
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('re-measures the remembered width when the trailing content changes', async () => {
+ const observer = captureResizeObserver();
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ let restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ const view = renderHeader();
+ expect(overflowTrigger()).not.toBeNull();
+
+ restoreMetrics();
+ restoreMetrics = mockHeaderMetrics({ ...CRAMPED, trailing: 200 });
+ shell.syncStatus = { state: 'offline', conflictCount: 0, hasRemote: true };
+ view.rerender(<AppHeader onOpenSearch={onOpenSearch} />);
+
+ await waitFor(() => expect(overflowTrigger()).toBeNull());
+ observer.flush();
+ expect(overflowTrigger()).toBeNull();
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('a pane button that goes while folded resets the remembered width, and the header unfolds and stays unfolded', () => {
+ const observer = captureResizeObserver();
+ publishPanes();
+ const restoreMetrics = mockHeaderMetrics({
+ header: 600,
+ leading: 220,
+ trailing: 300,
+ collapsedTrailing: 44,
+ paneButton: 40,
+ });
+ try {
+ renderHeader();
+ expect(
+ overflowTrigger(),
+ '300px of controls and two 40px pane buttons do not fit in 380px',
+ ).not.toBeNull();
+
+ publishPanes({ terminal: false });
+
+ expect(
+ overflowTrigger(),
+ 'the header kept the width it remembered with the Terminal button though the button is gone',
+ ).toBeNull();
+ for (const pass of [1, 2, 3]) {
+ observer.flush();
+ expect(
+ overflowTrigger(),
+ `re-measurement pass ${pass} folded the header again`,
+ ).toBeNull();
+ }
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('a pane button that appears re-measures at once, and the header folds and stays folded', () => {
+ const observer = captureResizeObserver();
+ publishPanes({ terminal: false });
+ const restoreMetrics = mockHeaderMetrics({
+ header: 600,
+ leading: 220,
+ trailing: 300,
+ collapsedTrailing: 44,
+ paneButton: 40,
+ });
+ try {
+ renderHeader();
+ expect(overflowTrigger()).toBeNull();
+
+ publishPanes();
+
+ expect(
+ overflowTrigger(),
+ 'the Terminal button appeared and the header kept a verdict measured without it',
+ ).not.toBeNull();
+ for (const pass of [1, 2, 3]) {
+ observer.flush();
+ expect(
+ overflowTrigger(),
+ `re-measurement pass ${pass} unfolded the header though the room never changed`,
+ ).not.toBeNull();
+ }
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test('turning the project terminal off and on re-measures the fold each time', () => {
+ const observer = captureResizeObserver();
+ publishPanes();
+ const restoreMetrics = mockHeaderMetrics({
+ header: 600,
+ leading: 220,
+ trailing: 300,
+ collapsedTrailing: 44,
+ paneButton: 40,
+ });
+ try {
+ const view = renderHeader();
+ expect(overflowTrigger()).not.toBeNull();
+
+ projectTerminal = { synced: true, enabled: false };
+ view.rerender(<AppHeader onOpenSearch={onOpenSearch} />);
+
+ expect(screen.queryByRole('button', { name: 'Terminal' })).toBeNull();
+ expect(
+ overflowTrigger(),
+ 'the header kept the width it remembered with the Terminal button after the terminal was turned off',
+ ).toBeNull();
+ observer.flush();
+ expect(overflowTrigger()).toBeNull();
+
+ projectTerminal = { synced: true, enabled: true };
+ view.rerender(<AppHeader onOpenSearch={onOpenSearch} />);
+
+ expect(screen.getByRole('button', { name: 'Terminal' })).toBeTruthy();
+ expect(
+ overflowTrigger(),
+ 'the Terminal button came back and the header kept a verdict measured without it',
+ ).not.toBeNull();
+ observer.flush();
+ expect(overflowTrigger()).not.toBeNull();
+ } finally {
+ restoreMetrics();
+ observer.restore();
+ }
+ });
+
+ test.each([
+ { status: { state: 'idle', conflictCount: 2 }, attention: 'conflict', label: 'Conflict' },
+ { status: { state: 'offline', conflictCount: 0 }, attention: 'offline', label: 'Offline' },
+ {
+ status: { state: 'auth-error', conflictCount: 0 },
+ attention: 'auth-error',
+ label: 'Reconnect required',
+ },
+ {
+ status: { state: 'disabled', conflictCount: 0, pausedReason: 'git-operation-in-progress' },
+ attention: 'paused',
+ label: 'Sync paused',
+ },
+ ] as const)(
+ 'a collapsed group puts the $attention sync state on the trigger',
+ ({ status, attention, label }) => {
+ shell.syncStatus = { ...status, hasRemote: true } as Partial<GitSyncStatus>;
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ const trigger = overflowTrigger() as HTMLElement;
+ expect(trigger.getAttribute('aria-label')).toBe(`More actions (${label})`);
+ expect(
+ trigger
+ .querySelector('[data-testid="header-overflow-actions-sync-indicator"]')
+ ?.getAttribute('data-sync-attention'),
+ ).toBe(attention);
+ } finally {
+ restoreMetrics();
+ }
+ },
+ );
+
+ test('a collapsed group leaves the trigger unadorned while sync is healthy', () => {
+ shell.syncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
+ const restoreMetrics = mockHeaderMetrics(CRAMPED);
+ try {
+ renderHeader();
+
+ const trigger = overflowTrigger() as HTMLElement;
+ expect(trigger.getAttribute('aria-label')).toBe('More actions');
+ expect(
+ trigger.querySelector('[data-testid="header-overflow-actions-sync-indicator"]'),
+ ).toBeNull();
+ } finally {
+ restoreMetrics();
+ }
+ });
+ });
+});
diff --git a/packages/app/src/components/EditorHeader.publish-focus.dom.test.tsx b/packages/app/src/components/AppHeader.publish-focus.dom.test.tsx
similarity index 57%
rename from packages/app/src/components/EditorHeader.publish-focus.dom.test.tsx
rename to packages/app/src/components/AppHeader.publish-focus.dom.test.tsx
index b5b36c539..b4f214723 100644
--- a/packages/app/src/components/EditorHeader.publish-focus.dom.test.tsx
+++ b/packages/app/src/components/AppHeader.publish-focus.dom.test.tsx
@@ -1,33 +1,20 @@
-import { cleanup, 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 { ComponentProps } from 'react';
+import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
-import { EditorHeader } from '@/components/EditorHeader';
+import { AppHeader } from '@/components/AppHeader';
import { TooltipProvider } from '@/components/ui/tooltip';
-import { captureResizeObserver, mockHeaderMetrics } from './EditorHeader.layout.test-helper';
+import { ConfigContext } from '@/lib/config-context';
+import { configContextWithTerminal, TERMINAL_SETTING_UNSET } from '@/test-utils/config-context';
vi.mock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'docs/notes',
activeTarget: { kind: 'doc' },
activeProvider: null,
- panes: [{ id: 'pane-0' }],
}),
}));
-vi.mock('@/lib/single-file-mode', () => ({ useSingleFileMode: () => false }));
-
-vi.mock('@/components/ui/sidebar', () => ({
- useSidebar: () => ({ state: 'expanded' }),
- SidebarTrigger: (props: ComponentProps<'button'>) => (
- <button type="button" data-testid="sidebar-trigger" {...props}>
- sidebar
- </button>
- ),
-}));
-
-vi.mock('@/components/AppMenubar', () => ({ AppMenubar: () => null }));
-
vi.mock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatusDetailed: () => ({
status: { state: 'dormant', conflictCount: 0, hasRemote: false },
@@ -49,11 +36,6 @@ vi.mock('@/components/SyncStatusBadge', async () => ({
SyncStatusBadge: () => <div data-testid="sync-status-badge" />,
}));
-vi.mock('@/components/BetaBadge', () => ({ BetaBadge: () => null }));
-vi.mock('@/components/InstanceBadge', () => ({ InstanceBadge: () => null }));
-vi.mock('@/components/SettingsButton', () => ({
- SettingsButton: () => <div data-testid="settings-button" />,
-}));
vi.mock('@/components/HelpPopover', () => ({
HelpPopover: () => <div data-testid="help-popover" />,
}));
@@ -70,33 +52,59 @@ vi.mock('@/lib/share/publish-wizard', async () => ({
fetchPublishNameCheck: () => new Promise(() => {}),
}));
-const CRAMPED = { header: 107, leading: 57, trailing: 218, collapsedTrailing: 44 };
-const ROOMY = { header: 1_280, leading: 57, trailing: 218 };
+const CRAMPED = { header: 470, leading: 220, trailing: 420, collapsedTrailing: 44 };
+const ROOMY = { header: 1_280, leading: 220, trailing: 420 };
let metrics: typeof CRAMPED | typeof ROOMY = ROOMY;
-let resizeObserver: ReturnType<typeof captureResizeObserver> | null = null;
+let resizeCallbacks: ResizeObserverCallback[] = [];
function installLayout() {
- mockHeaderMetrics(() => metrics);
- resizeObserver = captureResizeObserver();
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(function (
+ this: HTMLElement,
+ ) {
+ if (this.hasAttribute('data-app-header')) return metrics.header;
+ if (this.hasAttribute('data-app-header-leading')) return metrics.leading;
+ if (this.hasAttribute('data-app-header-trailing')) {
+ const collapsed =
+ this.querySelector('[data-testid="header-overflow-actions-trigger"]') !== null;
+ return collapsed && 'collapsedTrailing' in metrics
+ ? metrics.collapsedTrailing
+ : metrics.trailing;
+ }
+ return 0;
+ });
+ class CapturingResizeObserver {
+ constructor(callback: ResizeObserverCallback) {
+ resizeCallbacks.push(callback);
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ vi.stubGlobal('ResizeObserver', CapturingResizeObserver);
}
function relayout(next: typeof CRAMPED | typeof ROOMY) {
metrics = next;
- resizeObserver?.flush();
+ for (const callback of resizeCallbacks) {
+ act(() => callback([], {} as ResizeObserver));
+ }
}
-function renderHeader() {
- return render(
- <EditorHeader onOpenSearch={() => {}}>
- <div>tabs</div>
- </EditorHeader>,
- { wrapper: TooltipProvider },
+function HeaderProviders({ children }: { children: ReactNode }) {
+ return (
+ <ConfigContext value={configContextWithTerminal(TERMINAL_SETTING_UNSET)}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </ConfigContext>
);
}
+function renderHeader() {
+ return render(<AppHeader onOpenSearch={() => {}} />, { wrapper: HeaderProviders });
+}
+
function trailingGroup(): HTMLElement {
- return document.querySelector('[data-editor-header-actions]') as HTMLElement;
+ return screen.getByRole('banner').querySelector('[data-app-header-trailing]') as HTMLElement;
}
async function closeDialogWithEscape() {
@@ -109,16 +117,15 @@ afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
metrics = ROOMY;
- resizeObserver?.restore();
- resizeObserver = null;
+ resizeCallbacks = [];
});
-describe('EditorHeader Publish to GitHub dialog focus return', () => {
+describe('AppHeader Publish to GitHub dialog focus return', () => {
test('closing the dialog opened from the inline Share button focuses that Share button', async () => {
installLayout();
renderHeader();
- const share = await within(trailingGroup()).findByRole('button', { name: 'Share doc' });
+ const share = within(trailingGroup()).getByRole('button', { name: 'Share doc' });
await userEvent.click(share);
await screen.findByRole('dialog');
@@ -131,13 +138,11 @@ describe('EditorHeader Publish to GitHub dialog focus return', () => {
installLayout();
renderHeader();
- await userEvent.click(
- await within(trailingGroup()).findByRole('button', { name: 'Share doc' }),
- );
+ await userEvent.click(within(trailingGroup()).getByRole('button', { name: 'Share doc' }));
await screen.findByRole('dialog');
relayout(CRAMPED);
- const trigger = await screen.findByTestId('header-overflow-actions-trigger');
+ const trigger = screen.getByTestId('header-overflow-actions-trigger');
expect(screen.queryByRole('button', { name: 'Share doc' })).toBeNull();
await closeDialogWithEscape();
@@ -150,17 +155,17 @@ describe('EditorHeader Publish to GitHub dialog focus return', () => {
installLayout();
renderHeader();
- const trigger = await screen.findByTestId('header-overflow-actions-trigger');
+ const trigger = screen.getByTestId('header-overflow-actions-trigger');
await userEvent.click(trigger);
const panel = await waitFor(() => {
- const found = document.querySelector<HTMLElement>('[data-editor-header-overflow-actions]');
+ const found = document.querySelector<HTMLElement>('[data-header-overflow-actions]');
expect(found).not.toBeNull();
return found as HTMLElement;
});
await userEvent.click(within(panel).getByRole('button', { name: 'Share doc' }));
await screen.findByRole('dialog');
await waitFor(() =>
- expect(document.querySelector('[data-editor-header-overflow-actions]')).toBeNull(),
+ expect(document.querySelector('[data-header-overflow-actions]')).toBeNull(),
);
await closeDialogWithEscape();
diff --git a/packages/app/src/components/AppHeader.tsx b/packages/app/src/components/AppHeader.tsx
new file mode 100644
index 000000000..b49e22086
--- /dev/null
+++ b/packages/app/src/components/AppHeader.tsx
@@ -0,0 +1,285 @@
+import { parseManagedArtifactName } from '@inkeep/open-knowledge-core/constants/cc1';
+import { APP_HEADER_HEIGHT } from '@inkeep/open-knowledge-core/constants/chrome';
+import { useLingui } from '@lingui/react/macro';
+import { lazy, Suspense, useRef, useState } from 'react';
+import { ErrorBoundary } from 'react-error-boundary';
+import { shouldShowAppMenubar } from '@/components/app-menubar-gate';
+import { BetaBadge } from '@/components/BetaBadge';
+import {
+ HEADER_OVERFLOW_SLACK_PX,
+ HeaderOverflowActions,
+} from '@/components/HeaderOverflowActions';
+import { HeaderPaneButtons, useHeaderPaneButtonSet } from '@/components/HeaderPaneButtons';
+import { HeaderSearchBar, onPillRenderError } from '@/components/HeaderSearchBar';
+import { HelpPopover } from '@/components/HelpPopover';
+import { InstanceBadge } from '@/components/InstanceBadge';
+import { NavigationHistoryControls } from '@/components/NavigationHistoryControls';
+import { ProjectSwitcher } from '@/components/ProjectSwitcher';
+import { PublishToGitHubDialog } from '@/components/PublishToGitHubDialog';
+import { SettingsButton } from '@/components/SettingsButton';
+import { ShareButton } from '@/components/ShareButton';
+import { displayState, SyncStatusBadge } from '@/components/SyncStatusBadge';
+import { WebProjectName } from '@/components/WebProjectName';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';
+import { useTrailingOverflow } from '@/hooks/use-trailing-overflow';
+import { authPromptStore } from '@/lib/auth-prompt-store';
+import {
+ buildDocShareInput,
+ buildFolderShareInput,
+ type ShareTargetInput,
+} from '@/lib/share/run-share-action';
+import { useSingleFileMode } from '@/lib/single-file-mode';
+import { cn } from '@/lib/utils';
+import { PresenceBar } from '@/presence/PresenceBar';
+import { SyncToastHost } from '@/presence/SyncToastHost';
+
+const AppMenubar = lazy(() =>
+ import('@/components/AppMenubar').then((m) => ({ default: m.AppMenubar })),
+);
+
+export { APP_HEADER_HEIGHT };
+
+function centreNaturalWidth(centre: HTMLElement): number {
+ let width = 0;
+ for (const child of centre.children) {
+ if (child instanceof HTMLElement) width += child.offsetWidth;
+ }
+ if (centre.clientWidth > width + 1) return width;
+ for (const label of centre.querySelectorAll<HTMLElement>('[data-app-header-center-label]')) {
+ width += Math.max(0, label.scrollWidth - label.clientWidth);
+ }
+ return width;
+}
+
+function hiddenInstanceBadgeLabelWidth(leading: HTMLElement): number {
+ const label = leading.querySelector<HTMLElement>('[data-instance-badge-label]');
+ const badge = label?.parentElement;
+ if (!label || !badge) return 0;
+ const maxWidth = Number.parseFloat(getComputedStyle(label).maxWidth);
+ const natural = Number.isFinite(maxWidth)
+ ? Math.min(label.scrollWidth, maxWidth)
+ : label.scrollWidth;
+ return natural + (Number.parseFloat(getComputedStyle(badge).columnGap) || 0);
+}
+
+function leadingBadgesWidth(leading: HTMLElement): number | null {
+ const badges = leading.querySelector<HTMLElement>('[data-app-header-badges]');
+ if (!badges) return null;
+ if (badges.offsetWidth <= 0) return 0;
+ return badges.offsetWidth + (Number.parseFloat(getComputedStyle(leading).columnGap) || 0);
+}
+
+function AppHeaderBadges({
+ compact,
+ isElectronHost,
+}: {
+ compact: boolean;
+ isElectronHost: boolean;
+}) {
+ return (
+ <div data-app-header-badges="" className="flex items-center gap-1 empty:hidden">
+ <BetaBadge />
+ <InstanceBadge
+ compact={compact}
+ className={cn(isElectronHost && '[-webkit-app-region:no-drag]')}
+ />
+ </div>
+ );
+}
+
+function centreFloorWidth(centre: HTMLElement): number {
+ let width = 0;
+ for (const child of centre.children) {
+ if (child instanceof HTMLElement) width += child.offsetWidth;
+ }
+ for (const label of centre.querySelectorAll<HTMLElement>('[data-app-header-center-label]')) {
+ width -= label.offsetWidth;
+ }
+ return Math.max(0, width);
+}
+
+interface AppHeaderProps {
+ onOpenSearch: () => void;
+}
+
+export function AppHeader({ onOpenSearch }: AppHeaderProps) {
+ const { t } = useLingui();
+ const singleFile = useSingleFileMode();
+ const { activeDocName, activeTarget } = useDocumentContext();
+ const desktopBridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const isElectronHost = desktopBridge != null;
+ const foldsBadges = isElectronHost && desktopBridge.platform !== 'darwin';
+ const [publishOpen, setPublishOpen] = useState(false);
+ const [badgeCompact, setBadgeCompact] = useState(false);
+ const badgeCompactRef = useRef(false);
+ const leadingBadgesRef = useRef({ width: 0, labelWidth: 0, hasLabel: false });
+ const [header, setHeader] = useState<HTMLElement | null>(null);
+ const [leading, setLeading] = useState<HTMLDivElement | null>(null);
+ const [trailing, setTrailing] = useState<HTMLDivElement | null>(null);
+ const [centre, setCentre] = useState<HTMLDivElement | null>(null);
+ const shareButtonRef = useRef<HTMLButtonElement>(null);
+ const overflowTriggerRef = useRef<HTMLButtonElement>(null);
+
+ const shareInput: ShareTargetInput | null = singleFile
+ ? null
+ : (() => {
+ if (activeTarget?.kind === 'folder') return buildFolderShareInput(activeTarget.folderPath);
+ if (activeDocName && !parseManagedArtifactName(activeDocName)) {
+ return buildDocShareInput(activeDocName);
+ }
+ if (!activeTarget && !activeDocName) return buildFolderShareInput('');
+ return null;
+ })();
+ const { status: gitSyncStatus } = useGitSyncStatusDetailed();
+ const paneButtonSet = useHeaderPaneButtonSet();
+ const trailingContentSignature = [
+ String(shareInput != null),
+ gitSyncStatus?.hasRemote ? displayState(gitSyncStatus) : 'no-remote',
+ paneButtonSet.join(','),
+ ].join('|');
+
+ const actionsOverflowed = useTrailingOverflow({
+ header,
+ leading,
+ trailing,
+ centre,
+ signature: trailingContentSignature,
+ slack: HEADER_OVERFLOW_SLACK_PX,
+ measureTrailingWidth: (elements) =>
+ elements.trailing.offsetWidth +
+ (Number.parseFloat(getComputedStyle(elements.trailing).marginInlineEnd) || 0),
+ measureAvailableWidth: (elements, latchedTrailingWidth) => {
+ const headerWidth = elements.header.offsetWidth;
+ const badgesWidth = leadingBadgesWidth(elements.leading);
+ if (badgesWidth !== null) {
+ const labelWidth = hiddenInstanceBadgeLabelWidth(elements.leading);
+ leadingBadgesRef.current = {
+ width: badgesWidth + (badgeCompactRef.current ? labelWidth : 0),
+ labelWidth,
+ hasLabel: elements.leading.querySelector('[data-instance-badge-label]') != null,
+ };
+ }
+ const badges = leadingBadgesRef.current;
+ const leadingExpandedWidth =
+ badgesWidth === null
+ ? elements.leading.offsetWidth + badges.width
+ : elements.leading.offsetWidth + (badgeCompactRef.current ? badges.labelWidth : 0);
+ const compact =
+ centre != null &&
+ badges.hasLabel &&
+ leadingExpandedWidth +
+ centreNaturalWidth(centre) +
+ latchedTrailingWidth +
+ HEADER_OVERFLOW_SLACK_PX >
+ headerWidth;
+ badgeCompactRef.current = compact;
+ setBadgeCompact(compact);
+ const leadingSettledWidth = compact
+ ? leadingExpandedWidth - badges.labelWidth
+ : leadingExpandedWidth;
+ return headerWidth - leadingSettledWidth - (centre != null ? centreFloorWidth(centre) : 0);
+ },
+ });
+ const badgesFolded = (foldsBadges || singleFile) && actionsOverflowed;
+
+ const trailingActions = (
+ <>
+ <PresenceBar />
+ {!singleFile && (
+ <ShareButton
+ input={shareInput}
+ onClickWhenNoRemote={() => setPublishOpen(true)}
+ triggerRef={shareButtonRef}
+ />
+ )}
+ <SyncStatusBadge
+ onSignIn={() => authPromptStore.request('auth')}
+ onSetIdentity={() => authPromptStore.request('identity')}
+ />
+ {!singleFile && <SettingsButton />}
+ <HelpPopover />
+ </>
+ );
+
+ return (
+ // biome-ignore lint/a11y/useAriaPropsSupportedByRole: App mounts this header outside main, article and section, where it is the banner landmark and takes a name; the rule reads every header as generic.
+ <header
+ ref={setHeader}
+ aria-label={t`Application`}
+ data-app-header=""
+ data-electron-drag={isElectronHost ? '' : undefined}
+ className={cn(
+ 'grid h-[var(--ok-app-header-height,2.75rem)] w-full shrink-0 items-center',
+ 'grid-cols-[minmax(max-content,1fr)_minmax(0,auto)_minmax(max-content,1fr)] grid-rows-1',
+ 'bg-desk',
+ isElectronHost &&
+ '[-webkit-app-region:drag] [&_a]:[-webkit-app-region:no-drag] [&_button]:[-webkit-app-region:no-drag]',
+ )}
+ >
+ <div
+ ref={setLeading}
+ data-app-header-leading=""
+ className="flex min-w-0 items-center gap-1 justify-self-start ps-[calc(var(--ok-titlebar-reserve-left,0px)+0.625rem)] rtl:ps-[calc(var(--ok-titlebar-reserve-right,0px)+0.625rem)]"
+ >
+ {shouldShowAppMenubar() && (
+ <Suspense fallback={null}>
+ <AppMenubar className="-ms-0.5" />
+ </Suspense>
+ )}
+ {isElectronHost && !singleFile && <NavigationHistoryControls />}
+ {!singleFile && (
+ <ErrorBoundary
+ fallbackRender={() => null}
+ onError={onPillRenderError}
+ resetKeys={[activeDocName]}
+ >
+ <HeaderSearchBar onClick={onOpenSearch} />
+ </ErrorBoundary>
+ )}
+ {!badgesFolded && (
+ <AppHeaderBadges compact={badgeCompact} isElectronHost={isElectronHost} />
+ )}
+ </div>
+ <div
+ ref={setCentre}
+ data-app-header-center=""
+ className="flex min-w-0 items-center justify-center"
+ >
+ {singleFile ? null : desktopBridge ? (
+ <ProjectSwitcher bridge={desktopBridge} />
+ ) : (
+ <WebProjectName />
+ )}
+ </div>
+ <div
+ ref={setTrailing}
+ data-app-header-trailing=""
+ className={cn(
+ 'flex min-w-0 items-center justify-end gap-1 justify-self-end pe-2.5',
+ '[&_[data-slot=presence-bar]]:px-0',
+ isElectronHost &&
+ 'me-[var(--ok-titlebar-reserve-right,0px)] rtl:me-[var(--ok-titlebar-reserve-left,0px)]',
+ )}
+ >
+ {actionsOverflowed ? (
+ <HeaderOverflowActions syncStatus={gitSyncStatus} triggerRef={overflowTriggerRef}>
+ {badgesFolded && <AppHeaderBadges compact={false} isElectronHost={isElectronHost} />}
+ {trailingActions}
+ </HeaderOverflowActions>
+ ) : (
+ trailingActions
+ )}
+ <HeaderPaneButtons />
+ <SyncToastHost />
+ {!singleFile && (
+ <PublishToGitHubDialog
+ open={publishOpen}
+ onOpenChange={setPublishOpen}
+ returnFocus={() => (shareButtonRef.current ?? overflowTriggerRef.current)?.focus()}
+ />
+ )}
+ </div>
+ </header>
+ );
+}
diff --git a/packages/app/src/components/AppMenubar.dom.test.tsx b/packages/app/src/components/AppMenubar.dom.test.tsx
index 95a7e0bc2..0aa7d679e 100644
--- a/packages/app/src/components/AppMenubar.dom.test.tsx
+++ b/packages/app/src/components/AppMenubar.dom.test.tsx
@@ -29,7 +29,12 @@ function installBridge(
async function openMenu(name: string) {
const { AppMenubar } = await import('./AppMenubar');
- render(<AppMenubar />);
+ const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
+ render(
+ <SingleFileModeProvider>
+ <AppMenubar />
+ </SingleFileModeProvider>,
+ );
await userEvent.click(screen.getByRole('menuitem', { name }));
}
@@ -259,6 +264,36 @@ describe('AppMenubar View terminal toggle', () => {
expect(screen.queryByRole('menuitem', { name: /Show Terminal/ })).toBeNull();
});
+ test('a project window offers Hide Editor, then Show Editor once hidden, through the shared menu action', async () => {
+ const dispatch = installBridge('linux', 'editor', { queryResult: snapshot(false) });
+ await openMenu('View');
+
+ const item = await screen.findByRole('menuitem', { name: 'Hide Editor' });
+ dispatch.mockClear();
+ await userEvent.click(item);
+ expect(dispatch).toHaveBeenCalledWith({ kind: 'menu-action', action: 'toggle-editor' });
+
+ cleanup();
+ const hidden = snapshot(false);
+ installBridge('linux', 'editor', {
+ queryResult: { ...hidden, viewMenuState: { ...hidden.viewMenuState, editorVisible: false } },
+ });
+ await openMenu('View');
+ expect(await screen.findByRole('menuitem', { name: 'Show Editor' })).not.toBeNull();
+ });
+
+ test('a single-file window offers no editor toggle', async () => {
+ const dispatch = installBridge('win32', 'editor', { queryResult: snapshot(false) });
+ const bridge = (window as unknown as { okDesktop: { config: Record<string, unknown> } })
+ .okDesktop;
+ bridge.config.singleFile = true;
+ await openMenu('View');
+ await screen.findByRole('menuitem', { name: /document panel/ });
+
+ expect(screen.queryByRole('menuitem', { name: /Editor/ })).toBeNull();
+ expect(dispatch).not.toHaveBeenCalledWith({ kind: 'menu-action', action: 'toggle-editor' });
+ });
+
test('Windows keeps the terminal toggle absent while PTYs are unavailable', async () => {
installBridge('win32', 'editor', {
ptyAvailable: false,
diff --git a/packages/app/src/components/AppMenubar.tsx b/packages/app/src/components/AppMenubar.tsx
index e9be8b357..1ff962a65 100644
--- a/packages/app/src/components/AppMenubar.tsx
+++ b/packages/app/src/components/AppMenubar.tsx
@@ -20,11 +20,18 @@ import type {
OkMenuUiDispatchRequest,
} from '@/lib/desktop-bridge-types';
import { aboutAppLabel, moveToTrashLabel, revealInFileManagerLabel } from '@/lib/platform-labels';
+import { useSingleFileMode } from '@/lib/single-file-mode';
+import { cn } from '@/lib/utils';
-export function AppMenubar() {
+interface AppMenubarProps {
+ readonly className?: string;
+}
+
+export function AppMenubar({ className }: AppMenubarProps) {
const { t } = useLingui();
const bridge = typeof window !== 'undefined' ? (window.okDesktop ?? null) : null;
const [snapshot, setSnapshot] = useState<OkMenuRendererSnapshot | null>(null);
+ const singleFile = useSingleFileMode();
if (!shouldShowAppMenubar() || bridge == null || bridge.menu == null) return null;
const menu: NonNullable<OkDesktopBridge['menu']> = bridge.menu;
@@ -47,7 +54,10 @@ export function AppMenubar() {
return (
<Menubar
data-testid="app-menubar"
- className="h-auto rounded-none border-0 bg-transparent p-0 shadow-none [-webkit-app-region:no-drag]"
+ className={cn(
+ 'h-auto rounded-none border-0 bg-transparent p-0 shadow-none [-webkit-app-region:no-drag]',
+ className,
+ )}
onValueChange={(value) => {
if (value) refreshSnapshot();
}}
@@ -260,6 +270,13 @@ export function AppMenubar() {
{view?.docPanelVisible === false ? t`Show document panel` : t`Hide document panel`}
<MenubarShortcut>Ctrl+Alt+B</MenubarShortcut>
</MenubarItem>
+ {!singleFile && (
+ <MenubarItem
+ onSelect={() => dispatch({ kind: 'menu-action', action: 'toggle-editor' })}
+ >
+ {view?.editorVisible === false ? t`Show Editor` : t`Hide Editor`}
+ </MenubarItem>
+ )}
{bridge.config.ptyAvailable && (
<MenubarItem
onSelect={() => dispatch({ kind: 'menu-action', action: 'toggle-terminal' })}
diff --git a/packages/app/src/components/AssetPreview.tsx b/packages/app/src/components/AssetPreview.tsx
index ef333d650..90192e3b6 100644
--- a/packages/app/src/components/AssetPreview.tsx
+++ b/packages/app/src/components/AssetPreview.tsx
@@ -49,11 +49,11 @@ function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
if (effectiveMediaKind === 'pdf') {
return (
- <main className="flex h-full min-h-0 flex-col bg-background" aria-label={fileName}>
+ <section className="flex h-full min-h-0 flex-col bg-background" aria-label={fileName}>
<div className="min-h-0 flex-1 overflow-hidden">
<Pdf src={src} title={fileName} fillContainer />
</div>
- </main>
+ </section>
);
}
@@ -82,7 +82,7 @@ function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
}
return (
- <main className="flex h-full min-h-0 flex-col bg-background" aria-label={fileName}>
+ <section className="flex h-full min-h-0 flex-col bg-background" aria-label={fileName}>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
{effectiveMediaKind === 'image' ? (
<LoadingImage
@@ -139,6 +139,6 @@ function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
</div>
)}
</div>
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsx
index 11c75c60a..0ef115677 100644
--- a/packages/app/src/components/BottomComposer.tsx
+++ b/packages/app/src/components/BottomComposer.tsx
@@ -7,7 +7,7 @@ import {
} from '@inkeep/open-knowledge-core/handoff';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { ArrowUpRight, ChevronDown, TextQuote, X } from 'lucide-react';
-import { useEffect, useEffectEvent, useRef, useState } from 'react';
+import { useEffect, useEffectEvent, useRef, useState, useSyncExternalStore } from 'react';
import { toast } from 'sonner';
import {
composeCommentBatchInstruction,
@@ -96,7 +96,12 @@ import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils';
import { docNameToRelativePath } from '@/lib/workspace-paths';
import { emitOpenAskAiComposer, subscribeToOpenAskAiComposer } from './ask-ai-composer-events';
-import { clearComposerDraft, getComposerDraft, setComposerDraftDoc } from './composer-draft-store';
+import {
+ clearComposerDraft,
+ getComposerDraft,
+ setComposerDraftDoc,
+ subscribeComposerDraft,
+} from './composer-draft-store';
import { nextTouchedFiles } from './composer-touched-files';
import { focusComposerInputOnCardPointer } from './focus-composer-on-card-pointer';
import { usePageList } from './PageListContext';
@@ -165,7 +170,7 @@ export function BottomComposer({
const cardRef = useRef<HTMLDivElement>(null);
const clampRef = useRef<(() => void) | null>(null);
- const [initialDraftDoc] = useState(() => getComposerDraft().doc ?? undefined);
+ const { doc: savedDraftDoc } = useSyncExternalStore(subscribeComposerDraft, getComposerDraft);
const {
pendingAttachments,
@@ -857,7 +862,7 @@ export function BottomComposer({
/>
) : null}
</div>
- <div className="flex items-end gap-2">
+ <div className="flex flex-wrap items-end gap-2">
<ComposerAddMenu composerRef={inputRef} testId="ask-ai-add-to-prompt" size="icon">
{attachmentsAccepted ? <ComposerFilesMenuItem onFiles={ingestFiles} /> : null}
{selectedCommentCount > 0 && !hasQueuedComments ? (
@@ -868,7 +873,7 @@ export function BottomComposer({
) : null}
<ComposerMentionMenuItem onSelect={() => inputRef.current?.openMentionPicker()} />
</ComposerAddMenu>
- <div className="relative flex min-h-8 flex-1 flex-col justify-center">
+ <div className="relative flex min-h-8 min-w-24 flex-[1_1_6rem] flex-col justify-center">
<ComposerMentionInput
ref={inputRef}
ariaLabel={t`Ask AI`}
@@ -881,7 +886,7 @@ export function BottomComposer({
}}
onMentionsChange={setInlineMentions}
onSubmit={submit}
- initialDoc={initialDraftDoc}
+ initialDoc={savedDraftDoc ?? undefined}
className="max-h-[200px] overflow-y-auto overscroll-contain text-base md:text-sm"
/>
{}
@@ -895,6 +900,8 @@ export function BottomComposer({
) : null}
</div>
<AgentSplitButton
+ className="ms-auto max-w-full min-w-0"
+ primaryClassName="h-auto min-h-8 min-w-0 shrink whitespace-normal"
primary={
<>
{isThreadSelected ? (
@@ -908,7 +915,7 @@ export function BottomComposer({
) : resolvedTarget ? (
<TargetIcon id={resolvedTarget.id} className="size-4" aria-hidden />
) : null}
- <span>
+ <span className="min-w-0 break-words">
{isThreadSelected ? (
defaultThreadAgent !== null ? (
<AskAgentNameLabel agentName={defaultThreadAgent.name} />
diff --git a/packages/app/src/components/BranchRecycleBanner.dom.test.tsx b/packages/app/src/components/BranchRecycleBanner.dom.test.tsx
index 00719ca81..bc70a6c75 100644
--- a/packages/app/src/components/BranchRecycleBanner.dom.test.tsx
+++ b/packages/app/src/components/BranchRecycleBanner.dom.test.tsx
@@ -1,6 +1,7 @@
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { BRANCH_SWITCH_NOTICE_MS, type ContentRecycleNotice } from '@/lib/branch-recycle-notice';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
let notice: ContentRecycleNotice | null = null;
const dismiss = vi.fn();
@@ -106,3 +107,22 @@ test('with the desktop bridge, Restart server disables in flight and re-enables
Reflect.deleteProperty(window, 'okDesktop');
}
});
+
+test('both variants start below the application header rather than over it', async () => {
+ notice = { kind: 'branch-switch', branch: 'feat/x', at: Date.now() };
+ await renderBanner();
+ expectVisualClassTokens(screen.getByTestId('branch-recycle-banner-switch').className, [
+ 'fixed',
+ 'top-[var(--ok-app-header-height,0px)]',
+ 'inset-x-0',
+ ]);
+
+ cleanup();
+ notice = { kind: 'refused', at: Date.now() };
+ await renderBanner();
+ expectVisualClassTokens(screen.getByTestId('branch-recycle-banner-refused').className, [
+ 'fixed',
+ 'top-[var(--ok-app-header-height,0px)]',
+ 'inset-x-0',
+ ]);
+});
diff --git a/packages/app/src/components/BranchRecycleBanner.tsx b/packages/app/src/components/BranchRecycleBanner.tsx
index dc9fa8977..c80257c37 100644
--- a/packages/app/src/components/BranchRecycleBanner.tsx
+++ b/packages/app/src/components/BranchRecycleBanner.tsx
@@ -30,7 +30,7 @@ export function BranchRecycleBanner() {
<div
role="status"
data-testid="branch-recycle-banner-switch"
- className="fixed top-0 inset-x-0 z-50 bg-amber-500/95 text-amber-950 text-sm text-center py-2 px-4 ps-[var(--ok-titlebar-reserve-left,1rem)] shadow-md"
+ className="fixed top-[var(--ok-app-header-height,0px)] inset-x-0 z-50 bg-amber-500/95 text-amber-950 text-sm text-center py-2 px-4 ps-[var(--ok-titlebar-reserve-left,1rem)] shadow-md"
>
<Trans>
Server switched to branch <code className="bg-amber-100/60 px-1 rounded">{branch}</code> —
@@ -55,7 +55,7 @@ export function BranchRecycleBanner() {
<div
role="alert"
data-testid="branch-recycle-banner-refused"
- className="fixed top-0 inset-x-0 z-50 bg-red-500/95 text-red-950 text-sm text-center py-2 px-4 ps-[var(--ok-titlebar-reserve-left,1rem)] shadow-md flex items-center justify-center gap-3 flex-wrap"
+ className="fixed top-[var(--ok-app-header-height,0px)] inset-x-0 z-50 bg-red-500/95 text-red-950 text-sm text-center py-2 px-4 ps-[var(--ok-titlebar-reserve-left,1rem)] shadow-md flex items-center justify-center gap-3 flex-wrap"
>
<span>
<Trans>
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
index 8eccd40af..ca30aff94 100644
--- a/packages/app/src/components/CommandPalette.dom.test.tsx
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -1,11 +1,15 @@
import type { HandoffHostPlatform } from '@inkeep/open-knowledge-core/agent-registry';
-import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
__resetLocalMenuActionBusForTests,
subscribeLocalMenuAction,
} from '@/lib/local-menu-action-bus';
+import {
+ __resetPaneVisibilityStoreForTests,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import { __resetViewMenuStateForTests, setViewMenuState } from '@/lib/view-menu-state-store';
import {
restrictHandoffTargetPlatforms,
@@ -43,7 +47,7 @@ let activeTarget: { kind: string; [key: string]: unknown } | null = {
docName: 'docs/active',
};
let requestDocPanelTabCalls: string[] = [];
-let seedDialogProps: Array<{ open: boolean }> = [];
+let seedDialogProps: Array<{ open: boolean; onSeedApplied?: () => void }> = [];
let newItemDialogProps: Array<{ open: boolean; kind: string; initialDir: string }> = [];
let createProjectDialogProps: Array<{ open: boolean; bridge: unknown }> = [];
let reportBugDialogProps: Array<{ open: boolean; launcherBorne?: boolean }> = [];
@@ -142,7 +146,7 @@ vi.doMock('@/components/NewItemDialog', () => ({
}));
vi.doMock('@/components/SeedDialog', () => ({
- SeedDialog: (props: { open: boolean }) => {
+ SeedDialog: (props: { open: boolean; onSeedApplied?: () => void }) => {
seedDialogProps.push(props);
return <div data-open={String(props.open)} data-testid="seed-dialog" />;
},
@@ -312,15 +316,25 @@ function createBridge({
async function renderPalette({
bridge = createBridge(),
docName = 'docs/active',
+ withSingleFileModeProvider = false,
}: {
bridge?: (ReturnType<typeof createBridge> & { platform?: HandoffHostPlatform }) | null;
docName?: string | null;
+ withSingleFileModeProvider?: boolean;
} = {}) {
activeDocName = docName;
activeTarget = docName ? { kind: 'doc', docName } : null;
const onOpenChange = vi.fn(() => {});
const { CommandPalette } = await import('./CommandPalette');
- render(<CommandPalette bridge={bridge as never} open={true} onOpenChange={onOpenChange} />);
+ const palette = (
+ <CommandPalette bridge={bridge as never} open={true} onOpenChange={onOpenChange} />
+ );
+ if (withSingleFileModeProvider) {
+ const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
+ render(<SingleFileModeProvider>{palette}</SingleFileModeProvider>);
+ } else {
+ render(palette);
+ }
await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
return { bridge, onOpenChange };
}
@@ -335,6 +349,7 @@ async function setQuery(value: string) {
describe('CommandPalette DOM behavior', () => {
beforeEach(() => {
cleanup();
+ __resetPaneVisibilityStoreForTests();
activeDocName = 'docs/active';
activeTarget = { kind: 'doc', docName: 'docs/active' };
pageListLoading = false;
@@ -621,6 +636,25 @@ describe('CommandPalette DOM behavior', () => {
expect(seedDialogProps.at(-1)?.open).toBe(true);
});
+ test('an applied starter pack asks a hidden editor to show', async () => {
+ await renderPalette({ bridge: null });
+ await setQuery('scaffold');
+ fireEvent.click(screen.getByTestId('command-palette-initialize-starter-pack'));
+ await waitFor(() => expect(seedDialogProps.at(-1)?.open).toBe(true));
+
+ const requests: Array<{ pane: string; open: boolean }> = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+
+ act(() => seedDialogProps.at(-1)?.onSeedApplied?.());
+
+ expect(requests).toEqual([{ pane: 'editor', open: true }]);
+ });
+
test('CommandDialog receives no transition or placement prop from CommandPalette', async () => {
await renderPalette();
@@ -1169,6 +1203,7 @@ describe('Cmd+K menu-parity backfill', () => {
query: 'copy relative path',
id: 'copy-relative-path',
},
+ { testid: 'command-palette-toggle-editor', query: 'hide editor', id: 'toggle-editor' },
];
for (const { testid, query, id } of ID_BACKED) {
@@ -1194,6 +1229,22 @@ describe('Cmd+K menu-parity backfill', () => {
);
});
+ test('each pane toggle row wears the glyph its header pane button wears', async () => {
+ await renderPalette({ bridge: createBridge() });
+
+ await setQuery('agents');
+ const agents = screen.getByTestId('command-palette-toggle-agent-panel').querySelector('svg');
+ expect(agents?.classList.contains('lucide-sparkles')).toBe(true);
+
+ await setQuery('hide terminal');
+ const terminal = screen.getByTestId('command-palette-toggle-terminal').querySelector('svg');
+ expect(terminal?.classList.contains('lucide-square-terminal')).toBe(true);
+
+ await setQuery('hide editor');
+ const editor = screen.getByTestId('command-palette-toggle-editor').querySelector('svg');
+ expect(editor?.querySelector('path[d="M9 4v16"]')).not.toBeNull();
+ });
+
test('Ratchet C: every classified palette-command id renders a row or is a pre-existing surface', async () => {
const { PALETTE_COMMAND_IDS, PRE_EXISTING_PALETTE_IDS } = await import(
'@/lib/command-menu-parity.test-helper'
@@ -1337,6 +1388,48 @@ describe('Cmd+K menu-parity backfill', () => {
);
});
+ test('a project window offers Show/Hide Editor and a single-file window offers neither', async () => {
+ setViewMenuState({ editorVisible: true });
+ await renderPalette({ bridge: createBridge() });
+ await setQuery('hide editor');
+ expect(screen.getByTestId('command-palette-toggle-editor').textContent).toContain(
+ 'Hide Editor',
+ );
+
+ cleanup();
+ setViewMenuState({ editorVisible: false });
+ await renderPalette({ bridge: createBridge() });
+ await setQuery('show editor');
+ expect(screen.getByTestId('command-palette-toggle-editor').textContent).toContain(
+ 'Show Editor',
+ );
+
+ cleanup();
+ const projectBridge = createBridge();
+ const singleFileBridge = {
+ ...projectBridge,
+ config: { ...projectBridge.config, singleFile: true },
+ };
+ Object.defineProperty(window, 'okDesktop', { configurable: true, value: singleFileBridge });
+ try {
+ for (const editorVisible of [true, false]) {
+ setViewMenuState({ editorVisible });
+ await renderPalette({ bridge: singleFileBridge, withSingleFileModeProvider: true });
+ for (const query of ['editor', 'show editor', 'hide editor']) {
+ await setQuery(query);
+ expect(screen.queryByTestId('command-palette-toggle-editor')).toBeNull();
+ const editorRows = screen
+ .queryAllByRole('option')
+ .filter((row) => /Show Editor|Hide Editor/.test(row.textContent ?? ''));
+ expect(editorRows).toEqual([]);
+ }
+ cleanup();
+ }
+ } finally {
+ Reflect.deleteProperty(window, 'okDesktop');
+ }
+ });
+
test('terminal placement label and action invert with the current home', async () => {
setViewMenuState({ terminalPlacement: 'bottom' });
await renderPalette({ bridge: createBridge() });
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index 5c7862985..220c5a808 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -104,6 +104,7 @@ import {
} from '@/lib/keyboard-shortcuts';
import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
+import { revealEditor } from '@/lib/reveal-editor';
import { useSingleFileMode } from '@/lib/single-file-mode';
import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils.ts';
@@ -133,6 +134,7 @@ interface CommandPaletteProps {
}
function navigateToDocHash(docName: string): void {
+ revealEditor();
window.location.assign(hashFromDocName(docName));
}
@@ -1468,7 +1470,11 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
kind="folder"
initialDir={initialCreateDir}
/>
- <SeedDialog open={seedDialogOpen} onOpenChange={setSeedDialogOpen} />
+ <SeedDialog
+ open={seedDialogOpen}
+ onOpenChange={setSeedDialogOpen}
+ onSeedApplied={revealEditor}
+ />
{}
{bridge ? (
<CreateProjectDialog
diff --git a/packages/app/src/components/ConnectingBanner.dom.test.tsx b/packages/app/src/components/ConnectingBanner.dom.test.tsx
index 01f9a2499..da609afbd 100644
--- a/packages/app/src/components/ConnectingBanner.dom.test.tsx
+++ b/packages/app/src/components/ConnectingBanner.dom.test.tsx
@@ -1,8 +1,10 @@
import * as actualLinguiMacro from '@lingui/react/macro';
-import { cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+let collabTerminal = true;
let collabLastError: unknown = null;
vi.doMock('@lingui/react/macro', () => ({
@@ -13,7 +15,7 @@ vi.doMock('@lingui/react/macro', () => ({
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
collabUrl: null,
- collabTerminal: true,
+ collabTerminal,
collabLastError,
retryCollab: () => {},
}),
@@ -22,12 +24,42 @@ vi.doMock('@/editor/DocumentContext', () => ({
const { ConnectingBanner } = await import('./ConnectingBanner');
-describe('ConnectingBanner terminal copy names the running channel CLI', () => {
- afterEach(() => {
- cleanup();
- (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ collabTerminal = true;
+ collabLastError = null;
+ (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;
+});
+
+describe('ConnectingBanner placement', () => {
+ test('the terminal variant starts below the application header rather than over it', () => {
+ render(<ConnectingBanner />);
+
+ expectVisualClassTokens(screen.getByRole('alert').className, [
+ 'fixed',
+ 'top-[var(--ok-app-header-height,0px)]',
+ 'inset-x-0',
+ ]);
});
+ test('the retrying variant starts below the application header rather than over it', async () => {
+ collabTerminal = false;
+ vi.useFakeTimers();
+ render(<ConnectingBanner />);
+ await act(async () => {
+ vi.advanceTimersByTime(1_000);
+ });
+
+ expectVisualClassTokens(screen.getByRole('status').className, [
+ 'fixed',
+ 'top-[var(--ok-app-header-height,0px)]',
+ 'inset-x-0',
+ ]);
+ });
+});
+
+describe('ConnectingBanner terminal copy names the running channel CLI', () => {
test.each([
[undefined, 'ok'],
['ok-beta', 'ok-beta'],
diff --git a/packages/app/src/components/ConnectingBanner.tsx b/packages/app/src/components/ConnectingBanner.tsx
index 6411c500d..11f1c15a9 100644
--- a/packages/app/src/components/ConnectingBanner.tsx
+++ b/packages/app/src/components/ConnectingBanner.tsx
@@ -69,7 +69,7 @@ export function ConnectingBanner() {
<div
role="alert"
aria-live="assertive"
- className="fixed top-0 inset-x-0 z-50 bg-red-500/95 text-red-950 text-sm text-center py-2 px-4 pl-[var(--ok-titlebar-reserve-left,1rem)] shadow-md flex items-center justify-center gap-3 flex-wrap"
+ className="fixed top-[var(--ok-app-header-height,0px)] inset-x-0 z-50 bg-red-500/95 text-red-950 text-sm text-center py-2 px-4 pl-[var(--ok-titlebar-reserve-left,1rem)] shadow-md flex items-center justify-center gap-3 flex-wrap"
>
<span>
{isNoCollabServer ? (
@@ -113,7 +113,7 @@ export function ConnectingBanner() {
<div
role="status"
aria-live="polite"
- className="fixed top-0 inset-x-0 z-50 bg-amber-500/95 text-amber-950 text-sm text-center py-2 px-4 pl-[var(--ok-titlebar-reserve-left,1rem)] shadow-md"
+ className="fixed top-[var(--ok-app-header-height,0px)] inset-x-0 z-50 bg-amber-500/95 text-amber-950 text-sm text-center py-2 px-4 pl-[var(--ok-titlebar-reserve-left,1rem)] shadow-md"
>
<Trans>Connecting — waiting for collab server</Trans>
</div>
diff --git a/packages/app/src/components/CornerCardStack.tsx b/packages/app/src/components/CornerCardStack.tsx
new file mode 100644
index 000000000..a944eb0e4
--- /dev/null
+++ b/packages/app/src/components/CornerCardStack.tsx
@@ -0,0 +1,22 @@
+import { useLingui } from '@lingui/react/macro';
+import { FeedbackCardMount } from '@/components/FeedbackCard';
+import { UpdateNotices } from '@/components/UpdateNotices';
+
+export function CornerCardStack() {
+ const { t } = useLingui();
+ return (
+ <section
+ aria-label={t`Updates and feedback`}
+ data-testid="corner-card-stack"
+ className="pointer-events-none fixed start-3 bottom-3 z-40 w-88 max-w-[calc(100vw-1.5rem)] has-[>:empty]:hidden"
+ >
+ <div
+ data-testid="corner-card-stack-column"
+ className="corner-card-column flex max-h-[calc(100vh-var(--ok-app-header-height,2.75rem)-1.5rem)] flex-col gap-2"
+ >
+ <UpdateNotices />
+ <FeedbackCardMount />
+ </div>
+ </section>
+ );
+}
diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsx
index b567b8c28..45ac7e334 100644
--- a/packages/app/src/components/DocPanel.dom.test.tsx
+++ b/packages/app/src/components/DocPanel.dom.test.tsx
@@ -4,6 +4,10 @@ import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { DocLinkFindingsState } from '@/editor/validation-audit-client';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
type WindowGlobals = { NodeFilter?: typeof NodeFilter };
type GlobalWithDomShims = typeof globalThis &
@@ -195,3 +199,39 @@ describe('DocPanel — Problems badge', () => {
expect(screen.getByText('99+')).toBeTruthy();
});
});
+
+describe('DocPanel — card top bar', () => {
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'okDesktop');
+ });
+
+ test('the icon row is a 44px top bar with no hairline under it', () => {
+ renderPanel('outline');
+ const header = document.querySelector('[data-doc-panel-header]');
+ expectVisualClassTokens(header?.getAttribute('class'), ['h-11', 'shrink-0']);
+ expectVisualClassTokensAbsent(header?.getAttribute('class'), [
+ 'pe-9',
+ '[-webkit-app-region:drag]',
+ 'shadow-[inset_0_-1px_0_var(--border)]',
+ ]);
+ expect(header?.contains(screen.getByRole('tab', { name: 'Outline' }))).toBe(true);
+ });
+
+ test('on desktop the empty top bar drags the window while the tab buttons opt out', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'editor' } },
+ });
+ renderPanel('outline');
+ const header = document.querySelector('[data-doc-panel-header]');
+ expect(header?.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(header?.getAttribute('class'), ['[-webkit-app-region:drag]']);
+ expectVisualClassTokens(
+ screen
+ .getByRole('tab', { name: 'Outline' })
+ .closest('[data-slot="toggle-group"]')
+ ?.getAttribute('class'),
+ ['[-webkit-app-region:no-drag]'],
+ );
+ });
+});
diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsx
index b3be0f535..ad681f9e6 100644
--- a/packages/app/src/components/DocPanel.tsx
+++ b/packages/app/src/components/DocPanel.tsx
@@ -6,6 +6,7 @@ import { AlertTriangle, Clock, Link2, ListTree, MessageSquare, Network } from 'l
import { lazy, Suspense, useEffect } from 'react';
import { CommentsTab } from '@/comments/CommentsTab';
import { setCommentsPanelOnScreen } from '@/comments/comments-panel-visibility';
+import { setDocPanelOnScreen } from '@/components/doc-panel-visibility';
import {
composeFixAllProblemsTerminalPaste,
composeLintFixTerminalPaste,
@@ -18,6 +19,7 @@ import type { PanelScope } from '@/components/PanelScopeHeader';
import { type DiagnosticLike, ProblemsPanel } from '@/components/ProblemsPanel';
import { TimelineContent } from '@/components/TimelinePanel';
import { Badge } from '@/components/ui/badge';
+import { PANE_CARD_TOP_BAR_CLASS } from '@/components/ui/pane-card';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { applyLintFixes, collectFixes } from '@/editor/apply-lint-fix';
@@ -26,6 +28,7 @@ import { useDocLintConfig } from '@/editor/lint-config-client';
import { useDocDiagnostics } from '@/editor/useDocDiagnostics';
import { useDocLinkFindings } from '@/editor/validation-audit-client';
import { useSingleFileMode } from '@/lib/single-file-mode';
+import { cn } from '@/lib/utils';
import { type DocProblemCounts, patchDocValidationSource } from '@/lib/validation-store';
export type PanelTab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems' | 'comments';
@@ -83,6 +86,13 @@ interface DocPanelProps {
onActiveTabChange: (tab: PanelTab) => void;
mode: DocPanelMode;
isCollapsed?: boolean;
+ onDestinationComplete?: (target?: HTMLElement) => void;
+ onDestinationRequested?: (
+ docName: string,
+ allowMissing?: boolean,
+ onReady?: () => void,
+ completion?: 'synced' | 'navigated',
+ ) => void;
}
export function DocPanel({
@@ -92,8 +102,11 @@ export function DocPanel({
onActiveTabChange,
mode,
isCollapsed = false,
+ onDestinationComplete,
+ onDestinationRequested,
}: DocPanelProps) {
const { t } = useLingui();
+ const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
const { activeProvider, activeDocName } = useDocumentContext();
const { data: lintConfig } = useDocLintConfig(docName);
const lintProvider = activeDocName === docName ? activeProvider : null;
@@ -142,17 +155,30 @@ export function DocPanel({
const showTabStrip = mode === 'doc' && tabs.length > 1;
useEffect(() => {
setCommentsPanelOnScreen(!isCollapsed && mode === 'doc' && effectiveTab === 'comments');
- return () => setCommentsPanelOnScreen(false);
+ setDocPanelOnScreen(!isCollapsed);
+ return () => {
+ setCommentsPanelOnScreen(false);
+ setDocPanelOnScreen(false);
+ };
}, [isCollapsed, mode, effectiveTab]);
return (
<>
{}
{showTabStrip ? (
- <div className="flex flex-row items-center justify-center gap-3 p-2">
+ <div
+ data-doc-panel-header=""
+ data-electron-drag={isElectronHost ? '' : undefined}
+ className={cn(
+ PANE_CARD_TOP_BAR_CLASS,
+ 'flex flex-row items-center justify-center gap-3 px-2',
+ isElectronHost && '[-webkit-app-region:drag]',
+ )}
+ >
<ToggleGroup
type="single"
variant="outline"
value={effectiveTab}
+ className={cn(isElectronHost && '[-webkit-app-region:no-drag]')}
onValueChange={(value: PanelTab) => {
if (value) onActiveTabChange(value);
}}
@@ -204,9 +230,19 @@ export function DocPanel({
className="min-h-0 flex-1"
>
{effectiveTab === 'outline' && (
- <OutlinePanel docName={docName} isSourceMode={isSourceMode} />
+ <OutlinePanel
+ docName={docName}
+ isSourceMode={isSourceMode}
+ onNavigated={onDestinationComplete}
+ />
+ )}
+ {effectiveTab === 'links' && (
+ <LinksPanel
+ docName={docName}
+ onDestinationRequested={onDestinationRequested}
+ onDestinationComplete={onDestinationComplete}
+ />
)}
- {effectiveTab === 'links' && <LinksPanel docName={docName} />}
{effectiveTab === 'graph' && (
<Suspense
fallback={
@@ -215,11 +251,16 @@ export function DocPanel({
</div>
}
>
- <LazyGraphPanel activeDocName={docName} />
+ <LazyGraphPanel
+ activeDocName={docName}
+ onDestinationRequested={onDestinationRequested}
+ />
</Suspense>
)}
{effectiveTab === 'timeline' && <TimelineContent docName={docName} />}
- {effectiveTab === 'comments' && <CommentsTab docName={docName} />}
+ {effectiveTab === 'comments' && (
+ <CommentsTab docName={docName} onDestinationComplete={onDestinationComplete} />
+ )}
{effectiveTab === 'problems' && (
<ProblemsPanel
docName={docName}
@@ -230,6 +271,8 @@ export function DocPanel({
onAutoFix={lintProvider !== null ? handleAutoFix : undefined}
onAskAi={lintProvider !== null && terminalLaunch !== null ? handleAskAi : undefined}
onFixWithAi={terminalLaunch !== null ? handleFixWithAi : undefined}
+ onDestinationComplete={onDestinationComplete}
+ onDestinationRequested={onDestinationRequested}
/>
)}
</div>
@@ -246,7 +289,7 @@ export function DocPanel({
</div>
}
>
- <LazyActivityModeContent />
+ <LazyActivityModeContent onDestinationRequested={onDestinationRequested} />
</Suspense>
</div>
)}
diff --git a/packages/app/src/components/DocPanelToggle.dom.test.tsx b/packages/app/src/components/DocPanelToggle.dom.test.tsx
new file mode 100644
index 000000000..030c6edd4
--- /dev/null
+++ b/packages/app/src/components/DocPanelToggle.dom.test.tsx
@@ -0,0 +1,76 @@
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+
+const { DocPanelToggle } = await import('./DocPanelToggle');
+
+function renderToggle(isPanelCollapsed = false) {
+ const onTogglePanel = () => {};
+ render(
+ <TooltipProvider>
+ <DocPanelToggle isPanelCollapsed={isPanelCollapsed} onTogglePanel={onTogglePanel} />
+ </TooltipProvider>,
+ );
+}
+
+describe('DocPanelToggle', () => {
+ afterEach(() => {
+ cleanup();
+ Reflect.deleteProperty(window, 'okDesktop');
+ });
+
+ test('renders the document-panel shortcut as a Kbd keycap', async () => {
+ const user = userEvent.setup();
+ renderToggle();
+
+ await user.hover(
+ screen.getByRole('button', {
+ name: `Hide panel (${formatShortcutLabel('toggle-document-panel')})`,
+ }),
+ );
+ const tooltip = await screen.findByRole('tooltip', {
+ name: `Hide panel ${formatShortcutLabel('toggle-document-panel')}`,
+ });
+ expect(tooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(
+ formatShortcut('toggle-document-panel'),
+ );
+ });
+
+ test('hides the document-panel toggle in a note window', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'note' } },
+ });
+
+ renderToggle();
+
+ expect(document.querySelector('[data-doc-panel-toggle]')).toBeNull();
+ });
+
+ test('exposes the panel state and target for assistive tech and the focus rescue', () => {
+ renderToggle(true);
+ const toggle = screen.getByRole('button', {
+ name: `Show panel (${formatShortcutLabel('toggle-document-panel')})`,
+ });
+
+ expect(toggle.hasAttribute('data-doc-panel-toggle')).toBe(true);
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ expect(toggle.getAttribute('aria-controls')).toBe('doc-panel');
+ });
+
+ test('opts out of the window drag band on desktop', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'editor' } },
+ });
+
+ renderToggle();
+
+ expectVisualClassTokens(document.querySelector('[data-doc-panel-toggle]')?.className, [
+ '[-webkit-app-region:no-drag]',
+ ]);
+ });
+});
diff --git a/packages/app/src/components/DocPanelToggle.tsx b/packages/app/src/components/DocPanelToggle.tsx
new file mode 100644
index 000000000..ced4a4bed
--- /dev/null
+++ b/packages/app/src/components/DocPanelToggle.tsx
@@ -0,0 +1,59 @@
+import { useLingui } from '@lingui/react/macro';
+import { PanelRightClose, PanelRightOpen } from 'lucide-react';
+import { Button } from '@/components/ui/button.tsx';
+import { Kbd } from '@/components/ui/kbd';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import { isNoteWindow } from '@/lib/note-window-mode';
+import { cn } from '@/lib/utils';
+
+interface DocPanelToggleProps {
+ readonly isPanelCollapsed: boolean;
+ readonly onTogglePanel: () => void;
+ readonly className?: string;
+ readonly panelId?: string;
+}
+
+export function DocPanelToggle({
+ isPanelCollapsed,
+ onTogglePanel,
+ className,
+ panelId = 'doc-panel',
+}: DocPanelToggleProps) {
+ const { t } = useLingui();
+ const panelShortcut = formatShortcut('toggle-document-panel');
+ const panelShortcutLabel = formatShortcutLabel('toggle-document-panel');
+ const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
+ if (isNoteWindow()) return null;
+ return (
+ <Tooltip>
+ <Button
+ data-doc-panel-toggle=""
+ variant="ghost"
+ size="icon"
+ onClick={onTogglePanel}
+ aria-expanded={!isPanelCollapsed}
+ aria-controls={panelId}
+ aria-label={
+ isPanelCollapsed
+ ? t`Show panel (${panelShortcutLabel})`
+ : t`Hide panel (${panelShortcutLabel})`
+ }
+ className={cn(
+ 'shrink-0 text-muted-foreground',
+ isElectronHost && '[-webkit-app-region:no-drag]',
+ className,
+ )}
+ asChild
+ >
+ <TooltipTrigger>
+ {isPanelCollapsed ? <PanelRightOpen /> : <PanelRightClose />}
+ </TooltipTrigger>
+ </Button>
+ <TooltipContent side="bottom">
+ <span>{isPanelCollapsed ? t`Show panel` : t`Hide panel`}</span>{' '}
+ <Kbd aria-label={panelShortcutLabel}>{panelShortcut}</Kbd>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index 4ac4774bc..68f1e9fa6 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -393,10 +393,28 @@ function ActivityEntryHost({
element.className = 'relative h-full min-h-0';
return element;
});
+ const lastScrollTop = useRef<number | null>(null);
+
+ useLayoutEffect(() => {
+ const recordScroll = (event: Event) => {
+ const target = event.target;
+ if (target instanceof HTMLElement && target.dataset.testid === 'editor-scroll-container') {
+ lastScrollTop.current = target.scrollTop;
+ }
+ };
+ host.addEventListener('scroll', recordScroll, true);
+ return () => host.removeEventListener('scroll', recordScroll, true);
+ }, [host]);
useLayoutEffect(() => {
if (hostMount === null) return;
hostMount.append(host);
+ const scrollContainer = host.querySelector<HTMLElement>(
+ '[data-testid="editor-scroll-container"]',
+ );
+ if (scrollContainer && lastScrollTop.current !== null) {
+ scrollContainer.scrollTop = lastScrollTop.current;
+ }
return () => host.remove();
}, [host, hostMount]);
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 2ca81386c..72c057ebf 100644
--- a/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
@@ -1,6 +1,7 @@
import { cleanup, render, screen } from '@testing-library/react';
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';
type EditorMode = 'wysiwyg' | 'source';
@@ -112,12 +113,14 @@ const { EditorArea } = await import('./EditorArea');
function renderEditorArea(editorMode: EditorMode) {
return render(
<ConfigProvider collabUrl={null}>
- <EditorArea
- editorMode={editorMode}
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- />
+ <SidebarProvider>
+ <EditorArea
+ editorMode={editorMode}
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ />
+ </SidebarProvider>
</ConfigProvider>,
);
}
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index cdf053d7e..b47607028 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -1,9 +1,26 @@
import type { HocuspocusProvider } from '@hocuspocus/provider';
-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { type ReactNode, useEffect, useState } from 'react';
+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 { MIN_AGENTS_PANEL_WIDTH } from '@/lib/agents-panel-width-store';
+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';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneId,
+ type PaneVisibilityRequest,
+ 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 { FileListHostProvider } from './FileListHost';
type SettingsDialogShellProps = {
open: boolean;
@@ -181,6 +198,7 @@ vi.doMock('./TerminalDock', () => ({
},
}));
+let editorWorkspaceMounts = 0;
vi.doMock('./EditorWorkspace', () => ({
EditorWorkspace: ({
renderHeader,
@@ -192,32 +210,55 @@ vi.doMock('./EditorWorkspace', () => ({
isFocused: boolean;
activityDocName: string | null;
}) => ReactNode;
- }) => (
- <>
- {renderHeader(<div data-testid="workspace-tabs" />)}
- {renderPane({
- pane: { id: 'pane-test' },
- isFocused: true,
- activityDocName: null,
- })}
- </>
- ),
+ }) => {
+ useEffect(() => {
+ editorWorkspaceMounts += 1;
+ }, []);
+ return (
+ <>
+ {renderHeader(<div data-testid="workspace-tabs" />)}
+ {renderPane({
+ pane: { id: 'pane-test' },
+ isFocused: true,
+ activityDocName: null,
+ })}
+ </>
+ );
+ },
}));
-let groupLayout: Record<string, number> = {};
-let groupSetLayoutCalls: Array<Record<string, number>> = [];
+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 = {};
+let innerLayout: MockLayout = { ...INNER_LAYOUT_DOC_CLOSED };
+let groupSetLayoutCalls: MockLayout[] = [];
+let innerSetLayoutCalls: MockLayout[] = [];
let rejectNextGroupLayoutWrite = false;
let rejectGroupLayoutWrites = false;
-let groupOnLayoutChanged:
- | ((layout: Record<string, number>, meta: { isUserInteraction: boolean }) => void)
- | null = null;
+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 panelIsCollapsed = false;
let mockGroupPx = 1360;
+let mockInnerPx: number | null = null;
+let mockFileListPx = 0;
let mockPanelPercentage: number | null = null;
let mockPanelPx: number | null = null;
-let panelExpandCalls = 0;
let deferPanelGeometryCommit = false;
-let committedGroupLayout: Record<string, number> = {};
+let committedGroupLayout: MockLayout = {};
+let committedInnerLayout: MockLayout = {};
+let innerSetLayoutPx: number[] = [];
+let deliverDocPanelResizeAfterLayout = false;
+let lastDeliveredDocPanelSize: { asPercentage: number; inPixels: number } | null = null;
beforeEach(() => {
mockPanelPercentage = null;
@@ -225,22 +266,93 @@ beforeEach(() => {
rejectGroupLayoutWrites = false;
deferPanelGeometryCommit = false;
committedGroupLayout = {};
+ committedInnerLayout = {};
+ innerLayout = { ...INNER_LAYOUT_DOC_CLOSED };
+ innerSetLayoutCalls = [];
+ innerSetLayoutPx = [];
+ deliverDocPanelResizeAfterLayout = false;
+ lastDeliveredDocPanelSize = null;
+ innerRowHandlers.onLayoutChanged = null;
+ innerRowHandlers.onLayoutChange = null;
+ mockInnerPx = null;
+ mockFileListPx = 0;
+ conflictedDocName = null;
});
-function geometryLayout(): Record<string, number> {
- return deferPanelGeometryCommit ? committedGroupLayout : groupLayout;
+const renderedInnerPanelIds = () =>
+ [...screen.getByTestId('resizable-group-inner').children].map((el) => el.id).filter(Boolean);
+const innerRowWithDoc = (docPx: number, editorColumnPx: number): MockLayout => ({
+ 'workspace-main': 100 - (docPx / editorColumnPx) * 100,
+ 'doc-panel': (docPx / editorColumnPx) * 100,
+});
+const innerResidualWidthPx = () =>
+ screen
+ .getByTestId('resizable-group-inner')
+ .querySelector<HTMLElement>(':scope > [data-panel]:not([id])')
+ ?.getBoundingClientRect().width;
+
+function lastInnerWritePx(id: string): number | null {
+ const layout = innerSetLayoutCalls.at(-1);
+ const px = innerSetLayoutPx.at(-1);
+ const pct = layout?.[id];
+ return pct == null || px == null ? null : (pct / 100) * px;
}
-function mockedPanelWidthPx(element: HTMLElement): number {
- const layout = geometryLayout();
- if (element.id !== '') return ((layout[element.id] ?? 0) / 100) * mockGroupPx;
+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 residualPanelWidthPx(element: HTMLElement, row: EditorRow): number {
+ const layout = geometryLayout(row);
const group = element.parentElement;
if (group == null) return 0;
let claimedPercentage = 0;
for (const sibling of group.querySelectorAll<HTMLElement>(':scope > [data-panel]')) {
if (sibling.id !== '') claimedPercentage += layout[sibling.id] ?? 0;
}
- return (Math.max(0, 100 - claimedPercentage) / 100) * mockGroupPx;
+ 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);
}
function measureMockedPanel(element: HTMLDivElement | null) {
@@ -257,57 +369,118 @@ function measureMockedPanel(element: HTMLDivElement | null) {
get: () => Math.round(mockedPanelWidthPx(element)),
});
}
-vi.doMock('react-resizable-panels', () => ({
- usePanelRef: () => ({
- current: {
- collapse: () => {},
- expand: () => {
- panelExpandCalls += 1;
- },
- getSize: () => ({
- asPercentage: mockPanelPercentage ?? 25,
- inPixels: mockPanelPx ?? mockGroupPx / 4,
- }),
- isCollapsed: () => panelIsCollapsed,
- },
- }),
- useGroupRef: () => ({
- current: {
- getLayout: () => groupLayout,
- setLayout: (layout: Record<string, number>) => {
- groupSetLayoutCalls.push(layout);
- if (rejectNextGroupLayoutWrite) {
- rejectNextGroupLayoutWrite = false;
- return;
- }
- if (rejectGroupLayoutWrites) return;
- groupLayout = layout;
- if (deferPanelGeometryCommit) {
- queueMicrotask(() => {
- committedGroupLayout = layout;
- });
- } else {
- committedGroupLayout = layout;
+
+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);
}
- },
+ }
},
- }),
+ };
+}
+
+const groupHandles: Record<EditorRow, ReturnType<typeof createGroupHandle>> = {
+ outer: createGroupHandle('outer'),
+ inner: createGroupHandle('inner'),
+};
+
+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,
+ },
+ };
+ },
+ useGroupRef: () => useRef<ReturnType<typeof createGroupHandle> | null>(null),
}));
vi.doMock('@/components/ui/resizable', () => ({
ResizablePanelGroup: ({
children,
+ onLayoutChange,
onLayoutChanged,
+ groupRef,
+ 'data-editor-row': rowProp,
+ 'data-dragging': dragging,
}: {
children: ReactNode;
- onLayoutChanged?: (
- layout: Record<string, number>,
- meta: { isUserInteraction: boolean },
- ) => void;
+ onLayoutChange?: (layout: MockLayout) => void;
+ onLayoutChanged?: LayoutChangedHandler;
+ groupRef?: { current: ReturnType<typeof createGroupHandle> | null };
+ 'data-editor-row'?: string;
+ 'data-dragging'?: boolean;
}) => {
- groupOnLayoutChanged = onLayoutChanged ?? null;
+ 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;
+ }
return (
- <div data-testid="resizable-group" data-group="true" data-slot="resizable-panel-group">
+ <div
+ data-testid={row === 'inner' ? 'resizable-group-inner' : 'resizable-group'}
+ data-group="true"
+ data-editor-row={row}
+ data-dragging={dragging || undefined}
+ data-slot="resizable-panel-group"
+ >
{children}
</div>
);
@@ -318,17 +491,28 @@ vi.doMock('@/components/ui/resizable', () => ({
minSize,
maxSize,
onResize,
+ role,
+ 'aria-label': ariaLabel,
+ inert,
+ style,
}: {
children: ReactNode;
+ style?: CSSProperties;
id?: string;
minSize?: string | number;
maxSize?: string | number;
onResize?: (size: { asPercentage: number; inPixels: number }) => void;
+ role?: string;
+ 'aria-label'?: string;
+ inert?: boolean;
}) => {
if (id != null) railPanelOnResizeById.set(id, onResize ?? null);
return (
<div
id={id}
+ {...(role == null ? {} : { role, 'aria-label': ariaLabel })}
+ inert={inert}
+ style={style}
data-panel="true"
data-slot="resizable-panel"
ref={measureMockedPanel}
@@ -347,29 +531,40 @@ vi.doMock('@/components/ui/resizable', () => ({
'aria-controls'?: string;
'aria-label'?: string;
'data-agents-panel-resize-handle'?: string;
+ 'data-doc-panel-handle'?: string;
+ 'data-terminal-panel-handle'?: string;
+ style?: CSSProperties;
}) => (
<hr
+ style={props.style}
aria-controls={props['aria-controls']}
aria-label={props['aria-label']}
aria-valuenow={50}
data-testid="resizable-handle"
data-agents-panel-resize-handle={props['data-agents-panel-resize-handle']}
+ data-doc-panel-handle={props['data-doc-panel-handle']}
+ data-terminal-panel-handle={props['data-terminal-panel-handle']}
onPointerDown={onPointerDown}
tabIndex={0}
/>
),
}));
-vi.doMock('@/hooks/use-doc-panel-layout', () => ({
- useDocPanelLayout: () => ({ layout: 'panel', autoCollapse: false }),
-}));
-
vi.doMock('@/hooks/use-document-stats', () => ({
useDocumentStats: () => null,
}));
+let conflictedDocName: string | null = null;
vi.doMock('@/hooks/use-conflicts', () => ({
- useDocConflict: () => null,
+ useDocConflict: (docName: string | null) =>
+ docName != null && docName === conflictedDocName
+ ? {
+ file: `${docName}.md`,
+ docName,
+ detectedAt: '2026-09-25T00:00:00.000Z',
+ conflict: 'merge-native',
+ }
+ : null,
useConflicts: () => ({
conflicts: [],
loading: false,
@@ -414,6 +609,25 @@ vi.doMock('./EditorFooter', () => ({
EditorFooter: () => <div data-testid="editor-footer" />,
}));
+vi.doMock('@/components/DocPanelToggle', () => ({
+ DocPanelToggle: ({
+ isPanelCollapsed,
+ onTogglePanel,
+ }: {
+ isPanelCollapsed: boolean;
+ onTogglePanel: () => void;
+ }) => (
+ <button
+ type="button"
+ data-doc-panel-toggle=""
+ aria-controls="doc-panel"
+ aria-expanded={!isPanelCollapsed}
+ aria-label={isPanelCollapsed ? 'Show panel' : 'Hide panel'}
+ onClick={onTogglePanel}
+ />
+ ),
+}));
+
vi.doMock('@/components/settings/SettingsDialogShell', () => ({
SettingsDialogShell: (props: SettingsDialogShellProps) => {
shellProps.push(props);
@@ -429,13 +643,19 @@ vi.doMock('@/lib/use-settings-route', () => ({
}));
const { EditorArea } = 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');
+function render(ui: ReactNode) {
+ return rtlRender(ui, { wrapper: SidebarProvider });
+}
+
function renderEditorArea() {
return render(
<EditorArea
@@ -663,10 +883,10 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
mockGroupPx = 1360;
mockPanelPercentage = null;
mockPanelPx = null;
- panelExpandCalls = 0;
deferPanelGeometryCommit = false;
committedGroupLayout = {};
groupOnLayoutChanged = null;
+ groupOnLayoutChange = null;
toastInfoMessages = [];
});
@@ -919,19 +1139,22 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
render(<EditorArea {...baseProps} />);
groupLayout = {
'editor-main': 100,
- 'doc-panel': 0,
'terminal-column': 0,
'agents-column': 0,
};
groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
act(() => emitLocalMenuAction('toggle-doc-panel'));
+ const correctedInner = innerSetLayoutCalls.at(-1);
+ 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?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
expect(corrected?.['terminal-column']).toBe(0);
expect(corrected?.['agents-column']).toBe(0);
- expect(corrected?.['editor-main']).toBeCloseTo(100 - pctOf(320), 3);
+ expect(corrected?.['editor-main']).toBe(100);
});
test('a second toggle re-opens the doc panel the first toggle collapsed', () => {
@@ -939,18 +1162,19 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
docCtx = DOC_LIVE_CTX;
render(<EditorArea {...baseProps} />);
groupLayout = {
- 'editor-main': 75,
- 'doc-panel': 25,
+ 'editor-main': 100,
'terminal-column': 0,
'agents-column': 0,
};
- groupSetLayoutCalls = [];
+ innerLayout = { 'workspace-main': 75, 'doc-panel': 25 };
+ innerSetLayoutCalls = [];
act(() => emitLocalMenuAction('toggle-doc-panel'));
- expect(groupSetLayoutCalls.at(-1)?.['doc-panel']).toBe(0);
+ expect(innerSetLayoutCalls.at(-1)?.['doc-panel']).toBe(0);
act(() => emitLocalMenuAction('toggle-doc-panel'));
- expect(groupSetLayoutCalls.at(-1)?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
+ expect(innerSetLayoutCalls.at(-1)?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
+ 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 () => {
@@ -958,12 +1182,17 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
docCtx = DOC_LIVE_CTX;
const view = render(<EditorArea {...baseProps} agentsVisible />);
expect(groupSetLayoutCalls).toHaveLength(0);
- groupLayout = { 'editor-main': 70, 'doc-panel': 30 };
+ expect(innerSetLayoutCalls).toHaveLength(0);
+ groupLayout = { 'editor-main': 70, 'agents-column': 30 };
+ innerLayout = { 'workspace-main': 70, 'doc-panel': 30 };
view.rerender(<EditorArea {...baseProps} agentsVisible={false} />);
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).toBeDefined();
- expect(corrected?.['doc-panel']).toBe(0);
+ expect(corrected?.['agents-column']).toBe(0);
expect(corrected?.['editor-main']).toBe(100);
});
@@ -976,12 +1205,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(
<EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
);
- groupLayout = {
- 'editor-main': 100 - (320 / 1610) * 100 - (740 / 1610) * 100,
- 'doc-panel': (320 / 1610) * 100,
- 'terminal-column': (740 / 1610) * 100,
- 'agents-column': 0,
- };
+ groupLayout = { ...RAIL_OUTER_1610 };
+ innerLayout = { ...RAIL_INNER_1610 };
groupSetLayoutCalls = [];
view.rerender(
@@ -997,12 +1222,19 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
expect(terminalPercentage).toBeCloseTo((740 / 1610) * 100, 3);
});
- const RAIL_LAYOUT_1610 = {
- 'editor-main': 100 - (320 / 1610) * 100 - (740 / 1610) * 100,
- 'doc-panel': (320 / 1610) * 100,
+ 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,
+ });
+ const strandedInner1610 = (terminalPercentage: number): MockLayout =>
+ innerRowWithDoc(320, ((100 - terminalPercentage) / 100) * 1610);
const readExhaustedReports = (warnings: readonly string[]) =>
warnings
@@ -1022,7 +1254,7 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
})
.filter((entry) => entry?.event === 'right-rail-pin-exhausted');
- async function withSynchronousFrames(run: () => void) {
+ async function withSynchronousFrames(run: () => void | Promise<void>) {
const warnings: string[] = [];
const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {
warnings.push(String(message));
@@ -1033,7 +1265,7 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
return 0;
}) as typeof globalThis.requestAnimationFrame;
try {
- run();
+ await run();
await act(async () => {});
} finally {
globalThis.requestAnimationFrame = realRequestAnimationFrame;
@@ -1049,8 +1281,10 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(
<EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
);
- groupLayout = { ...RAIL_LAYOUT_1610 };
- committedGroupLayout = { ...RAIL_LAYOUT_1610 };
+ groupLayout = { ...RAIL_OUTER_1610 };
+ committedGroupLayout = { ...RAIL_OUTER_1610 };
+ innerLayout = { ...RAIL_INNER_1610 };
+ committedInnerLayout = { ...RAIL_INNER_1610 };
deferPanelGeometryCommit = true;
groupSetLayoutCalls = [];
@@ -1074,12 +1308,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(
<EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
);
- groupLayout = {
- 'editor-main': 100 - (320 / 1610) * 100 - strandedTerminalPercentage,
- 'doc-panel': (320 / 1610) * 100,
- 'terminal-column': strandedTerminalPercentage,
- 'agents-column': 0,
- };
+ groupLayout = strandedOuter1610(strandedTerminalPercentage);
+ innerLayout = strandedInner1610(strandedTerminalPercentage);
rejectGroupLayoutWrites = true;
const warnings = await withSynchronousFrames(() => {
@@ -1105,12 +1335,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(
<EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
);
- groupLayout = {
- 'editor-main': 100 - (320 / 1610) * 100 - 44,
- 'doc-panel': (320 / 1610) * 100,
- 'terminal-column': 44,
- 'agents-column': 0,
- };
+ groupLayout = strandedOuter1610(44);
+ innerLayout = strandedInner1610(44);
rejectGroupLayoutWrites = true;
const warnings = await withSynchronousFrames(() => {
@@ -1185,7 +1411,6 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
);
groupLayout = {
'editor-main': 60,
- 'doc-panel': 0,
'terminal-column': 40,
'agents-column': 0,
};
@@ -1231,11 +1456,11 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
);
act(() => emitLocalMenuAction('toggle-doc-panel'));
groupLayout = {
- 'editor-main': ((groupPx - terminalRenderedPx - docRenderedPx) / groupPx) * 100,
- 'doc-panel': (docRenderedPx / groupPx) * 100,
+ 'editor-main': ((groupPx - terminalRenderedPx) / groupPx) * 100,
'terminal-column': (terminalRenderedPx / groupPx) * 100,
'agents-column': 0,
};
+ innerLayout = innerRowWithDoc(docRenderedPx, groupPx - terminalRenderedPx);
const warnings = await withSynchronousFrames(() => {
view.rerender(
@@ -1266,12 +1491,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(
<EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
);
- groupLayout = {
- 'editor-main': 100 - (320 / 1610) * 100 - 44,
- 'doc-panel': (320 / 1610) * 100,
- 'terminal-column': 44,
- 'agents-column': 0,
- };
+ groupLayout = strandedOuter1610(44);
+ innerLayout = strandedInner1610(44);
rejectGroupLayoutWrites = true;
const warnings = await withSynchronousFrames(() => {
@@ -1300,12 +1521,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(
<EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
);
- groupLayout = {
- 'editor-main': 100 - (320 / 1610) * 100 - 44,
- 'doc-panel': (320 / 1610) * 100,
- 'terminal-column': 44,
- 'agents-column': 0,
- };
+ groupLayout = strandedOuter1610(44);
+ innerLayout = strandedInner1610(44);
rejectGroupLayoutWrites = true;
const warnings = await withSynchronousFrames(() => {
@@ -1333,18 +1550,46 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
expect(reports.filter((report) => report.trigger === 'doc-slot-presence').length).toBe(1);
});
+ test('an editor hide the row never settles into reports its own pin outcome under its own cap', async () => {
+ setViewportWidth(1400);
+ docCtx = DOC_LIVE_CTX;
+ const view = render(<EditorArea {...baseProps} agentsVisible />);
+ groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
+ 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 = 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);
docCtx = DOC_LIVE_CTX;
const view = render(<EditorArea {...baseProps} agentsVisible={false} />);
- groupLayout = { 'editor-main': 45, 'doc-panel': 25, 'agents-column': 30 };
+ groupLayout = { 'editor-main': 70, 'agents-column': 30 };
+ innerLayout = innerRowWithDoc(340, 0.7 * 1360);
view.rerender(<EditorArea {...baseProps} agentsVisible />);
await act(async () => {});
const corrected = groupSetLayoutCalls.at(-1);
expect(corrected).toBeDefined();
- expect(corrected?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
expect(corrected?.['agents-column']).toBeCloseTo(pctOf(480), 3);
- expect(corrected?.['editor-main']).toBeCloseTo(100 - pctOf(320) - 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);
});
test('the rail keeps one panel-ID set from a document to a new tab', () => {
@@ -1352,18 +1597,22 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
docCtx = DOC_LIVE_CTX;
const view = render(<EditorArea {...baseProps} agentsVisible />);
const withDocument = renderedPanelIds();
- expect(withDocument).toEqual(['doc-panel', 'terminal-column', 'agents-column']);
+ const withDocumentInner = renderedInnerPanelIds();
+ expect(withDocument).toEqual(['terminal-column', 'agents-column']);
+ expect(withDocumentInner).toEqual(['doc-panel']);
docCtx = EMPTY_DOC_CTX;
view.rerender(<EditorArea {...baseProps} agentsVisible />);
expect(renderedPanelIds()).toEqual(withDocument);
- expect(document.getElementById('doc-panel')?.childElementCount).toBe(0);
+ expect(renderedInnerPanelIds()).toEqual(withDocumentInner);
+ expect(document.getElementById('doc-panel')?.textContent).toBe('');
});
test('the rail keeps one panel-ID set across every view kind', () => {
setViewportWidth(1400);
- const expected = ['doc-panel', 'terminal-column', 'agents-column'];
+ const expected = ['terminal-column', 'agents-column'];
+ const expectedInner = ['doc-panel'];
for (const ctx of [
DOC_LIVE_CTX,
EMPTY_DOC_CTX,
@@ -1376,6 +1625,7 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
docCtx = ctx;
render(<EditorArea {...baseProps} agentsVisible />);
expect(renderedPanelIds()).toEqual(expected);
+ expect(renderedInnerPanelIds()).toEqual(expectedInner);
}
});
@@ -1399,7 +1649,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
view.rerender(<EditorArea {...baseProps} agentsVisible />);
expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
- expect(renderedPanelIds()).toEqual(['doc-panel', 'terminal-column', 'agents-column']);
+ expect(renderedPanelIds()).toEqual(['terminal-column', 'agents-column']);
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
expect(document.getElementById('doc-panel')?.childElementCount).toBe(1);
window.location.hash = '';
});
@@ -1409,27 +1660,28 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
docCtx = DOC_LIVE_CTX;
const view = render(<EditorArea {...baseProps} />);
groupLayout = {
- 'editor-main': 60,
- 'doc-panel': 40,
+ 'editor-main': 100,
'terminal-column': 0,
'agents-column': 0,
};
- groupSetLayoutCalls = [];
+ innerLayout = { 'workspace-main': 60, 'doc-panel': 40 };
+ innerSetLayoutCalls = [];
docCtx = ASSET_DOC_CTX;
view.rerender(<EditorArea {...baseProps} />);
await act(async () => {});
- const emptied = groupSetLayoutCalls.at(-1);
+ const emptied = innerSetLayoutCalls.at(-1);
expect(emptied?.['doc-panel']).toBe(0);
- expect(emptied?.['editor-main']).toBe(100);
+ expect(emptied?.['workspace-main']).toBe(100);
- groupLayout = { ...groupLayout, 'editor-main': 100, 'doc-panel': 0 };
+ innerLayout = { 'workspace-main': 100, 'doc-panel': 0 };
docCtx = DOC_LIVE_CTX;
view.rerender(<EditorArea {...baseProps} />);
await act(async () => {});
- const refilled = groupSetLayoutCalls.at(-1);
+ const refilled = innerSetLayoutCalls.at(-1);
expect(refilled?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
- expect(refilled?.['editor-main']).toBeCloseTo(100 - pctOf(320), 3);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ expect(refilled?.['workspace-main']).toBeCloseTo(100 - pctOf(320), 3);
});
test('folder-view agent activity fills the shared slot, not a panel of its own', () => {
@@ -1447,18 +1699,44 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const view = render(<EditorArea {...baseProps} />);
groupLayout = {
'editor-main': 100,
- 'doc-panel': 0,
'terminal-column': 0,
'agents-column': 0,
};
- groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
docCtx = { ...FOLDER_AGENT_CTX, docPanelExpandSignal: 1 };
view.rerender(<EditorArea {...baseProps} />);
await act(async () => {});
- const opened = groupSetLayoutCalls.at(-1);
+ const opened = innerSetLayoutCalls.at(-1);
expect(opened?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ });
+
+ test('an avatar click with the editor hidden shows the editor, then opens the side panel', async () => {
+ setViewportWidth(1024);
+ docCtx = FOLDER_DOC_CTX;
+ __resetPaneVisibilityStoreForTests();
+ 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 = [];
+
+ docCtx = { ...FOLDER_AGENT_CTX, docPanelExpandSignal: 1 };
+ view.rerender(<EditorArea {...baseProps} editorVisible={false} />);
+ await act(async () => {});
+ expect(requests).toEqual([{ pane: 'editor', open: true }]);
+
+ view.rerender(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ __resetPaneVisibilityStoreForTests();
});
test('a view with no document pane pins the slot shut and ignores the toggle', async () => {
@@ -1466,23 +1744,24 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
docCtx = ASSET_DOC_CTX;
groupLayout = {
'editor-main': 100 - pctOf(480),
- 'doc-panel': 0,
'terminal-column': 0,
'agents-column': pctOf(480),
};
render(<EditorArea {...baseProps} agentsVisible />);
groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
groupLayout = {
- 'editor-main': 45,
- 'doc-panel': 25,
+ '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 () => {
@@ -1510,6 +1789,37 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
expect(visibleChanges.at(-1)).toBe(false);
});
+ 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[] = [];
+ render(
+ <EditorArea
+ {...baseProps}
+ 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();
+ });
+
test('releasing an agents-handle drag in the middle band settles at the minimum', () => {
setViewportWidth(1400);
const visibleChanges: boolean[] = [];
@@ -1579,11 +1889,11 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
setViewportWidth(1400);
docCtx = FOLDER_DOC_CTX;
groupLayout = {
- 'editor-main': 100 - pctOf(320 + 440 + 480),
- 'doc-panel': pctOf(320),
+ '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 {
@@ -1597,11 +1907,11 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
/>,
);
groupLayout = {
- 'editor-main': 100 - pctOf(320 + 440 + 250),
- 'doc-panel': pctOf(320),
+ '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;
@@ -1648,19 +1958,19 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
setViewportWidth(1400);
docCtx = FOLDER_DOC_CTX;
groupLayout = {
- 'editor-main': 100 - pctOf(320 + 480),
- 'doc-panel': pctOf(320),
+ '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(320 + 250),
- 'doc-panel': pctOf(320),
+ 'editor-main': 100 - pctOf(250),
'agents-column': pctOf(250),
};
+ innerLayout = innerRowWithDoc(320, 1360 - 250);
mockPanelPx = 250;
mockPanelPercentage = pctOf(250);
rejectNextGroupLayoutWrite = true;
@@ -1996,6 +2306,22 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
expect(handle.getAttribute('aria-controls')).toBe(AGENTS_COLUMN_ID);
});
+ 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" />);
+
+ 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" />);
@@ -2218,19 +2544,19 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
setViewportWidth(1400);
docCtx = FOLDER_DOC_CTX;
groupLayout = {
- 'editor-main': 100 - pctOf(320 + 480),
- 'doc-panel': pctOf(320),
+ '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(320 + 250),
- 'doc-panel': pctOf(320),
+ 'editor-main': 100 - pctOf(250),
'agents-column': pctOf(250),
};
+ innerLayout = innerRowWithDoc(320, 1360 - 250);
rejectNextGroupLayoutWrite = true;
act(() => {
groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
@@ -2242,12 +2568,12 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
if (!(docHandle instanceof HTMLElement)) throw new Error('doc-panel resize handle not found');
docHandle.focus();
groupLayout = {
- 'editor-main': 100 - pctOf(320 + 600),
- 'doc-panel': pctOf(320),
+ 'editor-main': 100 - pctOf(600),
'agents-column': pctOf(600),
};
+ innerLayout = innerRowWithDoc(320, 1360 - 600);
act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
+ innerRowHandlers.onLayoutChanged?.(innerLayout, { isUserInteraction: true });
});
frames.run(30);
@@ -2266,11 +2592,16 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
({ panelId, terminalVisible }) => {
setViewportWidth(1400);
if (!terminalVisible) docCtx = FOLDER_DOC_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOf(320 + 480),
- [panelId]: pctOf(320),
- 'agents-column': pctOf(480),
- };
+ const outerRowWith = (agentsPx: number): MockLayout =>
+ 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(
@@ -2282,11 +2613,8 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
/>,
);
getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(320 + 250),
- [panelId]: pctOf(320),
- 'agents-column': pctOf(250),
- };
+ groupLayout = outerRowWith(250);
+ if (!terminalVisible) innerLayout = innerRowWithDoc(320, 1360 - 250);
rejectNextGroupLayoutWrite = true;
act(() => {
groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
@@ -2302,7 +2630,11 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
});
handle.focus();
act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
+ if (panelId === 'doc-panel') {
+ innerRowHandlers.onLayoutChanged?.(innerLayout, { isUserInteraction: true });
+ } else {
+ groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
+ }
});
frames.run(30);
@@ -2328,10 +2660,10 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
render(<EditorArea {...baseProps} agentsVisible />);
const handle = getAgentsHandle();
handle.focus();
- const panelWidths = [880, 0, 0, 320];
+ const panelWidths = [880, 0, 320];
const panelElements = screen
.getByTestId('resizable-group')
- .querySelectorAll('[data-slot="resizable-panel"]');
+ .querySelectorAll(':scope > [data-slot="resizable-panel"]');
expect(panelElements).toHaveLength(panelWidths.length);
panelElements.forEach((element, index) => {
Object.defineProperty(element, 'getBoundingClientRect', {
@@ -2346,7 +2678,6 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
mockPanelPx = 320.004;
groupLayout = {
'editor-main': 100 - mockPanelPercentage,
- 'doc-panel': 0,
'terminal-column': 0,
'agents-column': mockPanelPercentage,
};
@@ -2363,21 +2694,17 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
setViewportWidth(1400);
const visibleChanges: boolean[] = [];
render(
- <TooltipProvider>
- <EditorArea
- {...baseProps}
- agentsVisible
- onRevealAgents={() => {}}
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
- />
- </TooltipProvider>,
+ <EditorArea
+ {...baseProps}
+ agentsVisible
+ onAgentsVisibleChange={(visible: boolean) => {
+ visibleChanges.push(visible);
+ }}
+ />,
);
getAgentsHandle().focus();
groupLayout = {
'editor-main': 100,
- 'doc-panel': 0,
'terminal-column': 0,
'agents-column': 0,
};
@@ -2388,7 +2715,6 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
});
expect(groupSetLayoutCalls).toHaveLength(0);
expect(visibleChanges).toHaveLength(0);
- expect(screen.getByRole('button', { name: 'Open agents panel' })).toBeTruthy();
});
test('releasing an agents-handle drag with the column still open does NOT hide the panel', async () => {
@@ -2425,7 +2751,7 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
});
groupSetLayoutCalls = [];
- groupLayout = { 'editor-main': 45, 'doc-panel': 25, 'agents-column': 30 };
+ groupLayout = { 'editor-main': 70, 'agents-column': 30 };
view.rerender(<EditorArea {...baseProps} agentsVisible={false} />);
await act(async () => {});
expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
@@ -2508,93 +2834,34 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
});
});
-describe('EditorArea session-panel edge reveal tabs', () => {
- const revealProps = {
- editorMode: 'wysiwyg',
- onModeChange: () => {},
- activeTab: 'timeline',
- onActiveTabChange: () => {},
- terminalBridge: { terminal: {} } as never,
- onAgentsVisibleChange: () => {},
- onTerminalVisibleChange: () => {},
- onRevealAgents: () => {},
- } as const;
-
+describe('EditorArea agents panel region', () => {
beforeEach(() => {
cleanup();
docCtx = EMPTY_DOC_CTX;
});
- const renderArea = (props: Record<string, unknown>) =>
+ test('the agents panel mounts in the panels region, not the header', () => {
render(
- <TooltipProvider>
- <EditorArea {...revealProps} {...props} />
- </TooltipProvider>,
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ terminalBridge={{ terminal: {} } as never}
+ onAgentsVisibleChange={() => {}}
+ onTerminalVisibleChange={() => {}}
+ agentsVisible
+ />,
);
-
- test('the agents tab is up while the panel is hidden, even with no chats', () => {
- renderArea({ agentsVisible: false });
- const reveal = screen.getByRole('button', { name: 'Open agents panel' });
- const header = document.querySelector('[data-editor-area-header]');
- const panels = document.querySelector('[data-editor-area-panels]');
-
- expect(header).toBeTruthy();
- expect(panels).toBeTruthy();
- expect(header?.contains(screen.getByTestId('workspace-tabs'))).toBe(true);
- expect(panels?.contains(reveal)).toBe(true);
- expect(header?.contains(reveal)).toBe(false);
- });
-
- test('the agents tab goes away once the panel is open', () => {
- renderArea({ agentsVisible: true });
- expect(screen.queryByRole('button', { name: 'Open agents panel' })).toBeNull();
const header = document.querySelector('[data-editor-area-header]');
const panels = document.querySelector('[data-editor-area-panels]');
const agentMount = document.querySelector('[data-agents-panel-mount]');
expect(header).toBeTruthy();
+ expect(agentMount).toBeTruthy();
expect(panels?.contains(agentMount)).toBe(true);
expect(header?.contains(agentMount)).toBe(false);
});
-
- test('the measured-collapse reveal restores the preferred rail width without panel expand', () => {
- mockGroupPx = 1360;
- mockPanelPercentage = null;
- mockPanelPx = null;
- panelExpandCalls = 0;
- renderArea({ agentsVisible: true });
- groupLayout = {
- 'editor-main': 100,
- 'doc-panel': 0,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- groupSetLayoutCalls = [];
-
- fireEvent.click(screen.getByRole('button', { name: 'Open agents panel' }));
-
- expect(panelExpandCalls).toBe(0);
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo((480 / 1360) * 100, 3);
- });
-
- test('a note window never renders the agents reveal tab', () => {
- Object.defineProperty(window, 'okDesktop', {
- configurable: true,
- value: {
- config: { mode: 'note' },
- editor: { notifyViewMenuStateChanged: () => {} },
- },
- });
- try {
- renderArea({ agentsVisible: false });
- expect(screen.queryByRole('button', { name: 'Open agents panel' })).toBeNull();
- } finally {
- Reflect.deleteProperty(window, 'okDesktop');
- }
- });
});
describe('EditorArea terminal placement', () => {
@@ -2777,7 +3044,7 @@ describe('EditorArea terminal persists across view-kind switches', () => {
});
});
-describe('EditorArea hash-load skeleton renders outside the panel group (cold start)', () => {
+describe('EditorArea hash-load skeleton renders inside the editor card (cold start)', () => {
beforeEach(() => {
cleanup();
docCtx = DOC_COLD_CTX;
@@ -2786,7 +3053,7 @@ describe('EditorArea hash-load skeleton renders outside the panel group (cold st
window.location.hash = '';
});
- test('renders the load skeleton directly, not inside the terminal dock or panel group', () => {
+ 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
@@ -2800,14 +3067,106 @@ describe('EditorArea hash-load skeleton renders outside the panel group (cold st
/>,
);
- expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
- expect(screen.queryByTestId('resizable-group')).toBeNull();
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ 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');
});
-});
-describe('EditorArea terminal persists across a mid-session cold navigation', () => {
- beforeEach(() => {
+ 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" />}>
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ />
+ </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={() => {}}
+ />,
+ );
+ 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 = '';
@@ -2846,30 +3205,39 @@ describe('EditorArea terminal persists across a mid-session cold navigation', ()
expect(screen.getByTestId('resizable-group')).toBeTruthy();
});
- test('web host keeps the bare early-return on mid-session cold nav (no dock to preserve)', () => {
+ 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} />);
- expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
- expect(screen.queryByTestId('resizable-group')).toBeNull();
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ 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', () => {
- const pctOf = (px: number) => (px / 1360) * 100;
-
- function TabHost({ initialTab }: { initialTab: PanelTab }) {
+ function TabHost({
+ initialTab,
+ onActiveTabChange,
+ }: {
+ initialTab: PanelTab;
+ onActiveTabChange?: (tab: PanelTab) => void;
+ }) {
const [tab, setTab] = useState<PanelTab>(initialTab);
return (
<TooltipProvider>
@@ -2877,70 +3245,138 @@ describe('EditorArea doc-panel tab requests', () => {
editorMode="wysiwyg"
onModeChange={() => {}}
activeTab={tab}
- onActiveTabChange={setTab}
+ onActiveTabChange={(nextTab) => {
+ onActiveTabChange?.(nextTab);
+ setTab(nextTab);
+ }}
/>
</TooltipProvider>
);
}
+ function mountTabHost(initialTab: PanelTab, onActiveTabChange?: (tab: PanelTab) => void) {
+ const resizeObserver = installResizeObserver();
+ const view = render(<TabHost initialTab={initialTab} onActiveTabChange={onActiveTabChange} />);
+ const card = document.querySelector<HTMLElement>('[data-slot="pane-card"][data-pane="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]');
+ 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 = {};
+ 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', () => {
- render(<TabHost initialTab="timeline" />);
- groupLayout = { 'editor-main': 100, 'doc-panel': 0 };
- groupSetLayoutCalls = [];
+ 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');
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ const storedPins = localStorage.getItem('ok-sidebar-pins-v2');
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ await act(async () => {});
- const panel = screen.getByRole('tabpanel');
- expect(panel.getAttribute('id')).toBe('panel-problems');
- expect(groupSetLayoutCalls.at(-1)?.['doc-panel']).toBeCloseTo(pctOf(320), 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('a panel already parked on Problems in project scope comes back in doc scope', () => {
- render(<TabHost initialTab="problems" />);
- fireEvent.click(screen.getByTestId('panel-scope-project'));
- expect(screen.getByTestId('problems-project-scope')).toBeTruthy();
- groupLayout = { 'editor-main': 100, 'doc-panel': 0 };
- groupSetLayoutCalls = [];
+ 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' }));
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ await act(async () => {});
- expect(screen.getByTestId('panel-scope-doc').getAttribute('data-state')).toBe('on');
- expect(screen.queryByTestId('problems-project-scope')).toBeNull();
- expect(groupSetLayoutCalls.at(-1)?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
+ 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' };
- render(<TabHost initialTab="timeline" />);
+ 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 view = render(<TabHost initialTab="timeline" />);
- for (let i = 0; i < 3; i += 1) view.rerender(<TabHost initialTab="timeline" />);
- groupLayout = { 'editor-main': 100, 'doc-panel': 0 };
- groupSetLayoutCalls = [];
+ 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(groupSetLayoutCalls).toHaveLength(1);
+ 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(groupSetLayoutCalls).toHaveLength(1);
+ view.unmount();
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ expect(onActiveTabChange).toHaveBeenCalledTimes(1);
+ } finally {
+ resizeObserver.restore();
+ }
});
});
@@ -3290,3 +3726,2334 @@ describe('EditorArea rail mount inert', () => {
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);
+
+ view.rerender(renderRow(true));
+ await act(async () => {});
+
+ expect(terminalChanges).toEqual([]);
+ expect(toastInfoMessages).toEqual([]);
+ });
+
+ 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();
+ 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);
+
+ mockFileListPx = FILE_LIST_PX;
+ groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
+ resizeObserver.fire('[data-editor-inner-panels]');
+
+ 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);
+ } finally {
+ resizeObserver.restore();
+ }
+ });
+
+ test('at a 1400px window with a document open, chat joins the right terminal', async () => {
+ const resizeObserver = installResizeObserver();
+ 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]');
+
+ view.rerender(
+ <EditorArea
+ {...rowProps}
+ agentsVisible
+ terminalVisible
+ terminalPlacement="right"
+ onAgentsVisibleChange={(visible: boolean) => {
+ agentsChanges.push(visible);
+ }}
+ onTerminalVisibleChange={(visible: boolean) => {
+ terminalChanges.push(visible);
+ }}
+ />,
+ );
+ await act(async () => {});
+
+ expect(terminalChanges).toEqual([]);
+ expect(agentsChanges).toEqual([]);
+ expect(toastInfoMessages).toEqual([]);
+ } 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([]);
+
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 1 });
+ });
+
+ expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
+ expect(agentsChanges).toEqual([false]);
+ expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
+ } finally {
+ 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();
+ 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([]);
+
+ agentsHandle().removeAttribute('data-separator');
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 7 });
+ });
+
+ 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.']);
+ } 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);
+ act(() => {
+ innerRowHandlers.onLayoutChange?.(innerLayout);
+ });
+ 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 });
+ });
+ 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');
+
+ 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;
+ }
+ });
+
+ test('every side-panel drag end re-plans both rows', 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 () => {});
+ groupLayout = { 'editor-main': 60, 'agents-column': 40 };
+ innerLayout = innerRowWithDoc(300, 0.6 * 1360);
+ groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
+
+ act(() => {
+ fireEvent.pointerDown(docHandle(), { pointerId: 1 });
+ });
+ expect(groupSetLayoutCalls).toHaveLength(0);
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 1 });
+ });
+
+ expect(((groupSetLayoutCalls.at(-1)?.['agents-column'] ?? 0) / 100) * 1360).toBeCloseTo(480, 3);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ });
+
+ test('a chat drag the library started beside the divider commits the released width as the preferred width', 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 () => {});
+
+ 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,
+ );
+ } finally {
+ resizeObserver.restore();
+ }
+ });
+
+ 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 });
+ });
+
+ 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,
+ );
+ 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.']);
+ } finally {
+ resizeObserver.restore();
+ }
+ });
+
+ 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;
+ 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');
+
+ terminalHandle().setAttribute('data-separator', 'active');
+ groupLayout = { 'editor-main': 100, 'terminal-column': 0 };
+ act(() => {
+ groupOnLayoutChange?.(groupLayout);
+ });
+ expect(outerRow.getAttribute('data-dragging')).toBe('true');
+ groupSetLayoutCalls = [];
+ panelIsCollapsed = true;
+ terminalHandle().removeAttribute('data-separator');
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 7 });
+ });
+
+ expect(outerRow.getAttribute('data-dragging')).toBeNull();
+ expect(terminalChanges).toEqual([]);
+ expect(groupSetLayoutCalls).toHaveLength(0);
+ });
+
+ 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);
+ }}
+ />,
+ );
+ 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 });
+ });
+
+ 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;
+ 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);
+ }}
+ />,
+ );
+ 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();
+ }
+ });
+
+ test('an outer layout change that leaves the editor column width alone does not swallow the next inner resize', async () => {
+ const resizeObserver = installResizeObserver();
+ try {
+ const agentsChanges: boolean[] = [];
+ await renderWideRowsWithTerminalAndChat(agentsChanges);
+ act(() => groupOnLayoutChange?.(groupLayout));
+ resizeObserver.fire('[data-editor-inner-panels]');
+ await flushFrame();
+
+ groupLayout = {
+ 'editor-main': groupLayout['editor-main'],
+ 'terminal-column': pctOfRow(700, 2000),
+ 'agents-column': pctOfRow(520, 2000),
+ };
+ act(() => groupOnLayoutChange?.(groupLayout));
+ groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
+
+ innerLayout = innerRowWithDoc(300, 2000 - 740 - 480);
+ resizeObserver.fire('[data-editor-inner-panels]');
+ await flushFrame();
+
+ 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 () => {
+ const resizeObserver = installResizeObserver();
+ try {
+ const agentsChanges: boolean[] = [];
+ await renderWideRowsWithTerminalAndChat(agentsChanges);
+
+ mockGroupPx = 0;
+ resizeObserver.fire('[data-editor-area-panels]');
+ await flushFrame();
+ expect(agentsChanges).toEqual([]);
+ groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
+
+ mockGroupPx = 1000;
+ act(() => groupOnLayoutChange?.(groupLayout));
+ 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();
+ }
+ });
+
+ test('the observers stay off inside an embedded host', () => {
+ const resizeObserver = installResizeObserver();
+ const originalUserAgent = navigator.userAgent;
+ Object.defineProperty(navigator, 'userAgent', {
+ configurable: true,
+ value: `${originalUserAgent} Claude/1.0`,
+ });
+ try {
+ setViewportWidth(1400);
+ docCtx = DOC_LIVE_CTX;
+ render(<EditorArea {...rowProps} agentsVisible />);
+ expect(() => resizeObserver.fire('[data-editor-area-panels]')).toThrow(/not observed/);
+ groupSetLayoutCalls = [];
+ innerSetLayoutCalls = [];
+ resizeObserver.fire('[data-editor-inner-panels]');
+ expect(groupSetLayoutCalls).toHaveLength(0);
+ expect(innerSetLayoutCalls).toHaveLength(0);
+ } finally {
+ Object.defineProperty(navigator, 'userAgent', {
+ configurable: true,
+ value: originalUserAgent,
+ });
+ resizeObserver.restore();
+ }
+ });
+});
+
+describe('EditorArea terminal and chat cards', () => {
+ const cardProps = {
+ editorMode: 'wysiwyg',
+ 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}"]`);
+
+ beforeEach(() => {
+ cleanup();
+ localStorage.clear();
+ docCtx = DOC_LIVE_CTX;
+ groupLayout = {};
+ groupSetLayoutCalls = [];
+ rejectNextGroupLayoutWrite = false;
+ rejectGroupLayoutWrites = false;
+ panelIsCollapsed = false;
+ mockGroupPx = 1360;
+ mockPanelPercentage = null;
+ mockPanelPx = null;
+ toastInfoMessages = [];
+ 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>
+ <FileListHostProvider enabled fileList={<nav data-testid="landmark-file-list" />}>
+ <EditorArea {...cardProps} agentsVisible />
+ </FileListHostProvider>
+ </TooltipProvider>,
+ );
+
+ const main = screen.getByRole('main');
+ expect(main.hasAttribute('data-editor-workspace-column')).toBe(true);
+ expect(main.contains(screen.getByTestId('workspace-tabs'))).toBe(true);
+ expect(main.contains(screen.getByTestId('landmark-file-list'))).toBe(false);
+ expect(cardOf('editor')?.contains(screen.getByTestId('landmark-file-list'))).toBe(true);
+ const sidePanel = screen.getByRole('region', { name: 'Document panel' });
+ expect(sidePanel.id).toBe('doc-panel');
+ expect(main.contains(sidePanel)).toBe(false);
+ const chat = screen.getByRole('region', { name: 'Agent panel' });
+ expect(chat.hasAttribute('data-agents-panel-mount')).toBe(true);
+ expect(main.contains(chat)).toBe(false);
+ expect(main.contains(document.querySelector('[data-terminal-panel-mount]'))).toBe(false);
+ expect(cardOf('editor')?.querySelector('[data-slot="sidebar-inset"]')?.contains(main)).toBe(
+ true,
+ );
+ });
+
+ test('the side panel toggle is one button at the end of the tab bar, only for an open document', () => {
+ const { rerender } = render(
+ <TooltipProvider>
+ <EditorArea {...cardProps} />
+ </TooltipProvider>,
+ );
+
+ const toggles = document.querySelectorAll('[data-doc-panel-toggle]');
+ expect(toggles).toHaveLength(1);
+ const header = document.querySelector('[data-editor-area-header]');
+ expect(header?.contains(toggles[0] ?? null)).toBe(true);
+ expect(toggles[0]?.getAttribute('aria-controls')).toBe('doc-panel');
+ expect(toggles[0]?.getAttribute('aria-expanded')).toBe('true');
+ expect(
+ screen.getByTestId('workspace-tabs').compareDocumentPosition(toggles[0] as Node) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+
+ fireEvent.click(toggles[0] as Element);
+ act(() => {
+ railPanelOnResizeById.get('doc-panel')?.({ asPercentage: 0, inPixels: 0 });
+ });
+ expect(document.querySelector('[data-doc-panel-toggle]')?.getAttribute('aria-expanded')).toBe(
+ 'false',
+ );
+
+ act(() => {
+ docCtx = FOLDER_DOC_CTX;
+ });
+ rerender(
+ <TooltipProvider>
+ <EditorArea {...cardProps} />
+ </TooltipProvider>,
+ );
+ expect(document.querySelector('[data-doc-panel-toggle]')).toBeNull();
+ });
+
+ test('the side panel toggle leaves the tab bar while the open document has a sync conflict', () => {
+ const { rerender } = render(
+ <TooltipProvider>
+ <EditorArea {...cardProps} />
+ </TooltipProvider>,
+ );
+ expect(document.querySelectorAll('[data-doc-panel-toggle]')).toHaveLength(1);
+
+ conflictedDocName = 'docs/notes';
+ rerender(
+ <TooltipProvider>
+ <EditorArea {...cardProps} />
+ </TooltipProvider>,
+ );
+
+ const header = document.querySelector('[data-editor-area-header]');
+ expect(header?.contains(screen.getByTestId('workspace-tabs'))).toBe(true);
+ 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,
+ value: {
+ config: { singleFile: true },
+ editor: { notifyViewMenuStateChanged: () => {} },
+ },
+ });
+ try {
+ render(
+ <TooltipProvider>
+ <SingleFileModeProvider>
+ <EditorArea
+ {...cardProps}
+ terminalBridge={{} as never}
+ terminalVisible
+ terminalPlacement="right"
+ agentsVisible
+ />
+ </SingleFileModeProvider>
+ </TooltipProvider>,
+ );
+ expect(cardOf('editor')?.getAttribute('data-variant')).toBe('card');
+ expect(cardOf('terminal')?.getAttribute('data-variant')).toBe('card');
+ expect(cardOf('agents')?.getAttribute('data-variant')).toBe('card');
+ expect(screen.getByRole('main').contains(screen.getByTestId('workspace-tabs'))).toBe(true);
+ } finally {
+ Reflect.deleteProperty(window, 'okDesktop');
+ }
+ });
+
+ test('inside an embedded host the cards render as in a project window while the host rules hold', () => {
+ const originalUserAgent = navigator.userAgent;
+ Object.defineProperty(navigator, 'userAgent', {
+ configurable: true,
+ value: `${originalUserAgent} Cursor/1.0`,
+ });
+ try {
+ render(
+ <TooltipProvider>
+ <EditorArea {...cardProps} agentsVisible={false} />
+ </TooltipProvider>,
+ );
+ expect(cardOf('editor')?.getAttribute('data-variant')).toBe('card');
+ expect(cardOf('agents')?.getAttribute('data-variant')).toBe('card');
+ expect(screen.queryByTestId('bottom-composer')).toBeNull();
+ expect(document.getElementById('doc-panel')?.hasAttribute('inert')).toBe(true);
+ expect(document.querySelector('[data-doc-panel-toggle]')?.getAttribute('aria-expanded')).toBe(
+ 'false',
+ );
+ } finally {
+ Object.defineProperty(navigator, 'userAgent', {
+ configurable: true,
+ value: originalUserAgent,
+ });
+ }
+ cleanup();
+ render(
+ <TooltipProvider>
+ <EditorArea {...cardProps} agentsVisible={false} />
+ </TooltipProvider>,
+ );
+ 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', () => {
+ const hiddenProps = {
+ editorMode: 'wysiwyg',
+ onModeChange: () => {},
+ 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 () => {});
+
+ beforeEach(() => {
+ cleanup();
+ localStorage.clear();
+ docCtx = DOC_LIVE_CTX;
+ groupLayout = {};
+ groupSetLayoutCalls = [];
+ rejectNextGroupLayoutWrite = false;
+ rejectGroupLayoutWrites = false;
+ panelIsCollapsed = false;
+ mockGroupPx = ROW_PX;
+ mockPanelPercentage = null;
+ mockPanelPx = null;
+ toastInfoMessages = [];
+ Object.defineProperty(window, 'innerWidth', {
+ value: 1400,
+ configurable: true,
+ writable: true,
+ });
+ });
+
+ test('chat alone fills the row and the editor column may reach zero', async () => {
+ const view = render(<EditorArea {...hiddenProps} agentsVisible />);
+ groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
+ await settle();
+ const innerWritesBeforeHide = innerSetLayoutCalls.length;
+
+ 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');
+ });
+
+ 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 };
+ const view = render(
+ <EditorArea
+ {...hiddenProps}
+ agentsVisible
+ terminalVisible
+ terminalPlacement="right"
+ terminalRightWidth={400}
+ />,
+ );
+ groupLayout = { 'editor-main': 40, 'terminal-column': 25, 'agents-column': 35 };
+ await settle();
+
+ view.rerender(
+ <EditorArea
+ {...hiddenProps}
+ agentsVisible
+ terminalVisible
+ terminalPlacement="right"
+ terminalRightWidth={400}
+ 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('');
+ });
+
+ 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} />);
+ await settle();
+
+ 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} />);
+ await settle();
+ expect(groupLayout['agents-column']).toBe(100);
+ const innerWritesWhileHidden = innerSetLayoutCalls.length;
+
+ view.rerender(<EditorArea {...hiddenProps} agentsVisible />);
+ 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);
+ });
+
+ 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 () => {
+ 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 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 workspaceMountsBefore = editorWorkspaceMounts;
+
+ view.rerender(
+ <FileListHostProvider enabled>
+ <EditorArea {...hiddenProps} agentsVisible editorVisible={false} />
+ </FileListHostProvider>,
+ );
+ await settle();
+
+ expect(editorCard()).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');
+
+ view.rerender(
+ <FileListHostProvider enabled>
+ <EditorArea {...hiddenProps} agentsVisible />
+ </FileListHostProvider>,
+ );
+ await settle();
+ await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
+
+ expect(groupLayout['editor-main']).toBeGreaterThan(0);
+ expect(editorCard()).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');
+ });
+
+ test('hiding the editor while focus is inside it moves focus to the header Editor button', async () => {
+ const editorButton = document.createElement('button');
+ editorButton.setAttribute('data-header-pane-button', 'editor');
+ document.body.append(editorButton);
+ const view = render(<EditorArea {...hiddenProps} agentsVisible />);
+ const region = document.querySelector<HTMLElement>('[data-editor-region]');
+ region?.focus();
+ expect(document.activeElement).toBe(region);
+
+ view.rerender(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
+ await settle();
+
+ expect(document.activeElement).toBe(editorButton);
+ editorButton.remove();
+ });
+
+ test('showing the editor from the header Editor button moves focus into the editor', async () => {
+ const editorButton = document.createElement('button');
+ editorButton.setAttribute('data-header-pane-button', 'editor');
+ document.body.append(editorButton);
+ const view = render(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
+ await settle();
+ editorButton.focus();
+
+ view.rerender(<EditorArea {...hiddenProps} agentsVisible />);
+ await settle();
+
+ expect(document.activeElement).toBe(document.querySelector('[data-editor-region]'));
+ editorButton.remove();
+ });
+
+ test('showing the editor after Nothing open lets go of focus lands in the editor, not the page', async () => {
+ const view = render(<EditorArea {...hiddenProps} editorVisible={false} />);
+ await settle();
+ const nothingOpen = document.querySelector<HTMLElement>('[data-nothing-open]');
+ nothingOpen?.focus();
+ expect(document.activeElement).toBe(nothingOpen);
+
+ view.rerender(<EditorArea {...hiddenProps} />);
+ await settle();
+
+ expect(document.querySelector('[data-nothing-open]')).toBeNull();
+ expect(document.activeElement).toBe(document.querySelector('[data-editor-region]'));
+ });
+
+ test('showing the editor while focus is in another pane leaves it there', async () => {
+ const composer = document.createElement('textarea');
+ document.body.append(composer);
+ const view = render(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
+ await settle();
+ composer.focus();
+
+ view.rerender(<EditorArea {...hiddenProps} agentsVisible />);
+ await settle();
+
+ expect(document.activeElement).toBe(composer);
+ 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]);
+
+ mockPanelPx = null;
+ view.rerender(<EditorArea {...props} />);
+ await settle();
+ await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
+
+ expect(groupLayout['agents-column']).toBeCloseTo(pctOfRow(preferredChatPx));
+ expect(groupLayout['terminal-column']).toBeCloseTo(pctOfRow(400));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ 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);
+
+ view.rerender(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
+ await settle();
+ expect(mount()?.hasAttribute('data-chat-alone')).toBe(true);
+
+ view.rerender(
+ <EditorArea
+ {...hiddenProps}
+ agentsVisible
+ editorVisible={false}
+ terminalVisible
+ terminalPlacement="right"
+ />,
+ );
+ await settle();
+ expect(mount()?.hasAttribute('data-chat-alone')).toBe(false);
+ });
+
+ test('Nothing open appears only when the editor, chat and terminal are all hidden', async () => {
+ const view = render(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
+ await settle();
+ expect(document.querySelector('[data-nothing-open]')).toBeNull();
+
+ view.rerender(<EditorArea {...hiddenProps} editorVisible={false} />);
+ await settle();
+ const nothingOpen = document.querySelector('[data-nothing-open]');
+ expect(nothingOpen?.parentElement).toBe(document.querySelector('[data-editor-area-panels]'));
+
+ view.rerender(<EditorArea {...hiddenProps} />);
+ await settle();
+ expect(document.querySelector('[data-nothing-open]')).toBeNull();
+ });
+
+ test('hiding the last pane while focus is in the editor moves focus to Nothing open', async () => {
+ const view = render(<EditorArea {...hiddenProps} />);
+ const region = document.querySelector<HTMLElement>('[data-editor-region]');
+ region?.focus();
+
+ view.rerender(<EditorArea {...hiddenProps} editorVisible={false} />);
+ await settle();
+
+ 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}
+ />,
+ );
+ await settle();
+
+ 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 />);
+ await settle();
+
+ const chatPct = pctOfRow(getInitialAgentsPanelWidth());
+ expect(groupLayout['editor-main']).toBeCloseTo(100 - chatPct);
+ expect(groupLayout['agents-column']).toBeCloseTo(chatPct);
+ });
+});
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 969caaa91..dfeb4ab58 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
@@ -1,6 +1,7 @@
import { cleanup, render, screen } from '@testing-library/react';
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';
function assetCtx(assetPath: string) {
@@ -116,12 +117,14 @@ const { EditorArea } = await import('./EditorArea');
function renderEditorArea() {
return render(
<ConfigProvider collabUrl={null}>
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- />
+ <SidebarProvider>
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ />
+ </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 bb7684e0a..146f709eb 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
@@ -1,6 +1,7 @@
import { cleanup, render, screen } from '@testing-library/react';
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 { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
@@ -118,12 +119,14 @@ const { EditorArea } = await import('./EditorArea');
function renderEditorArea() {
return render(
<ConfigProvider collabUrl={null}>
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- />
+ <SidebarProvider>
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ />
+ </SidebarProvider>
</ConfigProvider>,
);
}
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 4680c883e..30e110899 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -12,13 +12,16 @@ import {
type TerminalPlacement,
} from '@inkeep/open-knowledge-core/terminal-layout';
import { Trans, useLingui } from '@lingui/react/macro';
+import { ChevronLeft, PanelRightClose } from 'lucide-react';
import {
lazy,
type ReactNode,
+ type Ref,
Suspense,
useDeferredValue,
useEffect,
useEffectEvent,
+ useImperativeHandle,
useLayoutEffect,
useRef,
useState,
@@ -29,22 +32,36 @@ import { useGroupRef, usePanelRef } from 'react-resizable-panels';
import { toast } from 'sonner';
import { AssetPreview } from '@/components/AssetPreview';
import { DocPanel, type PanelTab } from '@/components/DocPanel';
+import { DocPanelToggle } from '@/components/DocPanelToggle';
import {
consumePendingDocPanelTabRequest,
subscribeToDocPanelTabRequests,
} from '@/components/doc-panel-events';
import { EditorSkeleton } from '@/components/EditorSkeleton';
import { EmptyEditorState } from '@/components/EmptyEditorState';
+import { useAttachFileListHost, useFileListHost } from '@/components/FileListHost';
import { FolderOverview } from '@/components/FolderOverview';
import { LargeFileEditorState } from '@/components/LargeFileEditorState';
import { MountStalledAffordance } from '@/components/MountStalledAffordance';
+import { NothingOpen } from '@/components/NothingOpen';
import { OkBlobRunnerPage } from '@/components/OkBlobRunnerPage';
import { PropertyProvider, useProperties } from '@/components/PropertyContext';
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,
+ PaneCard,
+ paneCardDividerClass,
+ SECONDARY_PANEL_SURFACE_CLASS,
+} from '@/components/ui/pane-card';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
+import { SidebarInset, useSidebar } from '@/components/ui/sidebar';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import {
isBlobRunnerNewTabId,
useDocumentContext,
@@ -73,19 +90,31 @@ import {
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 { 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 { ProfilerBoundary } from '@/lib/perf';
+import { moveHostPreservingScroll, observeHostScrollRestore } from '@/lib/preserve-subtree-scroll';
+import { revealEditor, revealEditorBeforeActing } from '@/lib/reveal-editor';
import {
matchesShareReceiveMiss,
pendingReceiveNavStore,
} from '@/lib/share/pending-receive-nav-store';
import { RIGHT_COLLAPSE_THRESHOLD, resolvePartition } from '@/lib/sidebar-partition';
-import { applyToggle, readPins, resolveEffectiveState } from '@/lib/sidebar-pin-store';
+import {
+ applyToggleAtEveryWidth,
+ openIntentAfterPartitionChange,
+ readPins,
+ resolveEffectiveState,
+} from '@/lib/sidebar-pin-store';
import { closeTimelineDiff, useTimelineDiffView } from '@/lib/timeline-diff-store';
+import { EditorContentOnScreenContext } from '@/lib/use-editor-pane-on-screen';
import { useSettingsRoute } from '@/lib/use-settings-route';
+import { cn } from '@/lib/utils';
import { setViewMenuState } from '@/lib/view-menu-state-store';
import { withViewTransition } from '@/lib/view-transition';
import { useSyncStatus } from '@/presence/use-sync-status';
@@ -100,6 +129,12 @@ 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,
@@ -107,6 +142,8 @@ import {
type RailPanelSpaceRefusal,
type RailPanelSpaceResult,
type RailWidthShortfall,
+ reportUnexpectedPanelGroupFailure,
+ resolveInnerRowChromePx,
resolveRailPanelSpace,
resolveRailPanelSpacePx,
} from './editor-area-panel-space';
@@ -123,16 +160,117 @@ import {
resolveRightRailAdmission,
} from './right-rail-admission';
import { isSlidesHost } from './slides-host-gate';
-import { TerminalDock } from './TerminalDock';
-import { TerminalRevealTab } from './TerminalRevealTab';
+import { TerminalDock, type TerminalDockHandle } from './TerminalDock';
const LazyActivityModeContent = lazy(async () => {
const mod = await import('@/components/ActivityModeContent');
return { default: mod.ActivityModeContent };
});
-const PANEL_GROUP_UNAVAILABLE_MESSAGE = /^Could not find Group with id "/;
const BLOCKED_RAIL_LAYOUT_RETRY_DEADLINE_MS = 60_000;
+const DESTINATION_FOCUS_DEADLINE_MS = 10_000;
+
+function measureSidebarUnitWidth(element: HTMLElement | null, fallbackWidthPx: number | null) {
+ const width = element?.getBoundingClientRect().width;
+ return width != null && width > 0 ? width : fallbackWidthPx;
+}
+
+type SidebarFitContext = {
+ widthPx: number | null;
+ filesDockWidth: string;
+ filesPresent: boolean;
+ informationWidthPx: number;
+ filesIntentOpen: boolean;
+ informationIntentOpen: boolean;
+ preferredSidebar: EditorSidebar | null;
+};
+
+function resolveFilesDockWidthPx(filesDockWidth: string): number {
+ const filesWidth = Number.parseFloat(filesDockWidth);
+ return filesDockWidth.endsWith('rem')
+ ? filesWidth * Number.parseFloat(getComputedStyle(document.documentElement).fontSize)
+ : filesWidth;
+}
+
+function sidebarFitWidthBucket(context: SidebarFitContext, widthPx: number | null): string {
+ const availablePx = widthPx == null ? Infinity : widthPx - DOC_USABLE_MIN_WIDTH_PX;
+ const filesPx = context.filesPresent ? resolveFilesDockWidthPx(context.filesDockWidth) : 0;
+ const informationPx = context.informationWidthPx + 1;
+ return [0, filesPx, informationPx, filesPx + informationPx]
+ .map((thresholdPx) => (availablePx >= thresholdPx ? '1' : '0'))
+ .join('');
+}
+
+function docPanelDockReadyFor(innerWidthPx: number | null, docPanelWidthPx: number): boolean {
+ return innerWidthPx == null || innerWidthPx >= docPanelWidthPx + DOC_USABLE_MIN_WIDTH_PX + 1;
+}
+
+function resolveCurrentEditorSidebarFit(
+ context: SidebarFitContext,
+ informationPresent: boolean,
+ filesOpen = context.filesIntentOpen,
+ informationOpen = context.informationIntentOpen,
+ preferred = context.preferredSidebar,
+ widthPx = context.widthPx,
+) {
+ const filesWidthPx = resolveFilesDockWidthPx(context.filesDockWidth);
+ return resolveEditorSidebarFit({
+ widthPx,
+ filesWidthPx: context.filesPresent ? filesWidthPx : null,
+ informationWidthPx: informationPresent ? context.informationWidthPx : null,
+ documentMinimumPx: DOC_USABLE_MIN_WIDTH_PX,
+ filesOpen,
+ informationOpen,
+ preferred,
+ });
+}
+
+type FilesRequestCoordinatorInputs = {
+ fit: SidebarFitContext;
+ editorCardRef: { current: HTMLDivElement | null };
+ docSlotPresent: boolean;
+ setPreferredSidebar: (preferred: EditorSidebar | null) => void;
+ setDocPanelCover: (open: boolean) => void;
+ setPendingDocPanelDestination: (destination: null) => void;
+ setFilesCanDock: (canDock: boolean) => void;
+};
+
+function useFilesRequestCoordinator(inputs: FilesRequestCoordinatorInputs) {
+ const current = useRef(inputs);
+ useLayoutEffect(() => {
+ current.current = inputs;
+ });
+ const [coordinate] = useState(() => (open: boolean) => {
+ const {
+ fit,
+ editorCardRef,
+ docSlotPresent,
+ setPreferredSidebar,
+ setDocPanelCover,
+ setPendingDocPanelDestination,
+ setFilesCanDock,
+ } = current.current;
+ if (!fit.filesPresent) return null;
+ const result = resolveCurrentEditorSidebarFit(
+ fit,
+ docSlotPresent,
+ open,
+ fit.informationIntentOpen,
+ 'files',
+ measureSidebarUnitWidth(editorCardRef.current, fit.widthPx),
+ );
+ if (open) {
+ setPreferredSidebar(result.mode === 'both' ? null : 'files');
+ setDocPanelCover(false);
+ setPendingDocPanelDestination(null);
+ } else if (fit.preferredSidebar === 'files') {
+ setPreferredSidebar(null);
+ }
+ setFilesCanDock(result.filesDocked);
+ return result.filesDocked;
+ });
+ return coordinate;
+}
type AgentsPanelCloseRetryContext = {
readonly decision: 'close';
@@ -146,7 +284,7 @@ type AgentsPanelPointerReleaseRetryContext =
| { readonly decision: 'commit-preferred'; readonly targetWidthPx: number };
type RailLayoutSyncRetryContext = {
- readonly decision: 'sync-rail-columns' | 'sync-doc-presence';
+ readonly decision: 'sync-rail-columns' | 'sync-doc-presence' | 'observed-doc-width';
readonly targetWidthPx: number;
};
@@ -189,21 +327,6 @@ function createAgentsPanelPointerReleaseRetryContext(
}
}
-function reportUnexpectedPanelGroupFailure(
- event: string,
- error: unknown,
- context?: RailLayoutRetryContext,
-) {
- if (error instanceof Error && PANEL_GROUP_UNAVAILABLE_MESSAGE.test(error.message)) return;
- console.warn(
- JSON.stringify({
- event,
- error: error instanceof Error ? error.message : String(error),
- ...context,
- }),
- );
-}
-
function cancelRailLayoutRetry(retryRef: RailLayoutRetryControllerRef) {
if (retryRef.current.frameId !== 0) cancelAnimationFrame(retryRef.current.frameId);
if (retryRef.current.deadlineTimer != null) clearTimeout(retryRef.current.deadlineTimer);
@@ -311,17 +434,11 @@ function PaneDocumentToolbar({
provider,
isSourceMode,
onModeChange,
- isPanelCollapsed,
- onTogglePanel,
- reserveRightGutter,
}: {
docName: string;
provider: HocuspocusProvider;
isSourceMode: boolean;
onModeChange: (mode: EditorMode) => void;
- isPanelCollapsed: boolean;
- onTogglePanel: () => void;
- reserveRightGutter: boolean;
}) {
const { requestAddProperty } = useProperties();
const syncStatus = useSyncStatus(provider);
@@ -345,9 +462,6 @@ function PaneDocumentToolbar({
showAddPropertyButton={!isSourceMode}
onAddProperty={() => requestAddProperty(docName)}
frontmatterProblems={missingProperties}
- isPanelCollapsed={isPanelCollapsed}
- onTogglePanel={onTogglePanel}
- reserveRightGutter={reserveRightGutter}
/>
);
}
@@ -374,13 +488,18 @@ type RailPinOutcome =
| { 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: 'width-shortfall'; readonly shortfall: Record<string, RailWidthShortfall> }
+ | { readonly stage: 'editor-hidden-unsettled' };
-type RailPinExhaustedTrigger = 'rail-column-sync' | 'doc-slot-presence';
+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;
@@ -393,12 +512,42 @@ export interface SessionPlacements {
readonly editorRegion: HTMLElement | null;
}
+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 {
+ if (element == null) return false;
+ const { width, height } = element.getBoundingClientRect();
+ return width > 0 && height > 0;
+}
+
+interface WorkspaceHeaderChrome {
+ readonly trailing: ReactNode;
+}
+
interface EditorAreaProps {
+ ref?: Ref<EditorAreaHandle>;
+ onPaneExtentChange?: () => void;
editorMode: EditorMode;
onModeChange: (mode: EditorMode) => void;
activeTab: PanelTab;
onActiveTabChange: (tab: PanelTab) => void;
terminalBridge?: OkDesktopBridge | null;
+ editorVisible?: boolean;
terminalVisible?: boolean;
terminalPlacement?: TerminalPlacement;
terminalRightWidth?: number;
@@ -407,12 +556,16 @@ interface EditorAreaProps {
agentsVisible?: boolean;
onAgentsVisibleChange?: (visible: boolean) => void;
onSessionPlacements?: (placements: SessionPlacements) => void;
- onRevealAgents?: () => void;
- renderWorkspaceHeader?: (tabs: ReactNode) => ReactNode;
+ renderWorkspaceHeader?: (tabs: ReactNode, chrome: WorkspaceHeaderChrome) => ReactNode;
}
-function renderTabsWithoutHeader(tabs: ReactNode): ReactNode {
- return tabs;
+function renderTabsWithoutHeader(tabs: ReactNode, chrome: WorkspaceHeaderChrome): ReactNode {
+ return (
+ <>
+ {tabs}
+ {chrome.trailing}
+ </>
+ );
}
export function EditorArea(props: EditorAreaProps) {
@@ -440,12 +593,100 @@ function SettingsDialogPortal() {
);
}
+function useDocPanelHost() {
+ const [host] = useState(() => {
+ const element = document.createElement('div');
+ element.className = 'flex h-full min-h-0 w-full flex-col';
+ return element;
+ });
+ const dockTarget = useRef<HTMLDivElement | null>(null);
+ const coverTarget = useRef<HTMLDivElement | null>(null);
+ useEffect(() => observeHostScrollRestore(host, host), [host]);
+ const [dockRef] = useState(() => (target: HTMLDivElement) => {
+ dockTarget.current = target;
+ if (coverTarget.current == null && host.parentNode !== target) {
+ moveHostPreservingScroll(host, target);
+ }
+ return () => {
+ if (dockTarget.current === target) dockTarget.current = null;
+ if (host.parentNode === target) target.removeChild(host);
+ };
+ });
+ const [coverRef] = useState(() => (target: HTMLDivElement) => {
+ coverTarget.current = target;
+ if (host.parentNode !== target) moveHostPreservingScroll(host, target);
+ return () => {
+ if (coverTarget.current === target) coverTarget.current = null;
+ if (host.parentNode !== target) return;
+ const dock = dockTarget.current;
+ if (dock?.isConnected) moveHostPreservingScroll(host, dock);
+ else target.removeChild(host);
+ };
+ });
+ return { host, dockRef, coverRef };
+}
+
+function useFileListSlot() {
+ const [node, setNode] = useState<HTMLDivElement | null>(null);
+ const nodeRef = useRef<HTMLDivElement | null>(null);
+ const [slotRef] = useState(() => (target: HTMLDivElement | null) => {
+ setNode(target);
+ nodeRef.current = target;
+ });
+ return { node, nodeRef, slotRef };
+}
+
+function escapeBelongsToCover(
+ event: KeyboardEvent,
+ coverSelector: string,
+ opener: HTMLElement | null,
+): boolean {
+ const target = event.target;
+ if (!(target instanceof Element)) return true;
+ const doc = target.ownerDocument;
+ if (target === doc.body || target === doc.documentElement) return true;
+ return target.closest(coverSelector) !== null || target === opener;
+}
+
+function useDocPanelDestinationCompletion(
+ coverOpen: boolean,
+ setPendingDestination: (destination: null) => void,
+ setCoverOpen: (open: boolean) => void,
+ setDestinationFocusDocName: (docName: string) => void,
+) {
+ const coverOpenRef = useRef(coverOpen);
+ useLayoutEffect(() => {
+ coverOpenRef.current = coverOpen;
+ }, [coverOpen]);
+ const [complete] = useState(() => (target?: HTMLElement) => {
+ if (!coverOpenRef.current) return;
+ setPendingDestination(null);
+ setCoverOpen(false);
+ const editorDocName = target?.matches('.ProseMirror, .cm-content')
+ ? target.closest<HTMLElement>('[data-editor-activity-mount]')?.dataset.docName
+ : undefined;
+ if (editorDocName !== undefined) {
+ setDestinationFocusDocName(editorDocName);
+ return;
+ }
+ requestAnimationFrame(() => {
+ if (target?.isConnected && target.getClientRects().length > 0) {
+ target.focus({ preventScroll: true });
+ }
+ });
+ });
+ return { complete, coverOpenRef };
+}
+
function EditorAreaInner({
+ ref,
+ onPaneExtentChange,
editorMode,
onModeChange,
activeTab,
onActiveTabChange,
terminalBridge,
+ editorVisible = true,
terminalVisible = false,
terminalPlacement = 'bottom',
terminalRightWidth,
@@ -454,11 +695,13 @@ function EditorAreaInner({
agentsVisible = false,
onAgentsVisibleChange,
onSessionPlacements,
- onRevealAgents,
renderWorkspaceHeader = renderTabsWithoutHeader,
}: EditorAreaProps) {
const { t } = useLingui();
const noteWindow = isNoteWindow();
+ const cardLook = !noteWindow;
+ const cardVariant = cardLook ? 'card' : 'flat';
+ const terminalAvailable = terminalBridge != null;
const {
activeDocName,
activeProvider,
@@ -516,6 +759,7 @@ function EditorAreaInner({
const agentPanelOpen = docPanelMode === 'agent' && docPanelAgentId !== null;
if (!agentPanelOpen) closeAgentDiff();
}, [docPanelMode, docPanelAgentId]);
+ const activeDocConflict = useDocConflict(activeDocName);
const pendingReceiveNav = useSyncExternalStore(
pendingReceiveNavStore.subscribe,
pendingReceiveNavStore.getSnapshot,
@@ -525,29 +769,95 @@ function EditorAreaInner({
const [embeddedHost] = useState(() => detectEmbeddedHostFromBrowser());
const isEmbedded = embeddedHost !== null;
- const [rightPartition, setRightPartition] = useState(() =>
+ const [initialRightPartition] = useState(() =>
resolvePartition(embeddedHost, window.innerWidth, 'right'),
);
- const rightPartitionRef = useRef(rightPartition);
- useEffect(() => {
- rightPartitionRef.current = rightPartition;
- }, [rightPartition]);
const panelRef = usePanelRef();
const agentsColumnPanelRef = usePanelRef();
const terminalColumnPanelRef = usePanelRef();
const [initialRightCollapsed] = useState(() => {
const pins = readPins();
- return resolveEffectiveState('right', rightPartition, pins) === 'collapsed';
+ return resolveEffectiveState('right', initialRightPartition, pins) === 'collapsed';
});
const [isCollapsed, setIsCollapsed] = useState(initialRightCollapsed);
const isCollapsedRef = useRef(isCollapsed);
-
- const [agentsContainer, setAgentsContainer] = useState<HTMLDivElement | null>(null);
+ const [docPanelIntentOpen, setDocPanelIntentOpen] = useState(!initialRightCollapsed);
+ useEffect(() => {
+ const mql = window.matchMedia(`(min-width: ${RIGHT_COLLAPSE_THRESHOLD}px)`);
+ const onChange = () => {
+ const partition = resolvePartition(embeddedHost, window.innerWidth, 'right');
+ const intent = openIntentAfterPartitionChange('right', partition, readPins());
+ if (intent !== undefined) setDocPanelIntentOpen(intent);
+ };
+ mql.addEventListener('change', onChange);
+ return () => mql.removeEventListener('change', onChange);
+ }, [embeddedHost]);
+ const [docPanelCover, setDocPanelCover] = useState(false);
+ const [pendingDocPanelDestination, setPendingDocPanelDestination] = useState<{
+ docName: string;
+ allowMissing: boolean;
+ onReady?: () => void;
+ completion: 'synced' | 'navigated';
+ } | null>(null);
+ const [destinationFocusDocName, setDestinationFocusDocName] = useState<string | null>(null);
+ const pendingDocPanelDestinationRef = useRef(pendingDocPanelDestination);
+ useLayoutEffect(() => {
+ pendingDocPanelDestinationRef.current = pendingDocPanelDestination;
+ }, [pendingDocPanelDestination]);
+ const { complete: completeDocPanelDestination, coverOpenRef: docPanelCoverOpenRef } =
+ useDocPanelDestinationCompletion(
+ docPanelCover,
+ setPendingDocPanelDestination,
+ setDocPanelCover,
+ setDestinationFocusDocName,
+ );
+ function reportCoveredDiffFailure() {
+ if (docPanelCoverOpenRef.current) toast.error(t`Diff unavailable`);
+ }
+ const [editorCardWidthPx, setEditorCardWidthPx] = useState<number | null>(null);
+ const [innerWidthPx, setInnerWidthPx] = useState<number | null>(null);
+ const liveEditorCardWidthPxRef = useRef<number | null>(null);
+ const liveInnerWidthPxRef = useRef<number | null>(null);
+ const [preferredSidebar, setPreferredSidebar] = useState<EditorSidebar | null>(null);
+ const docPanelBackRef = useRef<HTMLButtonElement | null>(null);
+ const docPanelDockFocusRef = useRef<HTMLElement | null>(null);
+ const docPanelCoverOpenerRef = useRef<HTMLElement | null>(null);
+ const {
+ host: docPanelHost,
+ dockRef: docPanelDockRef,
+ coverRef: docPanelCoverRef,
+ } = useDocPanelHost();
+ useEffect(() => {
+ const trackFocus = (event: FocusEvent) => {
+ if (event.target === document.body) return;
+ docPanelDockFocusRef.current =
+ event.target instanceof HTMLElement && docPanelHost.contains(event.target)
+ ? event.target
+ : null;
+ };
+ document.addEventListener('focusin', trackFocus, true);
+ return () => document.removeEventListener('focusin', trackFocus, true);
+ }, [docPanelHost]);
+ const {
+ cover: filesCover,
+ canDock: filesCanDock,
+ dismissCover: dismissFilesCover,
+ setCanDock: setFilesCanDock,
+ registerOpenRequestHandler: registerFilesOpenRequestHandler,
+ registerCoverSelectionHandler: registerFilesCoverSelectionHandler,
+ open: filesIntentOpen,
+ width: filesDockWidth,
+ } = useSidebar();
+ const fileListHost = useFileListHost();
+ const [filesCoverTarget, setFilesCoverTarget] = useState<HTMLDivElement | null>(null);
+ const filesBackRef = useRef<HTMLButtonElement | null>(null);
+
+ const [agentsContainer, setAgentsContainer] = useState<HTMLElement | null>(null);
const [rightTerminalContainer, setRightTerminalContainer] = useState<HTMLDivElement | null>(null);
const [workspaceHeaderContainer, setWorkspaceHeaderContainer] = useState<HTMLDivElement | null>(
null,
);
- const [workspaceColumnEl, setWorkspaceColumnEl] = useState<HTMLDivElement | null>(null);
+ const [workspaceColumnEl, setWorkspaceColumnEl] = useState<HTMLElement | null>(null);
const [bottomTerminalContainer, setBottomTerminalContainer] = useState<HTMLDivElement | null>(
null,
);
@@ -557,17 +867,70 @@ function EditorAreaInner({
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 rightRevealTabPresent =
- !noteWindow && (!agentsVisible || agentsColumnCollapsed) && onRevealAgents != null;
+ 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 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);
+ 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;
+ 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();
+ }, [editorVisible, terminalEditorRegion]);
const terminalContainer =
terminalPlacement === 'right' ? rightTerminalContainer : bottomTerminalContainer;
const terminalShowing =
terminalVisible &&
terminalContainer != null &&
- (terminalPlacement !== 'right' || !terminalColumnCollapsed || terminalShowingHold);
+ (terminalPlacement === 'right'
+ ? !terminalColumnCollapsed || terminalShowingHold
+ : !bottomTerminalCollapsed);
const agentsShowing =
agentsColumnPresent && (!agentsColumnCollapsed || agentsShowingHold) && agentsContainer != null;
useEffect(() => {
@@ -586,9 +949,38 @@ function EditorAreaInner({
]);
useEffect(() => {
if (!agentsColumnPresent) setAgentsShowingHold(false);
- if (!terminalColumnPresent) setTerminalShowingHold(false);
+ if (!terminalColumnPresent) {
+ setTerminalShowingHold(false);
+ terminalCollapsedByUserRef.current = false;
+ }
}, [agentsColumnPresent, terminalColumnPresent]);
+ const onPaneExtentChangeRef = useRef(onPaneExtentChange);
+ useLayoutEffect(() => {
+ onPaneExtentChangeRef.current = onPaneExtentChange;
+ });
+ const paneExtentObserverRef = useRef<ResizeObserver | null>(null);
+ useLayoutEffect(() => {
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(() => onPaneExtentChangeRef.current?.());
+ paneExtentObserverRef.current = observer;
+ return () => {
+ observer.disconnect();
+ paneExtentObserverRef.current = null;
+ };
+ }, []);
+ useLayoutEffect(() => {
+ const observer = paneExtentObserverRef.current;
+ if (observer == null) return;
+ const mounts = [agentsContainer, rightTerminalContainer, bottomTerminalContainer].filter(
+ (mount) => mount != null,
+ );
+ for (const mount of mounts) observer.observe(mount);
+ return () => {
+ for (const mount of mounts) observer.unobserve(mount);
+ };
+ }, [agentsContainer, rightTerminalContainer, bottomTerminalContainer]);
+
useEffect(() => {
isCollapsedRef.current = isCollapsed;
}, [isCollapsed]);
@@ -597,6 +989,7 @@ function EditorAreaInner({
const [initialDocPanelWidthPx] = useState(() => getInitialDocPanelWidth());
const docPanelWidthPxRef = useRef(initialDocPanelWidthPx);
+ const [preferredDocPanelWidthPx, setPreferredDocPanelWidthPx] = useState(initialDocPanelWidthPx);
const writeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
function debouncedWriteDocPanelWidth(px: number) {
if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);
@@ -649,6 +1042,33 @@ function EditorAreaInner({
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();
+ useLayoutEffect(() => {
+ if (docPanelCover || isCollapsed) return;
+ const focusedPanelControl = docPanelDockFocusRef.current;
+ if (focusedPanelControl == null) return;
+ const frame = requestAnimationFrame(() => {
+ if (
+ docPanelDockFocusRef.current === focusedPanelControl &&
+ focusedPanelControl.isConnected &&
+ docPanelHost.contains(focusedPanelControl) &&
+ docPanelHost.closest('#doc-panel') != null &&
+ focusedPanelControl.closest('[inert]') == null &&
+ focusedPanelControl.getClientRects().length > 0
+ ) {
+ focusedPanelControl.focus({ preventScroll: true });
+ if (document.activeElement === focusedPanelControl) docPanelDockFocusRef.current = null;
+ }
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [docPanelCover, isCollapsed, docPanelHost]);
+ useAttachFileListHost(fileListHost, filesCover ? filesCoverTarget : fileListSlotEl);
useLayoutEffect(() => {
if (workspaceHeaderContainer == null || workspaceColumnEl == null) return;
@@ -666,14 +1086,25 @@ function EditorAreaInner({
}, [workspaceHeaderContainer, workspaceColumnEl]);
const docSlotPresentRef = useRef(false);
+ const docSlotHeldForLoadRef = useRef(false);
const presenceRepinRetryRef = useRef<RailLayoutRetryController>({
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) => {
@@ -689,9 +1120,46 @@ function EditorAreaInner({
});
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;
@@ -700,15 +1168,18 @@ function EditorAreaInner({
const group = groupRef.current;
if (group == null) return null;
try {
- const workspaceWidthPx = resolveGroupPxWidth();
+ const workspaceWidthPx = resolveSharedRowPxWidth();
if (workspaceWidthPx == null) return null;
if (!docSlotPresentRef.current) {
return { workspaceWidthPx, otherRailWidthPx: 0 };
}
- const measuredWidthPx = panelRef.current?.getSize().inPixels;
+ if (isCollapsedRef.current) {
+ return { workspaceWidthPx, otherRailWidthPx: 0 };
+ }
+ const measuredWidthPx = readDocPanelPx();
const docWidthPx =
measuredWidthPx != null && measuredWidthPx > 0
- ? measuredWidthPx
+ ? Math.min(measuredWidthPx, docPanelWidthPxRef.current)
: docPanelWidthPxRef.current;
return {
workspaceWidthPx,
@@ -732,20 +1203,58 @@ function EditorAreaInner({
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,
+ previous: admissionPrevious,
current: admissionVisibilityRef.current,
- trigger,
+ 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') {
@@ -765,7 +1274,11 @@ function EditorAreaInner({
const enforceRightRailAdmissionRef = useRef(enforceRightRailAdmission);
useLayoutEffect(() => {
enforceRightRailAdmissionRef.current = enforceRightRailAdmission;
+ filesCanDockRef.current = filesCanDock;
admissionVisibilityRef.current = admissionVisibility;
+ editorColumnChromePxRef.current = editorColumnChromePx;
+ editorVisibleRef.current = editorVisible;
+ bottomTerminalHeldRef.current = bottomTerminalHeld;
});
useLayoutEffect(() => {
@@ -790,6 +1303,121 @@ function EditorAreaInner({
});
}, [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;
+ try {
+ outerGroup.setLayout(next);
+ } catch (error) {
+ reportUnexpectedPanelGroupFailure('reopen-editor-column-write-failed', error);
+ }
+ railPlanWriteInProgressRef.current = false;
+ }
+
function applyRailLayout(
docCollapsed: boolean,
{
@@ -798,122 +1426,176 @@ function EditorAreaInner({
agentsWidthOverridePx?: number;
} = {},
): boolean {
- const group = groupRef.current;
- if (group == null) {
+ 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 panelSpace: RailPanelSpaceResult;
- let layout: Record<string, number>;
+ let outerSpace: RailPanelSpaceResult;
+ let innerSpace: RailPanelSpaceResult;
+ let outerLayout: Record<string, number>;
+ let innerLayout: Record<string, number>;
try {
- panelSpace = resolveRailPanelSpace(groupContainerElRef.current);
- layout = group.getLayout();
+ 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 (!panelSpace.ok) {
- railPinOutcomeRef.current = { stage: 'panel-space-unresolved', refusal: panelSpace.refusal };
+ 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 containerPx = panelSpace.panelSpacePx;
- const accounting = accountRailLayout(Object.keys(layout));
- if (!accounting.ok) {
+ 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 =
- accounting.unaccountedIds.length === 0
+ unaccountedIds.length === 0
? { stage: 'no-residual-panel' }
- : { stage: 'layout-unaccounted', unaccountedIds: accounting.unaccountedIds };
+ : { stage: 'layout-unaccounted', unaccountedIds };
if (import.meta.env.DEV) {
console.warn(
JSON.stringify({
event: 'right-rail-accounting-failed',
- unaccountedIds: accounting.unaccountedIds,
+ unaccountedIds,
}),
);
}
return false;
}
- const residualId = accounting.residualId;
- const buildPins = (atFloor: boolean): Record<string, number> => {
- const pins: Record<string, number> = {};
- if (DOC_PANEL_ID in layout) {
- pins[DOC_PANEL_ID] =
+ 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 layout) {
- pins[TERMINAL_COLUMN_ID] = !admissionVisibilityRef.current.terminalRightVisible
- ? 0
- : atFloor
- ? RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX
- : terminalWidthPxRef.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 layout) {
- pins[AGENTS_COLUMN_ID] = !admissionVisibilityRef.current.agentsVisible
+ if (AGENTS_COLUMN_ID in outerLayout) {
+ outer[AGENTS_COLUMN_ID] = !admissionVisibilityRef.current.agentsVisible
? 0
: atFloor
? MIN_AGENTS_PANEL_WIDTH
: (agentsWidthOverridePx ?? agentsPreferredWidthPxRef.current);
}
- return pins;
+ return { inner, outer, all: { ...inner, ...outer } };
};
- const widthsFrom = (pcts: Record<string, number>) => {
+ 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(pcts)) widths.set(id, (pct / 100) * containerPx);
+ 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).length === 0) {
+ if (Object.keys(pins.all).length === 0) {
railPinOutcomeRef.current = { stage: 'no-pinned-columns' };
return false;
}
-
- let next = computeStickyRepinLayout({
- currentLayout: layout,
- containerPx,
- pinnedPx: pins,
- residualId,
- });
- if (next === layout) {
- pins = buildPins(true);
- next = computeStickyRepinLayout({
- currentLayout: layout,
- containerPx,
- pinnedPx: pins,
- residualId,
- });
- }
- if (next === layout) {
- const shortfall = describeRailFloorShortfall(pins, widthsFrom(layout));
+ if (!fitsSharedRow(pins.all)) pins = buildPins(true);
+ if (!fitsSharedRow(pins.all)) {
+ const shortfall = describeRailFloorShortfall(
+ pins.all,
+ withDocRendered(renderedWidths(outerLayout, innerLayout)),
+ );
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 {
- group.setLayout(next);
+ 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;
}
- let readBack: Record<string, number>;
+ railPlanWriteInProgressRef.current = false;
+ let outerReadBack: Record<string, number>;
+ let innerReadBack: Record<string, number>;
try {
- readBack = group.getLayout();
+ outerReadBack = outerGroup.getLayout();
+ innerReadBack = innerGroup.getLayout();
} catch (error) {
railPinOutcomeRef.current = { stage: 'verify-failed' };
reportUnexpectedPanelGroupFailure('apply-rail-layout-verify-failed', error);
return false;
}
- const shortfall = describeRailWidthShortfall(pins, widthsFrom(readBack));
+ const shortfall = describeRailWidthShortfall(
+ pins.all,
+ renderedWidths(outerReadBack, innerReadBack, innerTargetPx),
+ );
const pinned = Object.keys(shortfall).length === 0;
railPinOutcomeRef.current = pinned
? { stage: 'pinned' }
@@ -921,16 +1603,54 @@ function EditorAreaInner({
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 reclaimHiddenRailColumn(columnId: string, present: boolean, widthPx: number) {
if (present || widthPx <= 0) return;
queueMicrotask(() => {
- const group = groupRef.current;
+ const innerRow = columnId === DOC_PANEL_ID;
+ if (!innerRow && !editorVisibleRef.current) return;
+ const group = innerRow ? innerGroupRef.current : groupRef.current;
if (group == null) return;
let layout: Record<string, number>;
let containerPx: number | null;
try {
layout = group.getLayout();
- containerPx = resolveGroupPxWidth();
+ containerPx = innerRow ? resolveInnerGroupPxWidth() : resolveGroupPxWidth();
} catch (error) {
reportUnexpectedPanelGroupFailure('reclaim-hidden-rail-read-failed', error);
return;
@@ -957,12 +1677,32 @@ function EditorAreaInner({
docCollapsed: boolean,
overrides?: { agentsWidthOverridePx?: number },
): RailLayoutRetryOutcome {
- if (
- isDraggingDocHandleRef.current ||
- isDraggingTerminalHandleRef.current ||
- isDraggingAgentsHandleRef.current
- )
- return 'blocked';
+ 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';
}
@@ -977,8 +1717,27 @@ function EditorAreaInner({
});
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,
+ pointerId: number | null,
setDragging: (dragging: boolean) => void,
draggingRef: { current: boolean },
onCommit?: () => void,
@@ -996,12 +1755,13 @@ function EditorAreaInner({
onDragEnd?.();
}
function onPointerUp(event: PointerEvent) {
- if (event.pointerId !== pointerId) return;
+ if (pointerId != null && event.pointerId !== pointerId) return;
end();
onCommit?.();
+ replanAfterDragEnd();
}
function onPointerCancel(event: PointerEvent) {
- if (event.pointerId !== pointerId) return;
+ if (pointerId != null && event.pointerId !== pointerId) return;
end();
assertRightRailLayoutRef.current(isCollapsedRef.current);
}
@@ -1009,6 +1769,71 @@ function EditorAreaInner({
window.addEventListener('pointerup', onPointerUp);
window.addEventListener('pointercancel', onPointerCancel);
}
+ function beginDocHandleDrag(pointerId: number | null) {
+ trackHandleDrag(
+ pointerId,
+ setIsDraggingDocHandle,
+ isDraggingDocHandleRef,
+ () => {
+ if (panelRef.current?.isCollapsed()) writeDocPanelIntent(false);
+ },
+ () => 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(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);
+ }
+ }
useEffect(() => () => endHandleDragRef.current?.(), []);
function cancelAgentsSettlement() {
@@ -1029,7 +1854,7 @@ function EditorAreaInner({
});
}
- function settleAgentsPointerRelease() {
+ function settleAgentsPointerRelease(options?: { readonly leaveCollapsed: boolean }) {
cancelAgentsSettlement();
const measuredWidthPx = agentsColumnPanelRef.current?.getSize().inPixels;
const decision = resolveAgentsPanelPointerRelease(
@@ -1037,10 +1862,17 @@ function EditorAreaInner({
agentsPreferredWidthPxRef.current,
);
const context = createAgentsPanelPointerReleaseRetryContext(decision);
+ if (!editorVisibleRef.current && context.decision !== 'close') {
+ superviseAgentsPointerSettlement(context);
+ return;
+ }
switch (context.decision) {
case 'close':
- if (onAgentsVisibleChange != null) {
+ if (options?.leaveCollapsed) {
+ dragCloseRequestedRef.current = true;
+ } else if (onAgentsVisibleChange != null) {
pendingAgentsVisibilityRetryContextRef.current = context;
+ dragCloseRequestedRef.current = true;
onAgentsVisibleChange(false);
} else {
superviseAgentsPointerSettlement(context);
@@ -1064,13 +1896,7 @@ function EditorAreaInner({
}
function settleAgentsKeyboardLayout(layout: Record<string, number>, isUserInteraction: boolean) {
- if (
- !isUserInteraction ||
- isDraggingDocHandleRef.current ||
- isDraggingTerminalHandleRef.current ||
- isDraggingAgentsHandleRef.current
- )
- return;
+ if (!isUserInteraction || railDragInProgress() || !editorVisibleRef.current) return;
const activeElement = document.activeElement;
if (
!(activeElement instanceof HTMLElement) ||
@@ -1123,55 +1949,352 @@ function EditorAreaInner({
return () => cancelRailLayoutRetry(railColumnSyncRetryRef);
}, [terminalColumnPresent, agentsColumnPresent]);
- function expandDocPanel() {
- if (!docSlotPresentRef.current) return;
- assertRightRailLayout(false);
+ 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,
+ 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 {
+ return docSlotPresentRef.current && !docSlotHeldForLoadRef.current;
+ }
+
+ function writeDocPanelIntent(open: boolean) {
+ if (!open && preferredSidebar === 'information') setPreferredSidebar(null);
+ const next = open ? 'open' : 'collapsed';
+ applyToggleAtEveryWidth('right', next);
+ setDocPanelIntentOpen(open);
+ }
+
+ function returnFocusFromDocPanelCover() {
+ const opener = docPanelCoverOpenerRef.current;
+ requestAnimationFrame(() => {
+ const candidates = [
+ opener,
+ document.querySelector<HTMLElement>('[data-doc-panel-toggle]'),
+ document.querySelector<HTMLElement>('[data-header-pane-button="editor"]'),
+ terminalEditorRegion,
+ ];
+ for (const candidate of candidates) {
+ if (
+ candidate?.isConnected &&
+ candidate !== document.body &&
+ (candidate.tabIndex >= 0 || candidate === terminalEditorRegion) &&
+ !candidate.matches(':disabled') &&
+ candidate.closest('[inert]') == null &&
+ candidate.getClientRects().length > 0 &&
+ getComputedStyle(candidate).visibility === 'visible'
+ ) {
+ candidate.focus();
+ if (document.activeElement === candidate) return;
+ }
+ }
+ });
+ }
+
+ function dismissDocPanelCover() {
+ setPendingDocPanelDestination(null);
+ setDocPanelCover(false);
+ returnFocusFromDocPanelCover();
+ }
+
+ function requestDocPanelDestination(
+ docName: string,
+ allowMissing = false,
+ onReady?: () => void,
+ completion: 'synced' | 'navigated' = 'synced',
+ ) {
+ if (docPanelCover)
+ setPendingDocPanelDestination({ docName, allowMissing, onReady, completion });
+ else onReady?.();
+ }
+
+ const sidebarFitContext: SidebarFitContext = {
+ widthPx: editorCardWidthPx,
+ filesDockWidth,
+ filesPresent: fileListHost != null,
+ informationWidthPx: preferredDocPanelWidthPx,
+ filesIntentOpen,
+ informationIntentOpen: docPanelIntentOpen,
+ preferredSidebar,
+ };
+ function adoptDraggedDocPanelWidth(widthPx: number) {
+ const liveCardPx = liveEditorCardWidthPxRef.current ?? editorCardWidthPx;
+ const liveInnerPx = liveInnerWidthPxRef.current ?? innerWidthPx;
+ const crossesThreshold =
+ sidebarFitWidthBucket({ ...sidebarFitContext, informationWidthPx: widthPx }, liveCardPx) !==
+ sidebarFitWidthBucket(sidebarFitContext, liveCardPx) ||
+ docPanelDockReadyFor(liveInnerPx, widthPx) !==
+ docPanelDockReadyFor(liveInnerPx, preferredDocPanelWidthPx);
+ if (crossesThreshold) setPreferredDocPanelWidthPx(widthPx);
+ }
+ const syncMeasuredWidths = useEffectEvent(() => {
+ const liveCardPx = liveEditorCardWidthPxRef.current;
+ if (
+ liveCardPx !== editorCardWidthPx &&
+ sidebarFitWidthBucket(sidebarFitContext, liveCardPx) !==
+ sidebarFitWidthBucket(sidebarFitContext, editorCardWidthPx)
+ ) {
+ setEditorCardWidthPx(liveCardPx);
+ }
+ const liveInnerPx = liveInnerWidthPxRef.current;
+ if (
+ liveInnerPx !== innerWidthPx &&
+ docPanelDockReadyFor(liveInnerPx, preferredDocPanelWidthPx) !==
+ docPanelDockReadyFor(innerWidthPx, preferredDocPanelWidthPx)
+ ) {
+ setInnerWidthPx(liveInnerPx);
+ }
+ });
+ useLayoutEffect(() => {
+ syncMeasuredWidths();
+ });
+ useLayoutEffect(() => {
+ const card = editorCardRef.current;
+ if (card == null || typeof ResizeObserver === 'undefined') return;
+ const measure = () => {
+ const cardWidth = card.getBoundingClientRect().width;
+ if (cardWidth <= 0) return;
+ liveEditorCardWidthPxRef.current = cardWidth;
+ syncMeasuredWidths();
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(card);
+ return () => observer.disconnect();
+ }, []);
+ useLayoutEffect(() => {
+ if (innerContainerEl == null || typeof ResizeObserver === 'undefined') return;
+ const measure = () => {
+ const width = innerContainerEl.getBoundingClientRect().width;
+ if (width <= 0) return;
+ liveInnerWidthPxRef.current = width;
+ syncMeasuredWidths();
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(innerContainerEl);
+ return () => observer.disconnect();
+ }, [innerContainerEl]);
+
+ function expandDocPanel(explicit = false) {
+ if (!docPanelToggleable()) return;
+ if (filesCover) dismissFilesCover(false);
+ const fit = resolveCurrentEditorSidebarFit(
+ sidebarFitContext,
+ docSlotPresentRef.current,
+ filesIntentOpen,
+ true,
+ 'information',
+ measureSidebarUnitWidth(editorCardRef.current, editorCardWidthPx),
+ );
+ setPreferredSidebar(fit.mode === 'both' ? null : 'information');
+ setFilesCanDock(fit.filesDocked);
+ if (explicit) writeDocPanelIntent(true);
+ else setDocPanelIntentOpen(true);
+ if (fit.mode !== 'cover') {
+ setDocPanelCover(false);
+ return;
+ }
+ docPanelCoverOpenerRef.current =
+ document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ assertRightRailLayout(true);
+ setDocPanelCover(true);
}
function togglePanel() {
- if (!docSlotPresentRef.current) return;
- const partition = rightPartitionRef.current;
- const collapsed = isCollapsedRef.current;
- if (collapsed) {
- applyToggle('right', partition, 'open');
- assertRightRailLayout(false);
- } else {
- applyToggle('right', partition, 'collapsed');
+ if (!docPanelToggleable()) return;
+ revealEditorBeforeActing();
+ if (docPanelCover || (!isCollapsedRef.current && docPanelIntentOpen)) {
+ writeDocPanelIntent(false);
assertRightRailLayout(true);
+ if (docPanelCover) dismissDocPanelCover();
+ return;
}
+ expandDocPanel(true);
}
- useEffect(() => {
- const mql = window.matchMedia(`(min-width: ${RIGHT_COLLAPSE_THRESHOLD}px)`);
- const onChange = () => {
- const newPartition = resolvePartition(embeddedHost, window.innerWidth, 'right');
- setRightPartition(newPartition);
- const pins = readPins();
- const effective = resolveEffectiveState('right', newPartition, pins);
- const nextCollapsed = effective === 'collapsed';
- setIsCollapsed(nextCollapsed);
- assertRightRailLayout(nextCollapsed);
- };
- mql.addEventListener('change', onChange);
- return () => mql.removeEventListener('change', onChange);
- }, [
- embeddedHost,
- // biome-ignore lint/correctness/useExhaustiveDependencies: assertRightRailLayout is render-bound; re-subscribing keeps the handler fresh (mirrors the ⌥⌘B menu effect below)
- assertRightRailLayout,
- ]);
+ 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';
+ const innerPx = resolveInnerGroupPxWidth();
+ if (innerPx == null) return 'blocked';
+ const collapsed =
+ !docSlotPresentRef.current ||
+ !docPanelIntentOpen ||
+ !resolveCurrentEditorSidebarFit(sidebarFitContext, docSlotPresentRef.current)
+ .informationDocked ||
+ innerPx < docPanelWidthPxRef.current + DOC_USABLE_MIN_WIDTH_PX;
+ const expectedDocWidth = collapsed ? 0 : docPanelWidthPxRef.current;
+ const actualDocWidth = innerContainerElRef.current
+ ?.querySelector<HTMLElement>(`#${DOC_PANEL_ID}`)
+ ?.getBoundingClientRect().width;
+ if (actualDocWidth != null && Math.abs(actualDocWidth - expectedDocWidth) <= 1)
+ return 'applied';
+ const group = innerGroupRef.current;
+ if (group == null) return 'blocked';
+ try {
+ const layout = group.getLayout();
+ const residualId = findResidualPanelId(Object.keys(layout));
+ if (residualId == null || !(DOC_PANEL_ID in layout)) return 'blocked';
+ isCollapsedRef.current = collapsed;
+ group.setLayout(
+ computeStickyRepinLayout({
+ currentLayout: layout,
+ containerPx: innerPx,
+ pinnedPx: { [DOC_PANEL_ID]: expectedDocWidth },
+ residualId,
+ }),
+ );
+ return 'failed';
+ } catch (error) {
+ reportUnexpectedPanelGroupFailure('settle-observed-information-width-failed', error);
+ return 'failed';
+ }
+ });
+ const settleObservedDocWidth = useEffectEvent(() => {
+ if (observedDocWidthRetryRef.current.context != null) return;
+ runRailLayoutRetry({
+ retryRef: observedDocWidthRetryRef,
+ attempt: attemptObservedDocWidth,
+ context: {
+ decision: 'observed-doc-width',
+ targetWidthPx: docPanelWidthPxRef.current,
+ },
+ });
+ });
useEffect(() => {
- if (groupContainerEl == null) return;
+ if (groupContainerEl == null || innerContainerEl == null) return;
if (isEmbedded) return;
- const ro = new ResizeObserver(() => {
+ 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();
+ });
+ outerObserver.observe(groupContainerEl);
+ innerObserver.observe(innerContainerEl);
+ if (docPanel != null) innerObserver.observe(docPanel);
+ return () => {
+ outerObserver.disconnect();
+ innerObserver.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);
});
- ro.observe(groupContainerEl);
- return () => ro.disconnect();
- }, [groupContainerEl, isEmbedded]);
+ observer.observe(fileListSlotEl);
+ return () => observer.disconnect();
+ }, [fileListSlotEl]);
const openRequestedDocPanelTab = useEffectEvent((tab: PanelTab) => {
+ revealEditor();
if (docPanelMode === 'agent') closeActivityPanel();
onActiveTabChange(tab);
expandDocPanel();
@@ -1189,17 +2312,15 @@ function EditorAreaInner({
});
}, []);
+ const expandDocPanelEvent = useEffectEvent(() => expandDocPanel());
useEffect(() => {
if (docPanelExpandSignal === 0) return;
- expandDocPanel();
- }, [
- docPanelExpandSignal,
- // biome-ignore lint/correctness/useExhaustiveDependencies: expandDocPanel is render-bound; re-running keeps the closure fresh
- expandDocPanel,
- ]);
+ revealEditor();
+ expandDocPanelEvent();
+ }, [docPanelExpandSignal]);
useLayoutEffect(() => {
- if (!isCollapsed) return;
+ if (!isCollapsed || docPanelCover) return;
const panelEl = document.getElementById(DOC_PANEL_ID);
if (!panelEl?.contains(document.activeElement)) return;
const toggle = document.querySelector<HTMLElement>('[data-doc-panel-toggle]');
@@ -1208,13 +2329,15 @@ function EditorAreaInner({
return;
}
document.querySelector<HTMLElement>('[data-sidebar="trigger"]')?.focus();
- }, [isCollapsed]);
+ }, [isCollapsed, docPanelCover]);
useEffect(() => {
- setViewMenuState({ docPanelVisible: !isCollapsed });
+ setViewMenuState({ docPanelVisible: !isCollapsed || docPanelCover });
if (window.okDesktop == null) return;
- window.okDesktop.editor.notifyViewMenuStateChanged({ docPanelVisible: !isCollapsed });
- }, [isCollapsed]);
+ window.okDesktop.editor.notifyViewMenuStateChanged({
+ docPanelVisible: !isCollapsed || docPanelCover,
+ });
+ }, [isCollapsed, docPanelCover]);
useEffect(() => {
return subscribeLocalMenuAction((action) => {
@@ -1268,7 +2391,8 @@ function EditorAreaInner({
let viewContent: ReactNode;
let docSlotContent: ReactNode = null;
let renderFocusedDocument: ((activityMount: ReactNode) => ReactNode) | null = null;
- let coldStartSkeleton = false;
+ let docSlotHeldForLoad = false;
+ let skeletonReplacesWorkspace = false;
if (activeTarget?.kind === 'large-file') {
viewContent = (
@@ -1317,7 +2441,10 @@ function EditorAreaInner({
</div>
}
>
- <LazyActivityModeContent showBackButton={false} />
+ <LazyActivityModeContent
+ showBackButton={false}
+ onDestinationRequested={requestDocPanelDestination}
+ />
</Suspense>
);
}
@@ -1364,7 +2491,6 @@ function EditorAreaInner({
subtitle={activeTarget.subtitle}
level={activeTarget.level}
path={activeTarget.path}
- reserveRightGutter={rightRevealTabPresent}
/>
);
} else if (shareReceiveMiss) {
@@ -1372,12 +2498,10 @@ function EditorAreaInner({
} else if (!activeProvider || !activeDocName) {
const hashDoc = typeof window !== 'undefined' ? docNameFromHash(window.location.hash) : null;
if (hashDoc !== null) {
- if (terminalBridge != null && everHadProvider) {
- viewContent = <EditorSkeleton />;
- docSlotContent = <div className="min-h-0 flex-1" />;
- } else {
- coldStartSkeleton = true;
- }
+ viewContent = <EditorSkeleton />;
+ docSlotContent = <div className="min-h-0 flex-1" />;
+ docSlotHeldForLoad = true;
+ skeletonReplacesWorkspace = terminalBridge == null || !everHadProvider;
} else if (isBlobRunnerNewTabId(activeNewTabId)) {
viewContent = <OkBlobRunnerPage />;
} else {
@@ -1439,8 +2563,10 @@ function EditorAreaInner({
<Suspense fallback={null}>
<LazyTimelineDiffPane
view={timelineDiff}
- isPanelCollapsed={isCollapsed}
+ isPanelCollapsed={isCollapsed && !docPanelCover}
onTogglePanel={togglePanel}
+ onDestinationComplete={completeDocPanelDestination}
+ onDestinationFailed={reportCoveredDiffFailure}
/>
</Suspense>
) : null}
@@ -1449,8 +2575,10 @@ function EditorAreaInner({
<Suspense fallback={null}>
<LazyAgentDiffPane
view={agentDiff}
- isPanelCollapsed={isCollapsed}
+ isPanelCollapsed={isCollapsed && !docPanelCover}
onTogglePanel={togglePanel}
+ onDestinationComplete={completeDocPanelDestination}
+ onDestinationFailed={reportCoveredDiffFailure}
/>
</Suspense>
) : null}
@@ -1488,7 +2616,9 @@ function EditorAreaInner({
activeTab={activeTab}
onActiveTabChange={onActiveTabChange}
mode={docPanelMode}
- isCollapsed={isCollapsed}
+ isCollapsed={isCollapsed && !docPanelCover}
+ onDestinationComplete={completeDocPanelDestination}
+ onDestinationRequested={requestDocPanelDestination}
/>
);
}
@@ -1496,15 +2626,210 @@ function EditorAreaInner({
if (noteWindow) docSlotContent = null;
const docSlotPresent = docSlotContent != null;
+ const sidebarFit = resolveCurrentEditorSidebarFit(sidebarFitContext, docSlotPresent);
+ const docPanelCanDock = sidebarFit.informationDocked;
+ const docPanelDockReady = docPanelDockReadyFor(innerWidthPx, preferredDocPanelWidthPx);
+ const coordinateFilesRequest = useFilesRequestCoordinator({
+ fit: sidebarFitContext,
+ editorCardRef,
+ docSlotPresent,
+ setPreferredSidebar,
+ setDocPanelCover,
+ setPendingDocPanelDestination,
+ setFilesCanDock,
+ });
+ useLayoutEffect(() => registerFilesOpenRequestHandler(coordinateFilesRequest));
+ useLayoutEffect(() => registerFilesCoverSelectionHandler(setDestinationFocusDocName));
+ useLayoutEffect(() => {
+ setFilesCanDock(sidebarFit.filesDocked);
+ }, [sidebarFit.filesDocked, setFilesCanDock]);
+ const docPanelOnScreen = docPanelCover || !isCollapsed;
+ useLayoutEffect(() => {
+ if (sidebarFit.mode === 'both' && preferredSidebar != null) setPreferredSidebar(null);
+ }, [sidebarFit.mode, preferredSidebar]);
+ const showDocPanelToggle =
+ !noteWindow && renderFocusedDocument != null && activeDocConflict === null;
+ const workspaceHeaderChrome: WorkspaceHeaderChrome = {
+ trailing: showDocPanelToggle ? (
+ <DocPanelToggle
+ isPanelCollapsed={!docPanelOnScreen}
+ onTogglePanel={togglePanel}
+ panelId={docPanelCover ? 'doc-panel-cover' : DOC_PANEL_ID}
+ />
+ ) : null,
+ };
+
+ const returnFocusFromDocPanelCoverEvent = useEffectEvent(returnFocusFromDocPanelCover);
+ useLayoutEffect(() => {
+ if (filesCover && docPanelCover) setDocPanelCover(false);
+ }, [filesCover, docPanelCover]);
+ const dismissFilesCoverEvent = useEffectEvent(dismissFilesCover);
+ useLayoutEffect(() => {
+ if (!filesCover) return;
+ if (fileListHost == null) {
+ dismissFilesCoverEvent(false);
+ return;
+ }
+ filesBackRef.current?.focus();
+ }, [filesCover, fileListHost]);
+ useEffect(() => {
+ if (!filesCover) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.key !== 'Escape' ||
+ event.isComposing ||
+ event.defaultPrevented ||
+ isOverlayLayerOpen() ||
+ !escapeBelongsToCover(event, '[data-files-cover]', null)
+ )
+ return;
+ event.preventDefault();
+ dismissFilesCoverEvent();
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [filesCover]);
+ useLayoutEffect(() => {
+ if (!docSlotPresent) {
+ if (docPanelCover) {
+ setDocPanelCover(false);
+ setPendingDocPanelDestination(null);
+ returnFocusFromDocPanelCoverEvent();
+ }
+ return;
+ }
+ const collapsed = !docPanelIntentOpen || !docPanelCanDock || !docPanelDockReady;
+ if (isCollapsedRef.current !== collapsed) assertRightRailLayoutRef.current(collapsed);
+ if (docPanelCover && docPanelCanDock && docPanelDockReady) {
+ const pendingDestination = pendingDocPanelDestinationRef.current;
+ if (pendingDestination !== null) {
+ pendingDestination.onReady?.();
+ if (pendingDestination.completion === 'synced') {
+ setDestinationFocusDocName(pendingDestination.docName);
+ }
+ } else {
+ if (document.activeElement === docPanelBackRef.current) returnFocusFromDocPanelCoverEvent();
+ if (
+ document.activeElement instanceof HTMLElement &&
+ docPanelHost.contains(document.activeElement)
+ ) {
+ docPanelDockFocusRef.current = document.activeElement;
+ }
+ }
+ setDocPanelCover(false);
+ }
+ }, [
+ docSlotPresent,
+ docPanelIntentOpen,
+ docPanelCanDock,
+ docPanelDockReady,
+ docPanelCover,
+ docPanelHost,
+ ]);
+
+ useLayoutEffect(() => {
+ if (docPanelCover) docPanelBackRef.current?.focus();
+ }, [docPanelCover]);
+
+ const dismissDocPanelCoverEvent = useEffectEvent(dismissDocPanelCover);
+ useEffect(() => {
+ if (!docPanelCover) setPendingDocPanelDestination(null);
+ }, [docPanelCover]);
+ useEffect(() => {
+ if (!docPanelCover || pendingDocPanelDestination?.docName !== activeDocName) return;
+ const completeWhenSynced = () => {
+ if (
+ !activeProvider?.isSynced &&
+ !(pendingDocPanelDestination.allowMissing && activeTarget?.kind === 'missing')
+ )
+ return;
+ pendingDocPanelDestination.onReady?.();
+ setPendingDocPanelDestination(null);
+ if (pendingDocPanelDestination.completion === 'navigated') return;
+ setDocPanelCover(false);
+ setDestinationFocusDocName(activeDocName);
+ };
+ completeWhenSynced();
+ activeProvider?.on('synced', completeWhenSynced);
+ return () => {
+ activeProvider?.off('synced', completeWhenSynced);
+ };
+ }, [docPanelCover, pendingDocPanelDestination, activeDocName, activeProvider, activeTarget]);
+ useEffect(() => {
+ if (filesCover || docPanelCover) setDestinationFocusDocName(null);
+ }, [filesCover, docPanelCover]);
+ useEffect(() => {
+ if (destinationFocusDocName === null) return;
+ const abandon = () => setDestinationFocusDocName(null);
+ const deadline = window.setTimeout(abandon, DESTINATION_FOCUS_DEADLINE_MS);
+ window.addEventListener('pointerdown', abandon, true);
+ window.addEventListener('keydown', abandon, true);
+ return () => {
+ window.clearTimeout(deadline);
+ window.removeEventListener('pointerdown', abandon, true);
+ window.removeEventListener('keydown', abandon, true);
+ };
+ }, [destinationFocusDocName]);
+ useEffect(() => {
+ if (
+ filesCover ||
+ docPanelCover ||
+ destinationFocusDocName === null ||
+ destinationFocusDocName !== activeDocName
+ )
+ return;
+ const focusDestination = () => {
+ const mount = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-editor-activity-mount]'),
+ ).find(
+ (element) =>
+ element.dataset.docName === destinationFocusDocName &&
+ element.closest('[inert]') === null &&
+ element.getClientRects().length > 0,
+ );
+ const editor = mount?.querySelector<HTMLElement>(
+ '.ProseMirror[contenteditable="true"], .cm-content[contenteditable="true"]',
+ );
+ if (!editor || editor.getClientRects().length === 0) return;
+ editor.focus({ preventScroll: true });
+ if (document.activeElement === editor) setDestinationFocusDocName(null);
+ };
+ const observer = new MutationObserver(focusDestination);
+ observer.observe(document.getElementById('root') ?? document.body, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['inert', 'style', 'contenteditable'],
+ });
+ focusDestination();
+ return () => observer.disconnect();
+ }, [filesCover, docPanelCover, destinationFocusDocName, activeDocName]);
+ useEffect(() => {
+ if (!docPanelCover) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.key !== 'Escape' ||
+ event.isComposing ||
+ event.defaultPrevented ||
+ isOverlayLayerOpen() ||
+ !escapeBelongsToCover(event, '[data-doc-panel-cover]', docPanelCoverOpenerRef.current)
+ )
+ return;
+ event.preventDefault();
+ dismissDocPanelCoverEvent();
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [docPanelCover]);
useLayoutEffect(() => {
const docSlotPresenceChanged = docSlotPresentRef.current !== docSlotPresent;
docSlotPresentRef.current = docSlotPresent;
+ docSlotHeldForLoadRef.current = docSlotHeldForLoad;
if (!docSlotPresenceChanged) return;
- const docCollapsed = isCollapsedRef.current;
runRailLayoutRetry({
retryRef: presenceRepinRetryRef,
- attempt: () => attemptRailLayout(docCollapsed),
+ attempt: () => attemptRailLayout(isCollapsedRef.current),
context: {
decision: 'sync-doc-presence',
targetWidthPx: agentsVisible ? agentsPreferredWidthPxRef.current : 0,
@@ -1617,9 +2942,6 @@ function EditorAreaInner({
provider={provider}
isSourceMode={isSourceMode}
onModeChange={onModeChange}
- isPanelCollapsed={isCollapsed}
- onTogglePanel={togglePanel}
- reserveRightGutter={docName === activeDocName && rightRevealTabPresent && isCollapsed}
/>
)
}
@@ -1632,40 +2954,50 @@ function EditorAreaInner({
);
}
- const leftColumn = (
- <TerminalDock
- placement={terminalPlacement}
- visible={terminalVisible}
- onVisibleChange={onTerminalVisibleChange ?? (() => {})}
- onBottomContainer={setBottomTerminalContainer}
- onEditorRegion={setTerminalEditorRegion}
+ const documentArea = skeletonReplacesWorkspace ? (
+ <EditorSkeleton />
+ ) : (
+ <div
+ ref={setTerminalEditorRegion}
+ tabIndex={-1}
+ data-editor-region=""
+ className="relative flex min-h-0 flex-1 flex-col outline-none"
>
- <EditorWorkspace
- renderHeader={(tabs) =>
- workspaceHeaderContainer == null
- ? null
- : createPortal(renderWorkspaceHeader(tabs), workspaceHeaderContainer)
- }
- renderPane={renderWorkspacePane}
- renderActivityPool={renderWorkspaceActivityPool}
- />
- </TerminalDock>
+ <EditorContentOnScreenContext value={!docPanelCover && !filesCover}>
+ <EditorWorkspace
+ renderHeader={(tabs) =>
+ workspaceHeaderContainer == null
+ ? null
+ : createPortal(
+ renderWorkspaceHeader(tabs, workspaceHeaderChrome),
+ workspaceHeaderContainer,
+ )
+ }
+ renderPane={renderWorkspacePane}
+ renderActivityPool={renderWorkspaceActivityPool}
+ />
+ </EditorContentOnScreenContext>
+ </div>
);
const docSlot = (
<>
<ResizableHandle
data-doc-panel-handle=""
- withHandle={docSlotPresent && !isCollapsed}
- disabled={!docSlotPresent || isCollapsed}
+ aria-controls={DOC_PANEL_ID}
+ aria-label={t`Resize document panel`}
+ withHandle={docSlotPresent && !isCollapsed && !docPanelCover}
+ disabled={!docSlotPresent || isCollapsed || docPanelCover}
className={docSlotPresent ? undefined : 'pointer-events-none'}
- style={docSlotPresent ? undefined : { display: 'none' }}
+ style={docSlotPresent && !isCollapsed && !docPanelCover ? undefined : { display: 'none' }}
onPointerDown={(event) => {
- trackHandleDrag(event.pointerId, setIsDraggingDocHandle, isDraggingDocHandleRef);
+ beginDocHandleDrag(event.pointerId);
}}
/>
<ResizablePanel
id={DOC_PANEL_ID}
+ role="region"
+ aria-label={t`Document panel`}
panelRef={panelRef}
defaultSize={!docSlotPresent || initialRightCollapsed ? 0 : `${initialDocPanelWidthPx}px`}
minSize={DOC_PANEL_MIN_SIZE}
@@ -1678,38 +3010,47 @@ function EditorAreaInner({
}
if (size.inPixels > 0 && isDraggingDocHandleRef.current) {
docPanelWidthPxRef.current = size.inPixels;
+ adoptDraggedDocPanelWidth(size.inPixels);
debouncedWriteDocPanelWidth(size.inPixels);
}
reclaimHiddenRailColumn(DOC_PANEL_ID, docSlotPresent, size.inPixels);
}}
inert={!docSlotPresent || isCollapsed}
- className="flex flex-col bg-muted/20"
+ className={cn('flex flex-col', SECONDARY_PANEL_SURFACE_CLASS)}
>
- {docSlotContent}
+ <div ref={docPanelDockRef} className="flex h-full min-h-0 w-full flex-col" />
</ResizablePanel>
</>
);
+ 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
- withHandle={terminalColumnPresent}
- className={terminalColumnPresent ? undefined : 'pointer-events-none'}
- style={terminalColumnPresent ? undefined : { display: 'none' }}
+ 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) => {
- trackHandleDrag(
- event.pointerId,
- setIsDraggingTerminalHandle,
- isDraggingTerminalHandleRef,
- () => {
- if (terminalColumnPanelRef.current?.isCollapsed()) {
- onTerminalVisibleChange?.(false);
- }
- },
- () => {
- if (!terminalColumnPanelRef.current?.isCollapsed()) setTerminalShowingHold(false);
- },
- );
+ beginTerminalHandleDrag(event.pointerId);
}}
/>
<ResizablePanel
@@ -1721,11 +3062,22 @@ function EditorAreaInner({
collapsible
collapsedSize={0}
onResize={(size) => {
- if (size.inPixels > 0 && isDraggingTerminalHandleRef.current) {
+ 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) {
@@ -1734,13 +3086,24 @@ function EditorAreaInner({
reclaimHiddenRailColumn(TERMINAL_COLUMN_ID, terminalColumnPresent, size.inPixels);
}}
className="flex flex-col"
+ style={{ overflow: 'visible' }}
>
- <div
- ref={setRightTerminalContainer}
- data-terminal-panel-mount=""
- inert={!terminalColumnPresent || (terminalColumnCollapsed && !terminalShowingHold)}
- className="flex min-h-0 flex-1 flex-col overflow-hidden"
- />
+ {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>
</>
);
@@ -1748,23 +3111,17 @@ function EditorAreaInner({
const agentsColumn = (
<>
<ResizableHandle
- withHandle={agentsColumnPresent}
+ withHandle={agentsHandleShown}
aria-controls={terminalColumnPresent ? TERMINAL_COLUMN_ID : AGENTS_COLUMN_ID}
aria-label={terminalColumnPresent ? t`Terminal` : t`Agents`}
data-agents-panel-resize-handle=""
- className={agentsColumnPresent ? undefined : 'pointer-events-none'}
- style={agentsColumnPresent ? undefined : { display: 'none' }}
+ className={cn(
+ paneCardDividerClass(cardVariant, 'vertical'),
+ !agentsHandleShown && 'pointer-events-none',
+ )}
+ style={agentsHandleShown ? undefined : { display: 'none' }}
onPointerDown={(event) => {
- cancelAgentsSettlement();
- trackHandleDrag(
- event.pointerId,
- setIsDraggingAgentsHandle,
- isDraggingAgentsHandleRef,
- settleAgentsPointerRelease,
- () => {
- if (!agentsColumnPanelRef.current?.isCollapsed()) setAgentsShowingHold(false);
- },
- );
+ beginAgentsHandleDrag(event.pointerId);
}}
/>
<ResizablePanel
@@ -1772,7 +3129,7 @@ function EditorAreaInner({
panelRef={agentsColumnPanelRef}
defaultSize={agentsColumnPresent ? `${initialAgentsWidthPx}px` : 0}
minSize="0px"
- maxSize={agentsColumnPresent ? '95%' : '0px'}
+ maxSize={agentsColumnPresent ? (editorColumnHoldsPane ? '95%' : '100%') : '0px'}
collapsible
collapsedSize={0}
onResize={(size) => {
@@ -1785,30 +3142,46 @@ function EditorAreaInner({
reclaimHiddenRailColumn(AGENTS_COLUMN_ID, agentsColumnPresent, size.inPixels);
}}
className="flex flex-col"
+ style={{ overflow: 'visible' }}
>
- {}
- <div
- ref={setAgentsContainer}
- data-agents-panel-mount=""
- inert={!agentsColumnPresent || (agentsColumnCollapsed && !agentsShowingHold)}
- className="flex min-h-0 flex-1 flex-col overflow-hidden"
- />
+ <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>
</>
);
- if (coldStartSkeleton) return <EditorSkeleton />;
-
- const editorAbsorbsResidual =
- (docSlotPresent && !initialRightCollapsed) || resizableRailColumnPresent;
+ const railColumnMinSize = resizableRailColumnPresent ? '5%' : '30%';
+ const editorColumnMinSize = editorColumnHoldsPane ? railColumnMinSize : '0%';
+ const workspaceAbsorbsResidual = docSlotPresent && !initialRightCollapsed;
+ const outerRowDragging = isDraggingTerminalHandle || isDraggingAgentsHandle;
+ const workspaceHeaderTarget = (
+ <div
+ ref={setWorkspaceHeaderContainer}
+ data-editor-area-header=""
+ className={cn('relative z-30 shrink-0', (filesCover || docPanelCover) && 'invisible')}
+ />
+ );
return (
<div className="flex min-h-0 flex-1 flex-col">
- <div
- ref={setWorkspaceHeaderContainer}
- data-editor-area-header=""
- className="relative z-30 shrink-0"
- />
+ {noteWindow ? workspaceHeaderTarget : null}
<div
data-editor-area-panels=""
className="relative flex min-h-0 flex-1"
@@ -1820,37 +3193,200 @@ function EditorAreaInner({
<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);
}}
- data-dragging={
- isDraggingDocHandle || isDraggingTerminalHandle || isDraggingAgentsHandle || undefined
- }
+ data-dragging={outerRowDragging || undefined}
>
<ResizablePanel
- minSize={resizableRailColumnPresent ? '5%' : '30%'}
- {...(editorAbsorbsResidual ? {} : { defaultSize: '100%' })}
+ minSize={editorColumnMinSize}
+ {...(resizableRailColumnPresent ? {} : { defaultSize: '100%' })}
+ className="flex flex-col"
+ style={{
+ paddingInlineEnd: editorColumnChromePx,
+ overflow: editorVisible && editorCardPin == null ? 'visible' : 'hidden',
+ }}
>
- <div ref={setWorkspaceColumnEl} className="flex h-full min-w-0 flex-col">
- {leftColumn}
- </div>
+ <TerminalDock
+ ref={terminalDockRef}
+ editorVisible={editorVisible}
+ onBottomCollapsedChange={setBottomTerminalCollapsed}
+ placement={terminalPlacement}
+ visible={terminalVisible}
+ available={terminalAvailable}
+ variant={cardVariant}
+ onVisibleChange={onTerminalVisibleChange ?? (() => {})}
+ onBottomContainer={setBottomTerminalContainer}
+ >
+ <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' }
+ }
+ >
+ {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;
+ }}
+ >
+ <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 className="flex h-11 shrink-0 items-center gap-1 px-2">
+ <Button
+ ref={filesBackRef}
+ data-files-back=""
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t`Back to editor`}
+ title={t`Back to editor`}
+ onClick={() => dismissFilesCover()}
+ onKeyDown={(event) => {
+ if (event.key !== 'Escape' || isOverlayLayerOpen()) return;
+ event.preventDefault();
+ dismissFilesCover();
+ }}
+ >
+ <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">
+ {t`Files`}
+ </h2>
+ </div>
+ <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>
- {docSlot}
{terminalColumn}
{agentsColumn}
</ResizablePanelGroup>
- {rightRevealTabPresent ? (
- <TerminalRevealTab
- edge="right"
- onReveal={() => {
- if (agentsVisible && agentsColumnCollapsed) {
- assertRightRailLayout(isCollapsedRef.current);
- } else onRevealAgents();
- }}
- className="top-2.5 right-0"
- />
- ) : null}
+ {nothingOpen ? <NothingOpen /> : null}
</div>
+ {createPortal(docSlotContent, docPanelHost)}
</div>
);
}
diff --git a/packages/app/src/components/EditorFooter.checkout.dom.test.tsx b/packages/app/src/components/EditorFooter.checkout.dom.test.tsx
new file mode 100644
index 000000000..0b5ba69b6
--- /dev/null
+++ b/packages/app/src/components/EditorFooter.checkout.dom.test.tsx
@@ -0,0 +1,148 @@
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { DocumentStats } from '@/lib/document-stats';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
+ <>{value === 1 ? one : other}</>
+ ),
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+let branch: string | null = null;
+let worktreeModel: WorktreeSelectorModel | null = null;
+
+vi.doMock('@/hooks/use-current-branch', () => ({ useCurrentBranch: () => branch }));
+vi.doMock('@/hooks/use-worktrees', () => ({ useWorktrees: () => worktreeModel }));
+
+const STATS: DocumentStats = { words: 10, chars: 50, tokens: 12 };
+
+function model(currentWorktreePath: string): WorktreeSelectorModel {
+ return {
+ mainRoot: '/work/acme-notes',
+ currentBranch: null,
+ remoteBranches: [],
+ entries: [
+ {
+ branch: 'main',
+ worktreePath: '/work/acme-notes',
+ isCurrent: currentWorktreePath === '/work/acme-notes',
+ isMain: true,
+ locked: false,
+ },
+ {
+ branch: 'feat/new-layout',
+ worktreePath: '/work/acme-notes-feature',
+ isCurrent: currentWorktreePath === '/work/acme-notes-feature',
+ isMain: false,
+ locked: false,
+ },
+ {
+ branch: null,
+ worktreePath: '/work/acme-notes-review',
+ isCurrent: currentWorktreePath === '/work/acme-notes-review',
+ isMain: false,
+ locked: false,
+ },
+ ],
+ };
+}
+
+function installDesktopProject(projectName: string, projectPath: string) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { projectName, projectPath } },
+ });
+}
+
+async function renderFooter() {
+ const { EditorFooter } = await import('./EditorFooter');
+ return render(
+ <TooltipProvider delayDuration={0}>
+ <EditorFooter stats={STATS} />
+ </TooltipProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ branch = null;
+ worktreeModel = null;
+ Object.defineProperty(window, 'okDesktop', { configurable: true, value: undefined });
+});
+
+describe('EditorFooter checkout detail', () => {
+ test.each([
+ {
+ name: 'a nested project in a worktree on a branch',
+ projectName: 'docs',
+ projectPath: '/work/acme-notes-feature/docs',
+ checkout: '/work/acme-notes-feature',
+ currentBranch: 'feat/new-layout',
+ expected: 'docs · feat/new-layout',
+ },
+ {
+ name: 'a nested project in a worktree with no branch',
+ projectName: 'docs',
+ projectPath: '/work/acme-notes-review/docs',
+ checkout: '/work/acme-notes-review',
+ currentBranch: null,
+ expected: 'docs · acme-notes-review',
+ },
+ {
+ name: 'a project at the root of the original clone',
+ projectName: 'acme-notes',
+ projectPath: '/work/acme-notes',
+ checkout: '/work/acme-notes',
+ currentBranch: 'main',
+ expected: 'main',
+ },
+ {
+ name: 'a project at the root of a worktree',
+ projectName: 'acme-notes-feature',
+ projectPath: '/work/acme-notes-feature',
+ checkout: '/work/acme-notes-feature',
+ currentBranch: 'feat/new-layout',
+ expected: 'acme-notes-feature · feat/new-layout',
+ },
+ ])('shows what the project switcher used to show on its second line for $name', async (row) => {
+ installDesktopProject(row.projectName, row.projectPath);
+ branch = row.currentBranch;
+ worktreeModel = model(row.checkout);
+ await renderFooter();
+
+ expect(screen.getByTestId('editor-footer-branch').textContent).toBe(row.expected);
+ expect(screen.queryByText('acme-notes', { exact: true })).toBeNull();
+ });
+
+ test('keyboard focus on the checkout detail reveals the full project path', async () => {
+ installDesktopProject('docs', '/work/acme-notes-feature/docs');
+ branch = 'feat/new-layout';
+ worktreeModel = model('/work/acme-notes-feature');
+ await renderFooter();
+
+ const trigger = screen.getByTestId('editor-footer-checkout');
+ expect(trigger.tabIndex).toBe(0);
+ fireEvent.focus(trigger);
+ expect((await screen.findByRole('tooltip')).textContent).toContain(
+ '/work/acme-notes-feature/docs',
+ );
+ });
+
+ test('on the web, with no desktop project, the footer shows the branch alone and no path target', async () => {
+ branch = 'main';
+ await renderFooter();
+
+ expect(screen.getByTestId('editor-footer-branch').textContent).toBe('main');
+ expect(screen.queryByTestId('editor-footer-checkout')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/EditorFooter.dom.test.tsx b/packages/app/src/components/EditorFooter.dom.test.tsx
index bab59889d..099343f23 100644
--- a/packages/app/src/components/EditorFooter.dom.test.tsx
+++ b/packages/app/src/components/EditorFooter.dom.test.tsx
@@ -1,7 +1,9 @@
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';
+import { SidebarProvider } from '@/components/ui/sidebar';
+import { TooltipProvider } from '@/components/ui/tooltip';
import type { DocumentStats } from '@/lib/document-stats';
vi.doMock('@lingui/react/macro', () => ({
@@ -16,18 +18,88 @@ vi.doMock('@lingui/react/macro', () => ({
}),
}));
-vi.doMock('@/hooks/use-editor-footer-identity', () => ({
- useEditorFooterIdentity: () => null,
-}));
+const SERVER_BRANCH = 'feature/app-header';
+
+vi.stubGlobal('fetch', async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.endsWith('/api/server-info')) {
+ return Response.json({ serverInstanceId: 'server-1', currentBranch: SERVER_BRANCH });
+ }
+ if (url.endsWith('/api/workspace')) {
+ return Response.json({
+ contentDir: '/srv/field-notes',
+ pathSeparator: '/',
+ symlinkResolved: true,
+ });
+ }
+ return new Response(null, { status: 404 });
+});
+
+function installDesktopBridge() {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { projectName: 'Field Notes', projectPath: '/projects/field-notes' } },
+ });
+}
const STATS: DocumentStats = { words: 10, chars: 50, tokens: 12 };
async function renderFooter(composerBadge?: { onReopen: () => void } | null) {
const { EditorFooter } = await import('./EditorFooter');
- return render(<EditorFooter stats={STATS} composerBadge={composerBadge} />);
+ return render(
+ <TooltipProvider>
+ <EditorFooter stats={STATS} composerBadge={composerBadge} />
+ </TooltipProvider>,
+ );
+}
+
+async function renderFooterWithFileList(fileList: 'open' | 'closed') {
+ const { EditorFooter } = await import('./EditorFooter');
+ return render(
+ <SidebarProvider open={fileList === 'open'} onOpenChange={() => {}}>
+ <TooltipProvider>
+ <EditorFooter stats={STATS} />
+ </TooltipProvider>
+ </SidebarProvider>,
+ );
}
-afterEach(() => cleanup());
+afterEach(() => {
+ cleanup();
+ Object.defineProperty(window, 'okDesktop', { configurable: true, value: undefined });
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('EditorFooter identity row', () => {
+ test.each([
+ { host: 'desktop', fileList: 'open' },
+ { host: 'desktop', fileList: 'closed' },
+ { host: 'web', fileList: 'open' },
+ { host: 'web', fileList: 'closed' },
+ ] as const)(
+ 'shows the current branch and no project name on $host with the file list $fileList',
+ async ({ host, fileList }) => {
+ if (host === 'desktop') installDesktopBridge();
+ await renderFooterWithFileList(fileList);
+
+ const branch = await screen.findByTestId('editor-footer-branch');
+ expect(branch.textContent).toBe(SERVER_BRANCH);
+ expect(screen.queryByTestId('editor-footer-project-name')).toBeNull();
+ expect(screen.queryByText('Field Notes')).toBeNull();
+ },
+ );
+
+ test('shows the current branch with no file list in the tree at all, which is what note and single-file windows get', async () => {
+ installDesktopBridge();
+ await renderFooter();
+
+ const branch = await screen.findByTestId('editor-footer-branch');
+ expect(branch.textContent).toBe(SERVER_BRANCH);
+ });
+});
describe('EditorFooter (Ask AI reopen badge)', () => {
test('renders the Ask AI badge when composerBadge is set', async () => {
diff --git a/packages/app/src/components/EditorFooter.tsx b/packages/app/src/components/EditorFooter.tsx
index c0a0a5d1f..83258e3a5 100644
--- a/packages/app/src/components/EditorFooter.tsx
+++ b/packages/app/src/components/EditorFooter.tsx
@@ -2,11 +2,10 @@ import { Plural, useLingui } from '@lingui/react/macro';
import { ChevronUp, GitBranch, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import {
- type EditorFooterIdentity,
- useEditorFooterIdentity,
-} from '@/hooks/use-editor-footer-identity';
+import { useCurrentBranch } from '@/hooks/use-current-branch';
+import { useWorktrees } from '@/hooks/use-worktrees';
import type { DocumentStats } from '@/lib/document-stats';
+import { checkoutIdentity } from './checkout-identity';
interface EditorFooterProps {
stats: DocumentStats;
@@ -22,8 +21,16 @@ export function EditorFooter({
composerBadge,
}: EditorFooterProps) {
const { t } = useLingui();
- const identity = useEditorFooterIdentity();
- if (!showStats && identity === null && composerBadge == null) return null;
+ const branch = useCurrentBranch();
+ const worktreeModel = useWorktrees();
+ const desktopConfig = typeof window !== 'undefined' ? window.okDesktop?.config : undefined;
+ const { checkoutDetail } = checkoutIdentity({
+ projectName: desktopConfig?.projectName ?? null,
+ branch,
+ worktreeModel,
+ });
+ const projectPath = desktopConfig?.projectPath ?? null;
+ if (!showStats && checkoutDetail === null && composerBadge == null) return null;
const active = selectionStats ?? stats;
const isSelection = selectionStats != null;
const { words, chars, tokens } = active;
@@ -57,7 +64,9 @@ export function EditorFooter({
</Button>
) : null}
<span className="flex min-w-0 items-center gap-3">
- {identity !== null ? <IdentityRow identity={identity} /> : null}
+ {checkoutDetail !== null ? (
+ <CheckoutDetail detail={checkoutDetail} projectPath={projectPath} />
+ ) : null}
</span>
{showStats ? (
<span className="flex shrink-0 items-center gap-3">
@@ -88,35 +97,25 @@ export function EditorFooter({
);
}
-function IdentityRow({ identity }: { identity: EditorFooterIdentity }) {
- const { projectName, projectPath, branch } = identity;
+function CheckoutDetail({ detail, projectPath }: { detail: string; projectPath: string | null }) {
+ const row = (
+ <span className="flex min-w-0 items-center gap-1" data-testid="editor-footer-branch">
+ <GitBranch aria-hidden="true" className="size-3 shrink-0" />
+ <span className="truncate">{detail}</span>
+ </span>
+ );
+ if (projectPath === null) return row;
return (
- <>
- {projectName !== null ? (
- projectPath ? (
- <Tooltip>
- <TooltipTrigger asChild>
- {/* biome-ignore lint/a11y/noNoninteractiveTabindex: tooltip-on-static-text pattern — focusable span lets keyboard users surface the full project path that mouse users see on hover. */}
- <span tabIndex={0} className="truncate" data-testid="editor-footer-project-name">
- {projectName}
- </span>
- </TooltipTrigger>
- <TooltipContent side="top" className="max-w-xs break-all">
- {projectPath}
- </TooltipContent>
- </Tooltip>
- ) : (
- <span className="truncate" data-testid="editor-footer-project-name">
- {projectName}
- </span>
- )
- ) : null}
- {branch !== null ? (
- <span className="flex min-w-0 items-center gap-1" data-testid="editor-footer-branch">
- <GitBranch aria-hidden="true" className="size-3 shrink-0" />
- <span className="truncate">{branch}</span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* biome-ignore lint/a11y/noNoninteractiveTabindex: tooltip-on-static-text pattern — focusable span lets keyboard users surface the full project path that mouse users see on hover. */}
+ <span tabIndex={0} className="flex min-w-0" data-testid="editor-footer-checkout">
+ {row}
</span>
- ) : null}
- </>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-xs break-all">
+ {projectPath}
+ </TooltipContent>
+ </Tooltip>
);
}
diff --git a/packages/app/src/components/EditorHeader.dom.test.tsx b/packages/app/src/components/EditorHeader.dom.test.tsx
index 78b3683ca..c2a4d8ed1 100644
--- a/packages/app/src/components/EditorHeader.dom.test.tsx
+++ b/packages/app/src/components/EditorHeader.dom.test.tsx
@@ -1,21 +1,27 @@
+import { REDUCED_CHROME_HEADER_HEIGHT } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
+import { act, cleanup, render, screen } from '@testing-library/react';
import { type ComponentProps, type ReactNode, useEffect } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
-import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import { ConfigContext } from '@/lib/config-context';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibility,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
+import {
+ configContextWithTerminal,
+ type ProjectTerminalSetting,
+ TERMINAL_SETTING_UNSET,
+} from '@/test-utils/config-context';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-import {
- captureResizeObserver,
- type HeaderMetrics,
- mockHeaderMetrics,
-} from './EditorHeader.layout.test-helper';
+import { mockHeaderMetrics } from './EditorHeader.layout.test-helper';
vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
@@ -27,21 +33,16 @@ vi.doMock('@lingui/react/macro', () => ({
}));
let activeDocName: string | null = 'docs/notes';
-let activeTarget: unknown = { kind: 'doc' };
let sidebarState: 'expanded' | 'collapsed' = 'expanded';
-let paneCount = 1;
let singleFile = false;
-let lastShareInput: unknown;
let gitSyncStatus: Partial<GitSyncStatus> | null = null;
const syncToastsHookCalls: unknown[][] = [];
const syncToastsHosts = { mounted: 0 };
-const onOpenSearch = vi.fn(() => {});
+const gitSyncStatusReads = { count: 0 };
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName,
- activeTarget,
- panes: Array.from({ length: paneCount }, (_, index) => ({ id: `pane-${index}` })),
}),
}));
@@ -62,30 +63,16 @@ vi.doMock('@/components/AppMenubar', () => ({
AppMenubar: () => <div data-testid="app-menubar" />,
}));
-vi.doMock('./ShareButton', () => ({
- ShareButton: ({ input }: { input: unknown }) => {
- lastShareInput = input;
- return (
- <button type="button" disabled={input === null}>
- Share
- </button>
- );
- },
-}));
-
-vi.doMock('./PublishToGitHubDialog', () => ({
- PublishToGitHubDialog: ({ open }: { open: boolean }) => (
- <div data-testid="publish-dialog" data-open={String(open)} />
- ),
-}));
-
vi.doMock('./SyncStatusBadge', async () => ({
...(await vi.importActual<typeof import('./SyncStatusBadge')>('./SyncStatusBadge')),
SyncStatusBadge: () => <div data-testid="sync-status-badge" />,
}));
vi.doMock('@/hooks/use-git-sync-status', () => ({
- useGitSyncStatusDetailed: () => ({ status: gitSyncStatus, fetchError: null }),
+ useGitSyncStatusDetailed: () => {
+ gitSyncStatusReads.count += 1;
+ return { status: gitSyncStatus, fetchError: null };
+ },
useGitSyncStatus: () => gitSyncStatus,
}));
@@ -109,10 +96,6 @@ vi.doMock('./BetaBadge', () => ({
BetaBadge: () => <div data-testid="beta-badge" />,
}));
-vi.doMock('./SettingsButton', () => ({
- SettingsButton: () => <button type="button">Settings</button>,
-}));
-
vi.doMock('./HelpPopover', () => ({
HelpPopover: () => <button type="button">Resources</button>,
}));
@@ -144,50 +127,46 @@ function setNoteHost() {
});
}
-let rerenderHeader: ((tabs?: ReactNode) => void) | null = null;
+let projectTerminal: ProjectTerminalSetting = TERMINAL_SETTING_UNSET;
+
+const PANE_HIDDEN: PaneVisibility = { open: false, onScreen: false };
+const PANE_SHOWN: PaneVisibility = { open: true, onScreen: true };
+
+function publishPanes({ terminal = true }: { terminal?: boolean } = {}) {
+ act(() => {
+ paneVisibilityStore.publish({
+ editor: null,
+ agents: PANE_SHOWN,
+ terminal: terminal ? PANE_HIDDEN : null,
+ });
+ });
+}
async function renderHeader(tabs?: ReactNode) {
const { EditorHeader } = await import('./EditorHeader');
const tree = (nextTabs?: ReactNode) => (
- <TooltipProvider delayDuration={0}>
- <EditorHeader onOpenSearch={onOpenSearch}>{nextTabs}</EditorHeader>
- </TooltipProvider>
+ <ConfigContext value={configContextWithTerminal(projectTerminal)}>
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader>{nextTabs}</EditorHeader>
+ </TooltipProvider>
+ </ConfigContext>
);
- const view = render(tree(tabs));
- rerenderHeader = (nextTabs?: ReactNode) => {
- act(() => {
- view.rerender(tree(nextTabs));
- });
- };
+ render(tree(tabs));
return document.querySelector('header') as HTMLElement;
}
async function renderMeasuredHeader() {
- const header = await renderHeader(<div>tabs</div>);
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
- await waitFor(() => expectVisualClassTokensAbsent(tabHost.className, ['invisible']));
- return header;
+ return await renderHeader(<div>tabs</div>);
}
-async function renderHeaderAwaitingTabSuppression() {
- const header = await renderHeader(<div>tabs</div>);
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
- await waitFor(() =>
- expect(tabHost.getAttribute('data-editor-header-tabs-suppressed')).not.toBeNull(),
- );
- return header;
-}
+const RESERVATION_PROPERTIES = [
+ '--editor-header-leading-width',
+ '--editor-header-trailing-width',
+ '--editor-header-leading-offset',
+] as const;
-async function trailingRailCollapses(state: 'expanded' | 'collapsed', metrics: HeaderMetrics) {
- sidebarState = state;
- const restoreMetrics = mockHeaderMetrics(metrics);
- try {
- await renderMeasuredHeader();
- return screen.queryByRole('button', { name: 'More actions' }) !== null;
- } finally {
- restoreMetrics();
- cleanup();
- }
+function reservationsOn(header: HTMLElement) {
+ return RESERVATION_PROPERTIES.map((property) => header.style.getPropertyValue(property));
}
describe('EditorHeader runtime behavior', () => {
@@ -195,16 +174,14 @@ describe('EditorHeader runtime behavior', () => {
cleanup();
setElectronHost(false);
activeDocName = 'docs/notes';
- activeTarget = { kind: 'doc' };
sidebarState = 'expanded';
- paneCount = 1;
singleFile = false;
- lastShareInput = undefined;
gitSyncStatus = null;
syncToastsHookCalls.length = 0;
syncToastsHosts.mounted = 0;
- rerenderHeader = null;
- onOpenSearch.mockClear();
+ gitSyncStatusReads.count = 0;
+ projectTerminal = TERMINAL_SETTING_UNSET;
+ __resetPaneVisibilityStoreForTests();
});
test('exports the EditorHeader component', async () => {
@@ -212,7 +189,40 @@ describe('EditorHeader runtime behavior', () => {
expect(typeof mod.EditorHeader).toBe('function');
});
- test('web host keeps baseline header layout without Electron drag treatment', async () => {
+ test('a single-file editor card owns document identity and its information control', async () => {
+ setElectronHost(true);
+ singleFile = true;
+ const { EditorHeader } = await import('./EditorHeader');
+ render(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader trailing={<button type="button">Show document information</button>} />
+ </TooltipProvider>,
+ );
+
+ const header = document.querySelector('[data-editor-header]') as HTMLElement;
+ const tabs = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
+ const trailing = header.querySelector('[data-editor-header-trailing]') as HTMLElement;
+ expect(tabs.textContent).toContain('docs');
+ expect(tabs.textContent).toContain('notes');
+ expect(
+ trailing.contains(screen.getByRole('button', { name: 'Show document information' })),
+ ).toBe(true);
+ expect(header.querySelector('[data-editor-header-actions]')).toBeNull();
+ expect(header.querySelector('[data-editor-header-leading-actions]')).toBeNull();
+ expect(header.querySelector('[data-testid="header-pane-buttons"]')).toBeNull();
+ expectVisualClassTokens(header.className, ['h-11']);
+ });
+
+ test('a note window alone keeps its reduced titlebar height', async () => {
+ setNoteHost();
+ const header = await renderHeader();
+ expectVisualClassTokens(header.className, ['h-[var(--ok-reduced-chrome-header-height)]']);
+ expect(header.style.getPropertyValue('--ok-reduced-chrome-header-height')).toBe(
+ REDUCED_CHROME_HEADER_HEIGHT,
+ );
+ });
+
+ test('a web project window tab row is a plain 44px row without window-drag treatment', async () => {
setElectronHost(false);
sidebarState = 'collapsed';
const header = await renderHeader();
@@ -220,179 +230,75 @@ describe('EditorHeader runtime behavior', () => {
expect(header.getAttribute('data-electron-drag')).toBeNull();
expectVisualClassTokens(header.className, [
'flex',
- 'h-12',
+ 'h-11',
'shrink-0',
'items-center',
'bg-background',
- 'shadow-[inset_0_-1px_0_var(--border)]',
]);
expectVisualClassTokensAbsent(header.className, [
+ 'shadow-[inset_0_-1px_0_var(--border)]',
+ 'h-[var(--ok-reduced-chrome-header-height)]',
'[-webkit-app-region:drag]',
'pl-[var(--ok-titlebar-reserve-left,1rem)]',
]);
- expectVisualClassTokensAbsent(screen.getByTestId('sidebar-trigger').className, [
- '[-webkit-app-region:no-drag]',
- ]);
expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
});
- test('renders the expanded Files shortcut as a Kbd keycap', async () => {
- const user = userEvent.setup();
- await renderHeader();
-
- await user.hover(screen.getByTestId('sidebar-trigger'));
- const tooltip = await screen.findByRole('tooltip', {
- name: `Hide Files ${formatShortcutLabel('toggle-files-sidebar')}`,
- });
- expect(tooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(
- formatShortcut('toggle-files-sidebar'),
- );
- });
-
- test('renders collapsed Files and Search shortcuts as Kbd keycaps with spoken button text', async () => {
- const user = userEvent.setup();
- sidebarState = 'collapsed';
- await renderHeader();
+ for (const state of ['expanded', 'collapsed'] as const) {
+ test(`an Electron project window tab row with the file list ${state} is a drag region holding only the tab strip`, async () => {
+ setElectronHost(true);
+ sidebarState = state;
+ const header = await renderHeader(<div data-testid="editor-tabs">tabs</div>);
+ const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
- const filesButton = screen.getByTestId('sidebar-trigger');
- await user.hover(filesButton);
- const filesTooltip = await screen.findByRole('tooltip', {
- name: `Show Files ${formatShortcutLabel('toggle-files-sidebar')}`,
+ expect(header.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(header.className, ['h-11', '[-webkit-app-region:drag]']);
+ expect(tabHost.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(tabHost.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokensAbsent(tabHost.className, ['[-webkit-app-region:no-drag]']);
+ expect(Array.from(header.children)).toEqual([tabHost]);
+ expect(tabHost.contains(screen.getByTestId('editor-tabs'))).toBe(true);
+ expect(header.querySelector('[data-editor-header-leading-actions]')).toBeNull();
+ expect(header.querySelector('[data-editor-header-actions]')).toBeNull();
+ expect(
+ screen.queryByTestId('sidebar-trigger'),
+ 'the file list toggle rides in the first pane tab strip, not in header chrome laid over it',
+ ).toBeNull();
+ expect(screen.queryByRole('group', { name: 'Workspace navigation' })).toBeNull();
+ expect(screen.queryByRole('button', { name: /^Search/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Back' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Forward' })).toBeNull();
+ expect(reservationsOn(header)).toEqual(['', '', '']);
});
- expect(filesTooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(
- formatShortcut('toggle-files-sidebar'),
- );
- cleanup();
- await renderHeader();
+ }
- const searchButton = screen.getByRole('button', {
- name: `Search (${formatShortcutLabel('command-palette')})`,
- });
- await user.hover(searchButton);
- const searchTooltip = await screen.findByRole('tooltip', {
- name: `Search ${formatShortcutLabel('command-palette')}`,
+ test('no window kind publishes leading or trailing width reservations for the tab strip', async () => {
+ const restoreMetrics = mockHeaderMetrics({
+ header: 1_000,
+ leading: 224,
+ leadingOffset: 78,
+ trailing: 300,
});
- expect(searchTooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(
- formatShortcut('command-palette'),
- );
- expect(searchButton).not.toBeNull();
- });
-
- test('Electron collapsed-sidebar host groups workspace navigation without a Search-to-Back separator', async () => {
- setElectronHost(true);
- sidebarState = 'collapsed';
- const header = await renderHeader();
- const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
-
- expect(header.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(header.className, ['[-webkit-app-region:drag]']);
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
- expect(tabHost.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(tabHost.className, ['[-webkit-app-region:drag]']);
- expectVisualClassTokensAbsent(tabHost.className, ['[-webkit-app-region:no-drag]']);
- expect(leadingZone.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(leadingZone.className, ['[-webkit-app-region:drag]']);
- expectVisualClassTokens(leadingZone.className, ['left-[var(--ok-titlebar-reserve-left,1rem)]']);
- expectVisualClassTokensAbsent(leadingZone.className, ['motion-safe:transition-[left]']);
- expectVisualClassTokens(screen.getByTestId('sidebar-trigger').className, [
- '[-webkit-app-region:no-drag]',
- ]);
- const workspaceNavigation = screen.getByRole('group', { name: 'Workspace navigation' });
- const search = screen.getByRole('button', { name: /^Search/ });
- const navigation = screen.getByTestId('navigation-history-controls');
- const separator = leadingZone.querySelector('[data-slot="separator"]') as HTMLElement;
- expect(workspaceNavigation.contains(screen.getByTestId('sidebar-trigger'))).toBe(true);
- expect(workspaceNavigation.contains(search)).toBe(true);
- expect(workspaceNavigation.contains(navigation)).toBe(true);
- expect(workspaceNavigation.querySelector('[data-slot="button-group-separator"]')).toBeNull();
- expect(screen.getAllByRole('button', { name: 'Back' })).toHaveLength(1);
- expect(screen.getAllByRole('button', { name: 'Forward' })).toHaveLength(1);
- expect(
- search.compareDocumentPosition(navigation) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(
- navigation.compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expectVisualClassTokensAbsent(navigation.className, ['[-webkit-app-region:no-drag]']);
- const rightZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
- expect(rightZone.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(rightZone.className, [
- '[-webkit-app-region:drag]',
- '[&_button]:[-webkit-app-region:no-drag]',
- '[&_a]:[-webkit-app-region:no-drag]',
- ]);
- expectVisualClassTokensAbsent(rightZone.className, ['*:[-webkit-app-region:no-drag]']);
- expect(
- tabHost.compareDocumentPosition(leadingZone) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(
- tabHost.compareDocumentPosition(rightZone) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- });
-
- test('Electron host keeps the build label hoverable inside the draggable trailing rail', async () => {
- setElectronHost(true);
- const header = await renderHeader();
- const rightZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
- const badge = screen.getByTestId('instance-badge');
-
- expect(rightZone.contains(badge)).toBe(true);
- expectVisualClassTokens(rightZone.className, ['[-webkit-app-region:drag]']);
- expectVisualClassTokens(badge.className, ['[-webkit-app-region:no-drag]']);
- });
-
- test('web host leaves the build label without Electron drag treatment', async () => {
- setElectronHost(false);
- await renderHeader();
- expectVisualClassTokensAbsent(screen.getByTestId('instance-badge').className, [
- '[-webkit-app-region:no-drag]',
- ]);
- });
-
- test('Electron expanded sidebar keeps drag region but does not reserve traffic-light space', async () => {
- setElectronHost(true);
- sidebarState = 'expanded';
- const header = await renderHeader();
- const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
-
- expectVisualClassTokens(header.className, ['[-webkit-app-region:drag]']);
- expectVisualClassTokensAbsent(leadingZone.className, [
- 'left-[var(--ok-titlebar-reserve-left,1rem)]',
- ]);
- expect(header.style.getPropertyValue('--editor-header-leading-offset')).toBe('0px');
- expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
- });
-
- test('keeps the sidebar offset separate from the measured leading action width', async () => {
- setElectronHost(true);
- sidebarState = 'collapsed';
- const offsetWidth = vi
- .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
- .mockImplementation(function (this: HTMLElement) {
- if (this.hasAttribute('data-editor-header-leading-actions')) return 224;
- if (this.hasAttribute('data-editor-header-actions')) return 160;
- return 0;
- });
-
try {
- const header = await renderHeader(<div>tabs</div>);
-
- expect(header.style.getPropertyValue('--editor-header-leading-width')).toBe('224px');
- expect(header.style.getPropertyValue('--editor-header-leading-offset')).toBe(
- 'var(--ok-titlebar-reserve-left, 1rem)',
- );
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
- await waitFor(() => expectVisualClassTokensAbsent(tabHost.className, ['invisible']));
+ for (const kind of ['project', 'single-file'] as const) {
+ setElectronHost(true);
+ sidebarState = 'collapsed';
+ singleFile = kind === 'single-file';
+ const header = await renderHeader(<div>tabs</div>);
+
+ expect(reservationsOn(header), `${kind} window`).toEqual(['', '', '']);
+ cleanup();
+ }
} finally {
- offsetWidth.mockRestore();
+ restoreMetrics();
}
});
- test('keeps tabs hidden on the first render until header chrome is measured', async () => {
+ test('tabs paint on the first render, with no header chrome to measure first', async () => {
const { EditorHeader } = await import('./EditorHeader');
const markup = renderToStaticMarkup(
<TooltipProvider delayDuration={0}>
- <EditorHeader onOpenSearch={onOpenSearch}>
+ <EditorHeader>
<div>restored tabs</div>
</EditorHeader>
</TooltipProvider>,
@@ -401,146 +307,66 @@ describe('EditorHeader runtime behavior', () => {
container.innerHTML = markup;
const tabHost = container.querySelector('[data-editor-header-tabs]') as HTMLElement;
- expectVisualClassTokens(tabHost.className, ['invisible']);
+ expectVisualClassTokensAbsent(tabHost.className, ['invisible']);
+ expect(tabHost.hasAttribute('data-editor-header-tabs-suppressed')).toBe(false);
});
- test('keeps restored tabs hidden until two settled layout frames have passed', async () => {
- const frames: FrameRequestCallback[] = [];
- const requestFrame = vi
- .spyOn(window, 'requestAnimationFrame')
- .mockImplementation((callback) => {
- frames.push(callback);
- return frames.length;
- });
- const cancelFrame = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});
-
- try {
- const header = await renderHeader(<div>restored tabs</div>);
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
+ test('the tab strip is bounded by the editor column width, not padded around header chrome', async () => {
+ const header = await renderHeader(<div>tabs</div>);
+ const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
- expectVisualClassTokens(tabHost.className, ['invisible']);
- act(() => frames.shift()?.(0));
- expectVisualClassTokens(tabHost.className, ['invisible']);
- act(() => frames.shift()?.(16));
- expectVisualClassTokensAbsent(tabHost.className, ['invisible']);
- } finally {
- requestFrame.mockRestore();
- cancelFrame.mockRestore();
- }
+ expectVisualClassTokens(tabHost.className, [
+ 'w-[var(--editor-header-tabs-width,100%)]',
+ 'min-w-0',
+ 'overflow-hidden',
+ ]);
+ expectVisualClassTokensAbsent(tabHost.className, ['absolute', 'invisible']);
});
- test('reserves only the header actions that overlap the editor-width tab strip', async () => {
- const offsetWidth = vi
- .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
- .mockImplementation(function (this: HTMLElement) {
- if (this.tagName === 'HEADER') return 1_000;
- if (this.hasAttribute('data-editor-header-tabs')) return 800;
- if (this.hasAttribute('data-editor-header-actions')) return 300;
- if (this.hasAttribute('data-editor-header-leading-actions')) return 100;
- return 0;
- });
+ test('a Windows project window leaves the app menu to the app header', async () => {
+ setWindowsHost();
+ const header = await renderHeader();
- try {
- const header = await renderHeader(<div>tabs</div>);
- expect(header.style.getPropertyValue('--editor-header-trailing-width')).toBe('100px');
- } finally {
- offsetWidth.mockRestore();
- }
+ await act(async () => {});
+ expect(screen.queryByTestId('app-menubar')).toBeNull();
+ expect(header.querySelector('[data-editor-header-leading-actions]')).toBeNull();
});
-
- test('includes the WCO reserve margin in the trailing tab-strip width', async () => {
- const offsetWidth = vi
- .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
- .mockImplementation(function (this: HTMLElement) {
- if (this.tagName === 'HEADER') return 1_000;
- if (this.hasAttribute('data-editor-header-tabs')) return 800;
- if (this.hasAttribute('data-editor-header-actions')) return 300;
- if (this.hasAttribute('data-editor-header-leading-actions')) return 100;
- return 0;
- });
- const realGetComputedStyle = window.getComputedStyle.bind(window);
- const computedStyle = vi
- .spyOn(window, 'getComputedStyle')
- .mockImplementation((element: Element, pseudo?: string | null) => {
- const style = realGetComputedStyle(element, pseudo);
- if (element instanceof HTMLElement && element.hasAttribute('data-editor-header-actions')) {
- return new Proxy(style, {
- get: (target, property) =>
- property === 'marginRight' ? '137px' : Reflect.get(target, property),
- }) as CSSStyleDeclaration;
- }
- return style;
- });
-
+ test('a project window tab row carries none of the header actions, which moved to the app header', async () => {
+ gitSyncStatus = { state: 'idle', conflictCount: 2, hasRemote: true };
+ const restoreMetrics = mockHeaderMetrics({ header: 107, leading: 57, trailing: 218 });
try {
- const header = await renderHeader(<div>tabs</div>);
- expect(header.style.getPropertyValue('--editor-header-trailing-width')).toBe('237px');
+ for (const state of ['expanded', 'collapsed'] as const) {
+ sidebarState = state;
+ const header = await renderMeasuredHeader();
+
+ expect(header.querySelector('[data-editor-header-actions]')).toBeNull();
+ expect(screen.queryByTestId('presence-bar')).toBeNull();
+ expect(screen.queryByRole('button', { name: /^Share/ })).toBeNull();
+ expect(screen.queryByTestId('sync-status-badge')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Settings' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Resources' })).toBeNull();
+ expect(screen.queryByTestId('beta-badge')).toBeNull();
+ expect(screen.queryByTestId('instance-badge')).toBeNull();
+ expect(screen.queryByTestId('header-overflow-actions-trigger')).toBeNull();
+ expect(syncToastsHosts.mounted).toBe(0);
+ expect(reservationsOn(header)).toEqual(['', '', '']);
+ cleanup();
+ }
} finally {
- computedStyle.mockRestore();
- offsetWidth.mockRestore();
+ restoreMetrics();
}
});
- test('keeps sidebar chrome movement immediate after a post-mount state change', async () => {
- setElectronHost(true);
- sidebarState = 'collapsed';
- const { EditorHeader } = await import('./EditorHeader');
- const headerUi = () => (
- <TooltipProvider delayDuration={0}>
- <EditorHeader onOpenSearch={onOpenSearch}>
- <div>restored tabs</div>
- </EditorHeader>
- </TooltipProvider>
- );
- const view = render(headerUi());
- const header = document.querySelector('header') as HTMLElement;
-
- const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
- expectVisualClassTokens(leadingZone.className, ['left-[var(--ok-titlebar-reserve-left,1rem)]']);
- expectVisualClassTokensAbsent(leadingZone.className, ['motion-safe:transition-[left]']);
-
- sidebarState = 'expanded';
- view.rerender(headerUi());
-
- expectVisualClassTokensAbsent(leadingZone.className, [
- 'left-[var(--ok-titlebar-reserve-left,1rem)]',
- 'motion-safe:transition-[left]',
- ]);
- });
-
- test('Windows places Hide Files before the File menu', async () => {
- setWindowsHost();
- const header = await renderHeader();
-
- const files = screen.getByTestId('sidebar-trigger');
- const menubar = await screen.findByTestId('app-menubar');
- const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
- const separator = leadingZone.querySelector('[data-slot="separator"]') as HTMLElement;
-
- expect(files.compareDocumentPosition(menubar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- expect(
- menubar.compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- });
+ test('document card headers leave sync status to the shared header', async () => {
+ gitSyncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
- test('Windows single-file mode keeps the menubar without project chrome', async () => {
- setWindowsHost();
- singleFile = true;
await renderHeader();
+ expect(gitSyncStatusReads.count).toBe(0);
- expect(await screen.findByTestId('app-menubar')).toBeTruthy();
- expect(screen.queryByTestId('sidebar-trigger')).toBeNull();
- });
-
- test('single-file mode omits collapsed navigation history with the rest of project chrome', async () => {
- setElectronHost(true);
- sidebarState = 'collapsed';
+ cleanup();
singleFile = true;
await renderHeader();
-
- expect(screen.queryByTestId('sidebar-trigger')).toBeNull();
- expect(screen.queryByRole('button', { name: /^Search/ })).toBeNull();
- expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
+ expect(gitSyncStatusReads.count).toBe(0);
});
test('note windows put document context in the titlebar without Resources or sync chrome', async () => {
@@ -550,9 +376,11 @@ describe('EditorHeader runtime behavior', () => {
try {
const { EditorHeader } = await import('./EditorHeader');
render(
- <TooltipProvider delayDuration={0}>
- <EditorHeader noteModeToggle={<button type="button">mode switch</button>} />
- </TooltipProvider>,
+ <ConfigContext value={configContextWithTerminal(projectTerminal)}>
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader noteModeToggle={<button type="button">mode switch</button>} />
+ </TooltipProvider>
+ </ConfigContext>,
);
const leadingZone = document.querySelector(
@@ -587,12 +415,41 @@ describe('EditorHeader runtime behavior', () => {
screen.queryByRole('button', { name: 'More actions' }),
'a note window has no trailing actions to collapse, so a cramped header must not grow an overflow trigger',
).toBeNull();
- expect(document.querySelector('[data-editor-header-overflow-actions]')).toBeNull();
+ expect(document.querySelector('[data-header-overflow-actions]')).toBeNull();
} finally {
restoreMetrics();
}
});
+ test('a note window has no chat or terminal, so it shows no Agents or Terminal buttons even when panes are published', async () => {
+ setNoteHost();
+ publishPanes();
+ const { EditorHeader } = await import('./EditorHeader');
+ render(
+ <ConfigContext value={configContextWithTerminal(projectTerminal)}>
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader />
+ </TooltipProvider>
+ </ConfigContext>,
+ );
+
+ expect(document.querySelector('[data-editor-header-actions]')).not.toBeNull();
+ expect(screen.queryByRole('group', { name: 'Panels' })).toBeNull();
+ expect(screen.queryByTestId('header-pane-divider')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Agents' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Terminal' })).toBeNull();
+ });
+
+ test('a project window tab row leaves the Agents and Terminal buttons to the app header', async () => {
+ publishPanes();
+ const header = await renderHeader(<div>tabs</div>);
+
+ expect(header.querySelector('[data-testid="header-pane-buttons"]')).toBeNull();
+ expect(screen.queryByRole('group', { name: 'Panels' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Agents' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Terminal' })).toBeNull();
+ });
+
test('renders workspace tabs between the global action zones', async () => {
await renderHeader(<div data-testid="editor-tabs">tabs</div>);
@@ -603,373 +460,82 @@ describe('EditorHeader runtime behavior', () => {
expect(screen.queryByText('assetFileName')).toBeNull();
});
- test('keeps the existing action-zone styling when workspace tabs share the header', async () => {
- const header = await renderHeader(<div data-testid="editor-tabs">tabs</div>);
- const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
- const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
-
- expectVisualClassTokensAbsent(leadingZone.className, ['bg-muted/95']);
- expectVisualClassTokensAbsent(trailingZone.className, ['bg-muted/95']);
- });
-
- test('keeps header actions inline with multiple editor panes', async () => {
- paneCount = 3;
- const header = await renderHeader();
- const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
-
- expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
- expect(trailingZone.contains(screen.getByRole('button', { name: 'Share' }))).toBe(true);
- expect(trailingZone.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true);
- expect(trailingZone.contains(screen.getByRole('button', { name: 'Resources' }))).toBe(true);
- expect(document.querySelector('[data-editor-header-overflow-actions]')).toBeNull();
- });
-
- test('collapses the trailing rail when its expanded width exceeds the available header space', async () => {
- const restoreMetrics = mockHeaderMetrics({ header: 107, leading: 57, trailing: 218 });
-
- try {
- const header = await renderMeasuredHeader();
- const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
- const overflowTrigger = screen.getByRole('button', { name: 'More actions' });
-
- expect(trailingZone.contains(overflowTrigger)).toBe(true);
- expect(
- trailingZone.querySelector('[data-testid="sync-status-badge"]'),
- 'the badge moves behind the overflow trigger instead of staying inline',
- ).toBeNull();
- expect(
- trailingZone.querySelector('[data-testid="presence-bar"]'),
- 'the presence bar moves behind the overflow trigger instead of staying inline',
- ).toBeNull();
- expect(
- syncToastsHosts.mounted,
- 'moving the visible sync surfaces behind the trigger must not take the sync-toast machine with them',
- ).toBe(1);
- expect(
- window.innerWidth,
- 'the jsdom viewport stays roomy, so a collapse here cannot be viewport-driven',
- ).toBeGreaterThan(500);
- } finally {
- restoreMetrics();
- }
- });
-
- test('keeps the sync-toast machine mounted outside the collapsible trailing rail', async () => {
- const restoreMetrics = mockHeaderMetrics({ header: 107, leading: 57, trailing: 218 });
-
- try {
- await renderMeasuredHeader();
-
- expect(screen.getByRole('button', { name: 'More actions' })).toBeTruthy();
- expect(
- screen.queryByTestId('presence-bar'),
- 'the presence bar sits behind a closed popover here, so it cannot be the hook host',
- ).toBeNull();
- expect(
- syncToastsHosts.mounted,
- 'useSyncToasts must run from a host that the collapse cannot unmount',
- ).toBe(1);
- expect(syncToastsHookCalls.at(-1)?.[1]).toBe('docs/notes');
- } finally {
- restoreMetrics();
- }
- });
-
- test('opening the overflow menu reveals every action the collapse took out of the rail', async () => {
- const user = userEvent.setup();
- const restoreMetrics = mockHeaderMetrics({ header: 107, leading: 57, trailing: 218 });
-
- try {
- await renderMeasuredHeader();
- await user.click(screen.getByTestId('header-overflow-actions-trigger'));
-
- const panel = await waitFor(() => {
- const found = document.querySelector('[data-editor-header-overflow-actions]');
- expect(found, 'the overflow trigger must open a panel').not.toBeNull();
- return found as HTMLElement;
- });
- expect(panel.contains(screen.getByRole('button', { name: 'Share' }))).toBe(true);
- expect(panel.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true);
- expect(panel.contains(screen.getByRole('button', { name: 'Resources' }))).toBe(true);
- expect(panel.querySelector('[data-testid="sync-status-badge"]')).not.toBeNull();
- expect(panel.querySelector('[data-testid="presence-bar"]')).not.toBeNull();
- } finally {
- restoreMetrics();
- }
- });
-
- test('mirrors an unresolved sync state onto the collapsed overflow trigger', async () => {
- gitSyncStatus = { state: 'idle', conflictCount: 2, hasRemote: true };
- const restoreMetrics = mockHeaderMetrics({ header: 107, leading: 57, trailing: 218 });
-
- try {
- await renderMeasuredHeader();
- const trigger = screen.getByTestId('header-overflow-actions-trigger');
-
- expect(
- trigger.getAttribute('aria-label'),
- 'collapsing the sync badge must not leave the trigger claiming there is nothing to see',
- ).toBe('More actions (Conflict)');
- expect(
- trigger
- .querySelector('[data-testid="header-overflow-actions-sync-indicator"]')
- ?.getAttribute('data-sync-attention'),
- ).toBe('conflict');
- } finally {
- restoreMetrics();
- }
- });
-
- test('leaves the collapsed overflow trigger unadorned while sync is healthy', async () => {
- gitSyncStatus = { state: 'idle', conflictCount: 0, hasRemote: true };
- const restoreMetrics = mockHeaderMetrics({ header: 107, leading: 57, trailing: 218 });
-
- try {
- await renderMeasuredHeader();
- const trigger = screen.getByTestId('header-overflow-actions-trigger');
-
- expect(trigger.getAttribute('aria-label')).toBe('More actions');
- expect(
- trigger.querySelector('[data-testid="header-overflow-actions-sync-indicator"]'),
- 'a healthy sync must not raise the attention indicator',
- ).toBeNull();
- } finally {
- restoreMetrics();
- }
- });
-
- test('keeps the trailing rail inline when its expanded width fits the available header space', async () => {
- const restoreMetrics = mockHeaderMetrics({ header: 1_000, leading: 100, trailing: 300 });
-
- try {
- const header = await renderMeasuredHeader();
- const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
-
- expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
- expect(document.querySelector('[data-editor-header-overflow-actions]')).toBeNull();
- expect(trailingZone.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true);
- expect(trailingZone.contains(screen.getByRole('button', { name: 'Resources' }))).toBe(true);
- expect(trailingZone.querySelector('[data-testid="sync-status-badge"]')).toBeTruthy();
- } finally {
- restoreMetrics();
- }
- });
-
- test('counts the leading rail offset against the available header space', async () => {
- const restoreMetrics = mockHeaderMetrics({
- header: 300,
- leading: 57,
- leadingOffset: 40,
- trailing: 218,
- });
-
- try {
- await renderMeasuredHeader();
-
- expect(
- screen.queryByRole('button', { name: 'More actions' }),
- 'a 218px trailing rail does not fit the 203px left of a 300px header once the 40px leading offset is counted',
- ).not.toBeNull();
- } finally {
- restoreMetrics();
- }
- });
-
- test('never collapses the trailing rail while the header is unmeasured', async () => {
- const restoreMetrics = mockHeaderMetrics({ header: 0, leading: 57, trailing: 218 });
-
- try {
- const header = await renderMeasuredHeader();
- const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
-
- expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
- expect(document.querySelector('[data-editor-header-overflow-actions]')).toBeNull();
- expect(trailingZone.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true);
- } finally {
- restoreMetrics();
- }
- });
-
- test('reads the collapse verdict off measured width, not the file-navigator state', async () => {
- const cramped = { header: 107, leading: 57, trailing: 218 };
-
- expect(await trailingRailCollapses('expanded', cramped)).toBe(true);
- expect(await trailingRailCollapses('collapsed', cramped)).toBe(true);
- });
-
- test('a collapsed trailing rail stays collapsed when its own collapsed width is re-measured', async () => {
- const observer = captureResizeObserver();
- const restoreMetrics = mockHeaderMetrics({
- header: 107,
- leading: 57,
- trailing: 218,
- collapsedTrailing: 36,
- });
-
- try {
- await renderMeasuredHeader();
- expect(screen.queryByRole('button', { name: 'More actions' })).not.toBeNull();
-
- for (const pass of [1, 2, 3]) {
- observer.flush();
- expect(
- screen.queryByRole('button', { name: 'More actions' }),
- `re-measurement pass ${pass} re-expanded the rail even though the available width never changed`,
- ).not.toBeNull();
- }
- } finally {
- restoreMetrics();
- observer.restore();
- }
- });
-
- test('re-measures the frozen expanded width when the trailing rail content changes', async () => {
- const observer = captureResizeObserver();
- let restoreMetrics = mockHeaderMetrics({
- header: 107,
- leading: 57,
- trailing: 218,
- collapsedTrailing: 36,
- });
-
- try {
- await renderMeasuredHeader();
- expect(screen.queryByRole('button', { name: 'More actions' })).not.toBeNull();
-
- restoreMetrics();
- restoreMetrics = mockHeaderMetrics({
- header: 107,
- leading: 57,
- trailing: 40,
- collapsedTrailing: 36,
- });
- activeDocName = '__skill__/project/my-skill';
- rerenderHeader?.(<div>tabs</div>);
-
- await waitFor(() =>
- expect(
- screen.queryByRole('button', { name: 'More actions' }),
- 'the cached expanded width never invalidates, so the rail latches collapsed at a width where it now fits',
- ).toBeNull(),
- );
- observer.flush();
- expect(
- screen.queryByRole('button', { name: 'More actions' }),
- 'the honest re-measure must read the new 40px rail, not bounce straight back to the stale 218px',
- ).toBeNull();
- } finally {
- restoreMetrics();
- observer.restore();
- }
- });
-
- test('hides the tab strip when the header cannot fit the strip reservations', async () => {
- const restoreMetrics = mockHeaderMetrics({
- header: 94,
- leading: 57,
- tabs: 94,
- trailing: 218,
- collapsedTrailing: 36,
- });
-
- try {
- const header = await renderHeaderAwaitingTabSuppression();
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
-
- expectVisualClassTokens(tabHost.className, ['invisible']);
- expect(
- screen.queryByRole('button', { name: 'More actions' }),
- 'a 94px header collapses the trailing rail as well, so the strip is not merely unmeasured',
- ).not.toBeNull();
- } finally {
- restoreMetrics();
- }
- });
-
- test('a collapsed trailing rail does not by itself hide the tab strip', async () => {
- const restoreMetrics = mockHeaderMetrics({
- header: 107,
- leading: 57,
- tabs: 107,
- trailing: 218,
- collapsedTrailing: 36,
- });
-
- try {
- const header = await renderMeasuredHeader();
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
-
- expect(screen.queryByRole('button', { name: 'More actions' })).not.toBeNull();
- expect(
- tabHost.getAttribute('data-editor-header-tabs-suppressed'),
- 'the strip hides on its own reservation arithmetic, never on the collapse verdict',
- ).toBeNull();
- expectVisualClassTokensAbsent(tabHost.className, ['invisible']);
- } finally {
- restoreMetrics();
- }
- });
-
- test('keeps the tab strip visible when the header has room for both rails', async () => {
- const restoreMetrics = mockHeaderMetrics({
- header: 900,
- leading: 100,
- tabs: 900,
- trailing: 300,
- });
-
- try {
- const header = await renderMeasuredHeader();
- const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
-
- expect(
- tabHost.getAttribute('data-editor-header-tabs-suppressed'),
- '900px of header leaves 492px of tab area, so the strip must not hide',
- ).toBeNull();
- expectVisualClassTokensAbsent(tabHost.className, ['invisible']);
- expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
- } finally {
- restoreMetrics();
- }
- });
-
- test('an active doc yields a doc-scope share input', async () => {
- activeDocName = 'docs/notes';
- activeTarget = { kind: 'doc' };
- await renderHeader();
-
- expect(lastShareInput).toEqual({ kind: 'doc', docName: 'docs/notes' });
- });
-
- test('a selected folder yields a folder-scope share input', async () => {
- activeDocName = null;
- activeTarget = { kind: 'folder', folderPath: 'guides' };
- await renderHeader();
-
- expect(lastShareInput).toEqual({ kind: 'folder', folderRelativePath: 'guides' });
- });
-
- test('nothing open or selected defaults to sharing the project root', async () => {
- activeDocName = null;
- activeTarget = null;
- await renderHeader();
-
- expect(lastShareInput).toEqual({ kind: 'folder', folderRelativePath: '' });
+ test('a project window tab row holds its trailing slot after the tab strip, a drag region whose controls opt out', async () => {
+ setElectronHost(true);
+ const { EditorHeader } = await import('./EditorHeader');
+ render(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader trailing={<button type="button">toggle</button>}>
+ <div data-testid="editor-tabs">tabs</div>
+ </EditorHeader>
+ </TooltipProvider>,
+ );
+ const header = document.querySelector('header') as HTMLElement;
+ const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
+ const trailing = header.querySelector('[data-editor-header-trailing]') as HTMLElement;
+
+ expect(Array.from(header.children)).toEqual([tabHost, trailing]);
+ expect(trailing.contains(screen.getByRole('button', { name: 'toggle' }))).toBe(true);
+ expect(trailing.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(trailing.className, [
+ 'absolute',
+ 'inset-y-0',
+ 'end-0',
+ '[-webkit-app-region:drag]',
+ '[&_button]:[-webkit-app-region:no-drag]',
+ '[&_a]:[-webkit-app-region:no-drag]',
+ ]);
+ expectVisualClassTokensAbsent(trailing.className, ['pe-9', 'shrink-0']);
+ expectVisualClassTokens(tabHost.className, [
+ 'min-w-0',
+ 'w-[var(--editor-header-tabs-width,100%)]',
+ ]);
});
- test('a managed-artifact doc (skill/template) keeps the share trigger disabled', async () => {
- activeDocName = '__skill__/project/my-skill';
- activeTarget = { kind: 'doc' };
- await renderHeader();
+ test('a project window tab row shows its trailing slot only while the row is at least 240px wide', async () => {
+ const { EditorHeader } = await import('./EditorHeader');
+ render(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader trailing={<button type="button">toggle</button>}>
+ <div data-testid="editor-tabs">tabs</div>
+ </EditorHeader>
+ </TooltipProvider>,
+ );
+ const header = document.querySelector('header') as HTMLElement;
+ const trailing = header.querySelector('[data-editor-header-trailing]') as HTMLElement;
- expect(lastShareInput).toBeNull();
+ expect(trailing.contains(screen.getByRole('button', { name: 'toggle' }))).toBe(true);
+ expectVisualClassTokens(header.className, ['@container/editor-header']);
+ expectVisualClassTokens(trailing.className, ['hidden', '@[15rem]/editor-header:flex']);
+ expectVisualClassTokensAbsent(trailing.className, ['flex']);
});
- test('a non-shareable asset target keeps the share trigger disabled', async () => {
- activeDocName = null;
- activeTarget = { kind: 'asset', assetPath: 'img/logo.png' };
- await renderHeader();
+ test('a project window tab row tells the last tab group how wide its trailing slot is, only while the slot shows', async () => {
+ const { EditorHeader } = await import('./EditorHeader');
+ const view = render(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader trailing={<button type="button">toggle</button>}>
+ <div data-testid="editor-tabs">tabs</div>
+ </EditorHeader>
+ </TooltipProvider>,
+ );
+ const header = document.querySelector('header') as HTMLElement;
+ const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
+ expectVisualClassTokens(tabHost.className, [
+ '@[15rem]/editor-header:[--editor-header-trailing-width:2rem]',
+ ]);
+ expect(header.className).not.toContain('--editor-header-trailing-width');
+ expect(header.style.getPropertyValue('--editor-header-trailing-width')).toBe('');
+ view.unmount();
- expect(lastShareInput).toBeNull();
+ render(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader>
+ <div data-testid="editor-tabs">tabs</div>
+ </EditorHeader>
+ </TooltipProvider>,
+ );
+ const bare = document.querySelector('[data-editor-header-tabs]') as HTMLElement;
+ expect(bare.className).not.toContain('--editor-header-trailing-width');
});
});
diff --git a/packages/app/src/components/EditorHeader.layout.test-helper.ts b/packages/app/src/components/EditorHeader.layout.test-helper.ts
index a68872c3b..76ad353b2 100644
--- a/packages/app/src/components/EditorHeader.layout.test-helper.ts
+++ b/packages/app/src/components/EditorHeader.layout.test-helper.ts
@@ -1,4 +1,3 @@
-import { act } from '@testing-library/react';
import { vi } from 'vitest';
export interface HeaderMetrics {
@@ -8,6 +7,7 @@ export interface HeaderMetrics {
tabs?: number;
trailing: number;
collapsedTrailing?: number;
+ paneButton?: number;
}
export function mockHeaderMetrics(source: HeaderMetrics | (() => HeaderMetrics)) {
@@ -15,14 +15,18 @@ export function mockHeaderMetrics(source: HeaderMetrics | (() => HeaderMetrics))
const offsetWidth = vi
.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
.mockImplementation(function (this: HTMLElement) {
- const { header, leading, tabs = 0, trailing, collapsedTrailing } = current();
+ const { header, leading, tabs = 0, trailing, collapsedTrailing, paneButton = 0 } = current();
if (this.tagName === 'HEADER') return header;
if (this.hasAttribute('data-editor-header-leading-actions')) return leading;
if (this.hasAttribute('data-editor-header-tabs')) return tabs;
if (this.hasAttribute('data-editor-header-actions')) {
const collapsed =
this.querySelector('[data-testid="header-overflow-actions-trigger"]') !== null;
- return collapsed && collapsedTrailing !== undefined ? collapsedTrailing : trailing;
+ const paneRow =
+ this.querySelectorAll('[data-testid^="header-pane-button-"]').length * paneButton;
+ return (
+ (collapsed && collapsedTrailing !== undefined ? collapsedTrailing : trailing) + paneRow
+ );
}
return 0;
});
@@ -38,29 +42,3 @@ export function mockHeaderMetrics(source: HeaderMetrics | (() => HeaderMetrics))
offsetWidth.mockRestore();
};
}
-
-export function captureResizeObserver() {
- const callbacks: ResizeObserverCallback[] = [];
- const original = globalThis.ResizeObserver;
- class CapturingResizeObserver {
- constructor(callback: ResizeObserverCallback) {
- callbacks.push(callback);
- }
- observe() {}
- unobserve() {}
- disconnect() {}
- }
- globalThis.ResizeObserver = CapturingResizeObserver as unknown as typeof ResizeObserver;
- return {
- flush() {
- for (const callback of callbacks) {
- act(() => {
- callback([], {} as ResizeObserver);
- });
- }
- },
- restore() {
- globalThis.ResizeObserver = original;
- },
- };
-}
diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsx
index ea4202650..d6a9af0d4 100644
--- a/packages/app/src/components/EditorHeader.tsx
+++ b/packages/app/src/components/EditorHeader.tsx
@@ -1,329 +1,59 @@
// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility
-import { parseManagedArtifactName } from '@inkeep/open-knowledge-core/constants/cc1';
-import { useLingui } from '@lingui/react/macro';
-import { MoreHorizontalIcon, Search } from 'lucide-react';
-import { lazy, type ReactNode, Suspense, useLayoutEffect, useRef, useState } from 'react';
+import { REDUCED_CHROME_HEADER_HEIGHT } from '@inkeep/open-knowledge-core/constants/chrome';
+import { type CSSProperties, lazy, type ReactNode, Suspense } from 'react';
import { shouldShowAppMenubar } from '@/components/app-menubar-gate';
-import { Button } from '@/components/ui/button';
-import { ButtonGroup } from '@/components/ui/button-group';
-import { Kbd } from '@/components/ui/kbd';
-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
-import { Separator } from '@/components/ui/separator';
-import { SidebarTrigger, useSidebar } from '@/components/ui/sidebar';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useDocumentContext } from '@/editor/DocumentContext';
-import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
-import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';
-import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { isNoteWindow } from '@/lib/note-window-mode';
-import {
- buildDocShareInput,
- buildFolderShareInput,
- type ShareTargetInput,
-} from '@/lib/share/run-share-action';
import { useSingleFileMode } from '@/lib/single-file-mode';
import { cn } from '@/lib/utils';
-import { PresenceBar } from '@/presence/PresenceBar';
-import { SyncToastHost } from '@/presence/SyncToastHost';
-import { BetaBadge } from './BetaBadge';
import { EditorBreadcrumb } from './EditorBreadcrumb';
-import { HelpPopover } from './HelpPopover';
-import { InstanceBadge } from './InstanceBadge';
-import { NavigationHistoryControls } from './NavigationHistoryControls';
-import { PublishToGitHubDialog } from './PublishToGitHubDialog';
-import { SettingsButton } from './SettingsButton';
-import { ShareButton } from './ShareButton';
-import { displayState, SyncStatusBadge } from './SyncStatusBadge';
const AppMenubar = lazy(() =>
import('@/components/AppMenubar').then((m) => ({ default: m.AppMenubar })),
);
-const HEADER_OVERFLOW_SLACK_PX = 8;
-const HEADER_TABS_GUTTER_PX = 8;
-
-type SyncAttention = 'conflict' | 'offline' | 'auth-error' | 'paused';
-
-function syncAttentionOf(status: GitSyncStatus | null): SyncAttention | null {
- if (!status?.hasRemote) return null;
- const state = displayState(status);
- if (state === 'conflict' || state === 'offline' || state === 'auth-error') return state;
- if (state === 'disabled' && status.pausedReason) return 'paused';
- return null;
-}
-
interface EditorHeaderProps {
children?: ReactNode;
+ trailing?: ReactNode;
noteModeToggle?: ReactNode;
- onSignIn?: () => void;
- onSetIdentity?: () => void;
- onOpenSearch?: () => void;
}
-export function EditorHeader({
- children,
- noteModeToggle,
- onSignIn,
- onSetIdentity,
- onOpenSearch,
-}: EditorHeaderProps) {
- const { t } = useLingui();
- const { activeDocName, activeTarget } = useDocumentContext();
- const managedArtifact = activeDocName ? parseManagedArtifactName(activeDocName) : null;
- const { state: sidebarState } = useSidebar();
- const singleFile = useSingleFileMode();
- const noteWindow = isNoteWindow();
- const reducedChrome = singleFile || noteWindow;
- const sidebarShortcut = formatShortcut('toggle-files-sidebar');
- const sidebarShortcutLabel = formatShortcutLabel('toggle-files-sidebar');
- const searchShortcut = formatShortcut('command-palette');
- const searchShortcutLabel = formatShortcutLabel('command-palette');
- const [publishOpen, setPublishOpen] = useState(false);
- const [chromeMeasured, setChromeMeasured] = useState(false);
- const [actionsOverflowed, setActionsOverflowed] = useState(false);
- const [tabsSuppressed, setTabsSuppressed] = useState(false);
- const actionsOverflowedRef = useRef(false);
- const measuredSignatureRef = useRef<string | null>(null);
- const trailingIntrinsicWidthRef = useRef(0);
- const headerRef = useRef<HTMLElement>(null);
- const leadingActionsRef = useRef<HTMLDivElement>(null);
- const tabsHostRef = useRef<HTMLDivElement>(null);
- const trailingActionsRef = useRef<HTMLDivElement>(null);
- const shareButtonRef = useRef<HTMLButtonElement>(null);
- const overflowTriggerRef = useRef<HTMLButtonElement>(null);
- const shareInput: ShareTargetInput | null = (() => {
- if (activeTarget?.kind === 'folder') {
- return buildFolderShareInput(activeTarget.folderPath);
- }
- if (activeDocName && !managedArtifact) {
- return buildDocShareInput(activeDocName);
- }
- if (!activeTarget && !activeDocName) {
- return buildFolderShareInput('');
- }
- return null;
- })();
-
- const { status: gitSyncStatus } = useGitSyncStatusDetailed();
- const syncAttention = syncAttentionOf(gitSyncStatus);
- const trailingContentSignature = [
- String(reducedChrome),
- String(noteWindow),
- String(shareInput != null),
- gitSyncStatus?.hasRemote ? displayState(gitSyncStatus) : 'no-remote',
- ].join('|');
+interface ReducedChromeZonesProps {
+ singleFile: boolean;
+ isElectronHost: boolean;
+ trailing?: ReactNode;
+ noteModeToggle?: ReactNode;
+}
- const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
- const isCollapsed = sidebarState === 'collapsed';
- const reserveTrafficLights = isElectronHost && (isCollapsed || noteWindow);
+function ReducedChromeZones({
+ singleFile,
+ isElectronHost,
+ trailing,
+ noteModeToggle,
+}: ReducedChromeZonesProps) {
+ const { activeDocName } = useDocumentContext();
const appMenubar = shouldShowAppMenubar() ? (
<Suspense fallback={null}>
<AppMenubar />
</Suspense>
) : null;
- useLayoutEffect(() => {
- const header = headerRef.current;
- const leadingActions = leadingActionsRef.current;
- const tabsHost = tabsHostRef.current;
- const trailingActions = trailingActionsRef.current;
- if (!header || !leadingActions || !tabsHost || !trailingActions) return;
-
- if (measuredSignatureRef.current !== trailingContentSignature) {
- measuredSignatureRef.current = trailingContentSignature;
- actionsOverflowedRef.current = false;
- trailingIntrinsicWidthRef.current = 0;
- }
-
- const updateChromeWidths = () => {
- const leadingWidth = leadingActions.offsetWidth;
- const leadingOffsetLeft = leadingActions.offsetLeft;
- const trailingWidth = trailingActions.offsetWidth;
- const trailingMargin = Number.parseFloat(getComputedStyle(trailingActions).marginRight) || 0;
- const headerWidth = header.offsetWidth;
- const tabsWidth = tabsHost.offsetWidth;
-
- const rightRailWidth = Math.max(0, headerWidth - tabsWidth);
- const trailingReserve = Math.max(0, trailingWidth + trailingMargin - rightRailWidth);
- header.style.setProperty('--editor-header-leading-width', `${leadingWidth}px`);
- header.style.setProperty('--editor-header-trailing-width', `${trailingReserve}px`);
-
- if (headerWidth > 0) {
- if (!actionsOverflowedRef.current) {
- trailingIntrinsicWidthRef.current = trailingWidth;
- }
- const available = headerWidth - (leadingOffsetLeft + leadingWidth);
- const next = trailingIntrinsicWidthRef.current + HEADER_OVERFLOW_SLACK_PX > available;
- actionsOverflowedRef.current = next;
- setActionsOverflowed(next);
-
- const tabsReserved =
- leadingOffsetLeft + leadingWidth + HEADER_TABS_GUTTER_PX + trailingReserve;
- setTabsSuppressed(tabsWidth > 0 && tabsWidth - tabsReserved <= 0);
- }
- };
- updateChromeWidths();
-
- let revealFrame = requestAnimationFrame(() => {
- updateChromeWidths();
- revealFrame = requestAnimationFrame(() => {
- updateChromeWidths();
- setChromeMeasured(true);
- });
- });
-
- const observer =
- typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(updateChromeWidths);
- observer?.observe(header);
- observer?.observe(leadingActions);
- observer?.observe(tabsHost);
- observer?.observe(trailingActions);
- return () => {
- cancelAnimationFrame(revealFrame);
- observer?.disconnect();
- };
- }, [trailingContentSignature]);
-
- const showOverflowActions = !noteWindow && actionsOverflowed;
-
- const syncAttentionLabel =
- syncAttention === 'conflict'
- ? t`Conflict`
- : syncAttention === 'offline'
- ? t`Offline`
- : syncAttention === 'auth-error'
- ? t`Reconnect required`
- : syncAttention === 'paused'
- ? t`Sync paused`
- : null;
- const overflowActionsLabel = syncAttentionLabel
- ? t`More actions (${syncAttentionLabel})`
- : t`More actions`;
-
- const headerActions = (
- <>
- {}
- {!reducedChrome && (
- <ShareButton
- input={shareInput}
- onClickWhenNoRemote={() => setPublishOpen(true)}
- triggerRef={shareButtonRef}
- />
- )}
- {!noteWindow && <SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} />}
- <PresenceBar />
- <Separator orientation="vertical" className="h-4 shrink-0 data-vertical:self-center" />
- <InstanceBadge className={cn(isElectronHost && '[-webkit-app-region:no-drag]')} />
- <BetaBadge />
- {}
- {!reducedChrome && <SettingsButton />}
- {!noteWindow && <HelpPopover />}
- </>
- );
-
return (
- <header
- ref={headerRef}
- data-electron-drag={isElectronHost ? '' : undefined}
- style={{
- ['--editor-header-leading-offset' as string]: reserveTrafficLights
- ? 'var(--ok-titlebar-reserve-left, 1rem)'
- : '0px',
- }}
- className={cn(
- 'group/editor-header relative flex h-12 shrink-0 items-center',
- 'bg-background',
- !noteWindow && 'shadow-[inset_0_-1px_0_var(--border)]',
- isElectronHost && '[-webkit-app-region:drag]',
- )}
- >
- {}
- <div
- ref={tabsHostRef}
- data-electron-drag={isElectronHost ? '' : undefined}
- data-editor-header-tabs=""
- data-editor-header-tabs-suppressed={tabsSuppressed ? '' : undefined}
- className={cn(
- 'absolute inset-y-0 left-0 z-10 flex min-w-0 w-[var(--editor-header-tabs-width,100%)] overflow-hidden',
- (!chromeMeasured || tabsSuppressed) && 'invisible',
- isElectronHost && '[-webkit-app-region:drag]',
- )}
- >
- {children}
- </div>
-
- {}
+ <>
<div
- ref={leadingActionsRef}
data-electron-drag={isElectronHost ? '' : undefined}
data-editor-header-leading-actions=""
className={cn(
- 'absolute inset-y-0 left-0 z-20 flex items-center gap-1 px-3',
- isElectronHost && '[-webkit-app-region:drag]',
- reserveTrafficLights && 'left-[var(--ok-titlebar-reserve-left,1rem)]',
- noteWindow && 'max-w-[calc(50%-4rem)] overflow-hidden',
+ 'absolute inset-y-0 left-0 z-20 flex max-w-[calc(50%-4rem)] items-center gap-1 overflow-hidden px-3',
+ isElectronHost && '[-webkit-app-region:drag] left-[var(--ok-titlebar-reserve-left,1rem)]',
)}
>
- {}
{singleFile && appMenubar}
- {noteWindow && <EditorBreadcrumb docName={activeDocName} includeCurrentPage />}
- {!reducedChrome && (
- <>
- <ButtonGroup
- aria-label={t`Workspace navigation`}
- className="-ml-1 shrink-0 has-[>[data-slot=button-group]]:gap-0"
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <SidebarTrigger
- className={cn(
- 'shrink-0 text-muted-foreground',
- isElectronHost && '[-webkit-app-region:no-drag]',
- )}
- />
- </TooltipTrigger>
- <TooltipContent>
- <span>{sidebarState === 'expanded' ? t`Hide Files` : t`Show Files`}</span>{' '}
- <Kbd aria-label={sidebarShortcutLabel}>{sidebarShortcut}</Kbd>
- </TooltipContent>
- </Tooltip>
- {isCollapsed && onOpenSearch && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={onOpenSearch}
- aria-label={t`Search (${searchShortcutLabel})`}
- data-telemetry-event="ok.editor_header.search.click"
- className={cn(
- 'shrink-0 text-muted-foreground',
- isElectronHost && '[-webkit-app-region:no-drag]',
- )}
- >
- <Search aria-hidden="true" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <span>{t`Search`}</span>{' '}
- <Kbd aria-label={searchShortcutLabel}>{searchShortcut}</Kbd>
- </TooltipContent>
- </Tooltip>
- )}
- {isElectronHost && isCollapsed && <NavigationHistoryControls />}
- </ButtonGroup>
- {}
- {appMenubar}
- <Separator
- orientation="vertical"
- className="mr-1 h-4 shrink-0 data-vertical:self-center"
- />
- </>
- )}
+ <EditorBreadcrumb docName={activeDocName} includeCurrentPage />
</div>
- {noteWindow && noteModeToggle ? (
+ {noteModeToggle ? (
<div
data-note-window-mode-toggle=""
className="absolute inset-y-0 left-1/2 z-30 flex -translate-x-1/2 items-center [-webkit-app-region:no-drag]"
@@ -333,66 +63,86 @@ export function EditorHeader({
) : null}
<div
- ref={trailingActionsRef}
data-electron-drag={isElectronHost ? '' : undefined}
data-editor-header-actions=""
className={cn(
- 'absolute inset-y-0 right-0 z-20 flex items-center justify-end gap-2',
- showOverflowActions ? 'px-1' : 'px-3',
+ 'absolute inset-y-0 right-0 z-20 flex items-center justify-end gap-2 ps-3 pe-3',
isElectronHost &&
'[-webkit-app-region:drag] [&_button]:[-webkit-app-region:no-drag] [&_a]:[-webkit-app-region:no-drag]',
isElectronHost && 'mr-[var(--ok-titlebar-reserve-right,0px)]',
)}
>
- {!noteWindow &&
- (showOverflowActions ? (
- <Popover>
- <PopoverTrigger asChild>
- <Button
- ref={overflowTriggerRef}
- variant="ghost"
- size="icon-sm"
- aria-label={overflowActionsLabel}
- data-testid="header-overflow-actions-trigger"
- className="relative shrink-0 text-muted-foreground"
- >
- <MoreHorizontalIcon aria-hidden="true" />
- {syncAttention ? (
- <span
- aria-hidden="true"
- data-testid="header-overflow-actions-sync-indicator"
- data-sync-attention={syncAttention}
- className={cn(
- 'absolute top-0.5 right-0.5 size-1.5 rounded-full ring-1 ring-background',
- syncAttention === 'auth-error' && 'bg-destructive',
- syncAttention === 'offline' && 'bg-muted-foreground',
- (syncAttention === 'conflict' || syncAttention === 'paused') &&
- 'bg-amber-500',
- )}
- />
- ) : null}
- </Button>
- </PopoverTrigger>
- <PopoverContent
- align="end"
- data-editor-header-overflow-actions=""
- className="flex w-auto max-w-[calc(100vw-1rem)] flex-wrap items-center justify-end gap-2 p-2"
- >
- {headerActions}
- </PopoverContent>
- </Popover>
- ) : (
- headerActions
- ))}
- {!noteWindow && <SyncToastHost />}
- {!reducedChrome && (
- <PublishToGitHubDialog
- open={publishOpen}
- onOpenChange={setPublishOpen}
- returnFocus={() => (shareButtonRef.current ?? overflowTriggerRef.current)?.focus()}
- />
+ {trailing}
+ </div>
+ </>
+ );
+}
+
+const TRAILING_WIDTH_CLASS = '@[15rem]/editor-header:[--editor-header-trailing-width:2rem]';
+
+export function EditorHeader({ children, trailing, noteModeToggle }: EditorHeaderProps) {
+ const singleFile = useSingleFileMode();
+ const noteWindow = isNoteWindow();
+ const { activeDocName } = useDocumentContext();
+ const reducedChrome = noteWindow;
+ const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
+
+ return (
+ <header
+ data-editor-header=""
+ data-electron-drag={isElectronHost ? '' : undefined}
+ style={
+ reducedChrome
+ ? ({ '--ok-reduced-chrome-header-height': REDUCED_CHROME_HEADER_HEIGHT } as CSSProperties)
+ : undefined
+ }
+ className={cn(
+ 'relative flex shrink-0 items-center @container/editor-header',
+ reducedChrome ? 'h-[var(--ok-reduced-chrome-header-height)]' : 'h-11',
+ 'bg-background',
+ isElectronHost && '[-webkit-app-region:drag]',
+ )}
+ >
+ <div
+ data-electron-drag={isElectronHost ? '' : undefined}
+ data-editor-header-tabs=""
+ className={cn(
+ 'flex h-full min-w-0 w-[var(--editor-header-tabs-width,100%)] overflow-hidden',
+ isElectronHost && '[-webkit-app-region:drag]',
+ !reducedChrome && trailing != null && TRAILING_WIDTH_CLASS,
+ )}
+ >
+ {singleFile ? (
+ <div className="flex min-w-0 items-center px-3">
+ <EditorBreadcrumb docName={activeDocName} includeCurrentPage />
+ </div>
+ ) : (
+ children
)}
</div>
+
+ {reducedChrome || trailing == null ? null : (
+ <div
+ data-editor-header-trailing=""
+ data-electron-drag={isElectronHost ? '' : undefined}
+ className={cn(
+ 'absolute inset-y-0 end-0 z-10 hidden items-center @[15rem]/editor-header:flex',
+ isElectronHost &&
+ '[-webkit-app-region:drag] [&_button]:[-webkit-app-region:no-drag] [&_a]:[-webkit-app-region:no-drag]',
+ )}
+ >
+ {trailing}
+ </div>
+ )}
+
+ {reducedChrome && (
+ <ReducedChromeZones
+ singleFile={singleFile}
+ isElectronHost={isElectronHost}
+ trailing={trailing}
+ noteModeToggle={noteModeToggle}
+ />
+ )}
</header>
);
}
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 d3ad05ac0..b94ca3cf1 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
@@ -13,6 +13,10 @@ import {
writeDockSessionOrder,
} from '@/lib/dock-session-persistence';
import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';
+import {
+ __resetPaneVisibilityStoreForTests,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
let openThreads: ThreadInfo[] = [];
let connectionStatus: 'idle' | 'connecting' | 'open' | 'closed' = 'open';
@@ -166,12 +170,10 @@ vi.doMock('./EditorArea', () => ({
EditorArea: ({
agentsVisible,
onAgentsVisibleChange,
- onRevealAgents,
onSessionPlacements,
}: {
agentsVisible?: boolean;
onAgentsVisibleChange?: (visible: boolean) => void;
- onRevealAgents?: () => void;
onSessionPlacements?: (placements: unknown) => void;
}) => {
const [agentsContainer] = useState(() => document.createElement('div'));
@@ -193,10 +195,6 @@ vi.doMock('./EditorArea', () => ({
/>
</div>
);
- if (onRevealAgents != null)
- return (
- <button type="button" data-testid="agents-reveal-tab" onClick={() => onRevealAgents()} />
- );
return null;
},
}));
@@ -321,6 +319,7 @@ describe('EditorPane agents-panel reload visibility', () => {
afterEach(() => {
cleanup();
delete (window as { okDesktop?: unknown }).okDesktop;
+ __resetPaneVisibilityStoreForTests();
});
test('web: a fresh mount restores a persisted open agents panel', async () => {
@@ -329,7 +328,7 @@ describe('EditorPane agents-panel reload visibility', () => {
await renderPane(3);
expect(screen.queryByTestId('agents-column')).not.toBeNull();
- expect(screen.queryByTestId('agents-reveal-tab')).toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(true);
});
test('web: the reload roster snapshot does not reveal a panel persisted closed', async () => {
@@ -338,7 +337,7 @@ describe('EditorPane agents-panel reload visibility', () => {
await renderPane(3);
expect(screen.queryByTestId('agents-column')).toBeNull();
- expect(screen.queryByTestId('agents-reveal-tab')).not.toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(false);
await act(async () => {
deliverRosterThreads([makeThread({ threadId: 't1' })]);
@@ -394,7 +393,7 @@ describe('EditorPane agents-panel reload visibility', () => {
fireEvent.click(screen.getByTestId('agents-collapse'));
});
- expect(screen.queryByTestId('agents-reveal-tab')).not.toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(false);
await act(async () => {
pushLiveThreads([
@@ -412,7 +411,7 @@ describe('EditorPane agents-panel reload visibility', () => {
await renderPane(3);
expect(screen.queryByTestId('agents-column')).toBeNull();
- expect(screen.queryByTestId('agents-reveal-tab')).not.toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(false);
await act(async () => {
deliverRosterThreads([makeThread({ threadId: 't1' })]);
@@ -428,7 +427,7 @@ describe('EditorPane agents-panel reload visibility', () => {
await renderPane(6);
expect(screen.queryByTestId('agents-column')).toBeNull();
- expect(screen.queryByTestId('agents-reveal-tab')).not.toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(false);
await act(async () => {
deliverRosterThreads([makeThread({ threadId: 't1' })]);
@@ -483,17 +482,59 @@ describe('EditorPane agents-panel reload visibility', () => {
expect(readPersistedAgentsPanelLevel()).toBe(false);
});
- test('web: revealing the agents panel persists the open level', async () => {
+ test('web: a header show and hide persist the agents-panel level', async () => {
await renderPane(3);
expect(readPersistedAgentsPanelLevel()).toBe(false);
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
expect(screen.queryByTestId('agents-column')).not.toBeNull();
expect(readPersistedAgentsPanelLevel()).toBe(true);
+
+ await act(async () => {
+ paneVisibilityStore.request('agents', false);
+ });
+
+ expect(screen.queryByTestId('agents-column')).toBeNull();
+ expect(readPersistedAgentsPanelLevel()).toBe(false);
+ });
+
+ test('desktop: a header show during a pending dock restore reads closed first and survives settlement', async () => {
+ const pendingDockState = deferredDockState();
+ const viewMenuStates: Array<Record<string, unknown>> = [];
+ installDesktopBridge(() => pendingDockState.promise, {
+ onViewMenuStateChanged: (state) => viewMenuStates.push(state),
+ });
+
+ await renderPane(6);
+
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: true, onScreen: true },
+ agents: { open: false, onScreen: false },
+ terminal: { open: false, onScreen: false },
+ });
+
+ await act(async () => {
+ paneVisibilityStore.request('agents', true);
+ paneVisibilityStore.request('terminal', true);
+ });
+
+ expect(screen.queryByTestId('agents-column')).not.toBeNull();
+
+ await act(async () => {
+ pendingDockState.resolve({ terminalVisible: false, agentPanelVisible: false });
+ });
+
+ expect(screen.queryByTestId('agents-column')).not.toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(true);
+ expect(paneVisibilityStore.getSnapshot().terminal?.open).toBe(true);
+ const levels = (key: string) =>
+ viewMenuStates.filter((state) => key in state).map((state) => state[key]);
+ expect(levels('agentPanelVisible').at(-1)).toBe(true);
+ expect(levels('terminalVisible').at(-1)).toBe(true);
});
test('desktop: a toggle during a pending dock restore survives settlement with the toggled level', async () => {
@@ -506,7 +547,7 @@ describe('EditorPane agents-panel reload visibility', () => {
await renderPane(6);
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
expect(screen.queryByTestId('agents-column')).not.toBeNull();
@@ -586,7 +627,10 @@ describe('EditorPane agents-panel reload visibility', () => {
expect(storeListeners.size).toBeGreaterThanOrEqual(6);
expect(screen.queryByTestId('agents-column')).toBeNull();
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
await act(async () => {
vi.advanceTimersByTime(5_000);
@@ -595,12 +639,22 @@ describe('EditorPane agents-panel reload visibility', () => {
expect(
warnSpy.mock.calls.some((call) =>
String(call[0]).includes(
- 'dock-state restore exceeded its 5000ms bound; the agents panel and terminal start closed and only that un-restored level is withheld from the view menu and the dock record, so a later reveal or toggle still publishes',
+ 'dock-state restore exceeded its 5000ms bound; the agents panel and terminal start closed and the editor starts shown until the read lands; a read that still lands reveals nothing, and hides the editor only when the saved layout had no pane open and the user has not chosen an editor level since mount; each level still unrestored is withheld from the view menu and the dock record, so a later reveal or toggle still publishes',
),
),
).toBe(true);
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ editorVisible: true,
+ wideIntent: { editorVisible: true },
+ });
await act(async () => {
pushLiveThreads([
@@ -610,14 +664,23 @@ describe('EditorPane agents-panel reload visibility', () => {
});
expect(screen.queryByTestId('agents-column')).not.toBeNull();
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: true });
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
await act(async () => {
hungDockState.resolve({ terminalVisible: true, agentPanelVisible: false });
});
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: true });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
expect(screen.queryByTestId('agents-column')).not.toBeNull();
} finally {
vi.useRealTimers();
@@ -646,15 +709,35 @@ describe('EditorPane agents-panel reload visibility', () => {
failingDockState.reject(new Error('dock-state ipc failed'));
});
+ expect(
+ errorSpy.mock.calls.some((call) =>
+ String(call[0]).includes(
+ 'dock-state restore failed; the agents panel and terminal start closed and the editor starts shown without its saved state applied;',
+ ),
+ ),
+ ).toBe(true);
expect(viewMenuStates).toContainEqual({ terminalPlacement: 'bottom' });
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ editorVisible: true,
+ wideIntent: { editorVisible: true },
+ });
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: true });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
} finally {
errorSpy.mockRestore();
}
@@ -679,20 +762,32 @@ describe('EditorPane agents-panel reload visibility', () => {
await act(async () => {});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
await act(async () => {
fireEvent.click(screen.getByTestId('agents-collapse'));
});
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: true });
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
await act(async () => {
vi.advanceTimersByTime(5_000);
});
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: false });
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
} finally {
vi.useRealTimers();
warnSpy.mockRestore();
@@ -717,19 +812,28 @@ describe('EditorPane agents-panel reload visibility', () => {
await act(async () => {});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
await act(async () => {
fireEvent.click(screen.getByTestId('agents-collapse'));
});
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
await act(async () => {
failingDockState.reject(new Error('dock-state ipc failed'));
});
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: false });
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
} finally {
errorSpy.mockRestore();
}
@@ -759,10 +863,13 @@ describe('EditorPane agents-panel reload visibility', () => {
});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: true });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
const lateRejection = new Error('dock-state ipc failed after the deadline');
await act(async () => {
@@ -780,7 +887,10 @@ describe('EditorPane agents-panel reload visibility', () => {
fireEvent.click(screen.getByTestId('agents-collapse'));
});
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
} finally {
vi.useRealTimers();
warnSpy.mockRestore();
@@ -807,19 +917,28 @@ describe('EditorPane agents-panel reload visibility', () => {
await act(async () => {});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
expect(screen.queryByTestId('agents-column')).not.toBeNull();
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: true });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
await act(async () => {
vi.advanceTimersByTime(5_000);
});
expect(screen.queryByTestId('agents-column')).not.toBeNull();
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: true });
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
} finally {
vi.useRealTimers();
warnSpy.mockRestore();
@@ -844,18 +963,27 @@ describe('EditorPane agents-panel reload visibility', () => {
await act(async () => {});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-reveal-tab'));
+ paneVisibilityStore.request('agents', true);
});
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: true });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
await act(async () => {
failingDockState.reject(new Error('dock-state ipc failed'));
});
expect(screen.queryByTestId('agents-column')).not.toBeNull();
- expect(viewMenuStates).toContainEqual({ agentPanelVisible: true });
- expect(viewMenuStates).not.toContainEqual({ agentPanelVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
} finally {
errorSpy.mockRestore();
}
@@ -883,14 +1011,23 @@ describe('EditorPane agents-panel reload visibility', () => {
emitLocalMenuAction('toggle-terminal');
});
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: true });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
await act(async () => {
vi.advanceTimersByTime(5_000);
});
- expect(viewMenuStates).toContainEqual({ terminalVisible: true });
- expect(viewMenuStates).not.toContainEqual({ terminalVisible: false });
+ expect(viewMenuStates).toContainEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
+ expect(viewMenuStates).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
} finally {
vi.useRealTimers();
warnSpy.mockRestore();
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index 1527406f5..e8767d9c7 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -3,7 +3,7 @@ import { act, cleanup, render, screen } from '@testing-library/react';
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 } from 'react';
+import { type ReactNode, type Ref, useEffect, useImperativeHandle } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { registerEditor, unregisterEditor } from '@/editor/active-editor';
@@ -15,6 +15,28 @@ import {
peekPendingSourceNavigation,
} from '@/editor/source-editor-navigation';
import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from '@/editor/view-in-source-event';
+import { resolveLauncherSelection } from '@/lib/acp/launcher-selection';
+import {
+ getDefaultRegisteredAgent,
+ getRegisteredAgentOptions,
+ pickEffectiveDefaultAgent,
+ reloadRegisteredAgentsFromStorage,
+ setDetectedRegisteredAgentSuggestions,
+} from '@/lib/acp/registered-agents';
+import { narrowWorkspaceSessionKey } from '@/lib/narrow-workspace-session';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneId,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
+import { RESTORE_SETTLE_TIMEOUT_MS } from '@/lib/restore-settle-timeout';
+import { revealEditor } from '@/lib/reveal-editor';
+import {
+ IN_APP_THREAD_ID,
+ loadStickyAgent,
+ saveStickyAgent,
+ terminalCliId,
+} from '@/lib/unified-agent-store';
import { subscribeToPreferredSessionRequests } from './handoff/preferred-session-events';
import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';
import {
@@ -93,6 +115,30 @@ function capturePreferredSessionRequests(): { readonly count: number; stop: () =
return state;
}
+const authoredPreferredStops: Array<() => void> = [];
+function trackPreferredStop(stop: () => void): () => void {
+ authoredPreferredStops.push(stop);
+ return stop;
+}
+
+function currentPreferredKind() {
+ return resolveLauncherSelection({
+ sticky: loadStickyAgent(),
+ effectiveThreadAgent: pickEffectiveDefaultAgent(
+ getRegisteredAgentOptions(),
+ getDefaultRegisteredAgent(),
+ ),
+ enabledClis: ['claude'],
+ enabledDesktopTargets: [],
+ installedClis: { claude: true },
+ terminalAvailable: true,
+ threadsAvailable: true,
+ desktopSelectable: false,
+ preferBareTerminal: false,
+ bareTerminalFallback: true,
+ }).kind;
+}
+
function shiftJKeydownInit(): KeyboardEventInit {
const init: KeyboardEventInit = { key: 'j', shiftKey: true, cancelable: true, bubbles: true };
if (isMacOS()) init.metaKey = true;
@@ -137,14 +183,16 @@ vi.doMock('@/lib/config-provider', () => ({
}),
}));
+let workspaceContentDir: string | null = '/tmp/project';
vi.doMock('@/lib/use-workspace', () => ({
- useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),
+ useWorkspace: () => ({ contentDir: workspaceContentDir, pathSeparator: '/' }),
}));
let activeProvider: { document: Y.Doc } | undefined;
+let activeDocumentName: string | null = TEST_DOC;
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
- activeDocName: 'docs/notes',
+ activeDocName: activeDocumentName,
collabUrl: 'ws://test',
activeProvider,
}),
@@ -166,28 +214,95 @@ vi.doMock('./EditorHeader', () => ({
),
}));
+type MockPlacements = {
+ terminal: { container: HTMLElement | null; isShowing: boolean };
+ agents: { container: HTMLElement | null; isShowing: boolean };
+ editorRegion: HTMLElement | null;
+};
+let reportedPlacements: MockPlacements | null = null;
+
+type MockPaneExtents = Record<PaneId, boolean>;
+const PANES_WITH_EXTENT: MockPaneExtents = { agents: true, terminal: true };
+let paneExtents: MockPaneExtents = { ...PANES_WITH_EXTENT };
+let reportPaneExtentChange: (() => void) | undefined;
+
+function setPaneExtent(pane: PaneId, hasExtent: boolean): void {
+ paneExtents = { ...paneExtents, [pane]: hasExtent };
+ act(() => reportPaneExtentChange?.());
+}
+
+type MockEditorAreaHandle = {
+ panesOnScreen(): MockPaneExtents;
+ bringBackPane(pane: PaneId): void;
+};
+
+function MockPaneExtentHandle({
+ handleRef,
+ onPaneExtentChange,
+}: {
+ handleRef?: Ref<MockEditorAreaHandle>;
+ onPaneExtentChange?: () => void;
+}) {
+ reportPaneExtentChange = onPaneExtentChange;
+ useImperativeHandle(handleRef, () => ({
+ panesOnScreen: () => ({ ...paneExtents }),
+ bringBackPane: (pane) => {
+ paneExtents = { ...paneExtents, [pane]: true };
+ onPaneExtentChange?.();
+ },
+ }));
+ return null;
+}
+
+function ReportPlacements({
+ onSessionPlacements,
+}: {
+ onSessionPlacements?: (placements: MockPlacements) => void;
+}) {
+ useEffect(() => {
+ if (reportedPlacements !== null) onSessionPlacements?.(reportedPlacements);
+ }, [onSessionPlacements]);
+ return null;
+}
+
vi.doMock('./EditorArea', () => ({
EditorArea: ({
+ ref,
+ onPaneExtentChange,
renderWorkspaceHeader,
terminalPlacement,
terminalRightWidth,
+ editorVisible,
+ onSessionPlacements,
}: {
- renderWorkspaceHeader?: (tabs: ReactNode) => ReactNode;
+ ref?: Ref<MockEditorAreaHandle>;
+ editorVisible?: boolean;
+ onPaneExtentChange?: () => void;
+ renderWorkspaceHeader?: (tabs: ReactNode, chrome: { trailing: ReactNode }) => ReactNode;
terminalPlacement?: string;
terminalRightWidth?: number;
+ 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" />)}
+ {renderWorkspaceHeader?.(<div data-testid="workspace-tabs" />, { trailing: null })}
+ <ReportPlacements onSessionPlacements={onSessionPlacements} />
+ <MockPaneExtentHandle handleRef={ref} onPaneExtentChange={onPaneExtentChange} />
</div>
),
}));
vi.doMock('./acp/AgentThreadClientBinder', () => ({
AgentThreadClientBinder: () => null,
}));
+const sessionsHostFocusRequests: (() => void)[] = [];
+let preferredHostReady: (() => void) | undefined;
+let agentsHostVisibleChange: ((visible: boolean) => void) | undefined;
+let terminalHostReady: (() => void) | undefined;
+let terminalHostVisibleChange: ((visible: boolean) => void) | undefined;
vi.doMock('./SessionsHost', () => ({
SessionsHost: ({
surface,
@@ -195,20 +310,22 @@ vi.doMock('./SessionsHost', () => ({
terminalCapable,
terminalPlacement,
onTerminalPlacementChange,
- reserveRightRevealTabGutter,
visible,
onVisibleChange,
launch,
threadLaunch,
+ onRequestEditorFocus,
+ onPreferredSessionHostReady,
}: {
surface: string;
+ onRequestEditorFocus?: () => void;
bridge?: unknown;
terminalCapable?: boolean;
terminalPlacement?: string;
onTerminalPlacementChange?: (placement: 'bottom' | 'right') => void;
- reserveRightRevealTabGutter?: boolean;
visible?: boolean;
onVisibleChange?: (visible: boolean) => void;
+ onPreferredSessionHostReady?: () => void;
launch?: {
nonce: number;
stagePaste?: string;
@@ -217,15 +334,28 @@ vi.doMock('./SessionsHost', () => ({
label?: string;
signInThreadId?: string;
} | null;
- threadLaunch?: { nonce: number; agentId?: string; prompt?: string | null } | null;
+ threadLaunch?: {
+ nonce: number;
+ agentId?: string;
+ prompt?: string | null;
+ docName?: string | null;
+ titleHint?: string | null;
+ } | null;
}) => {
+ if (onRequestEditorFocus != null) sessionsHostFocusRequests.push(onRequestEditorFocus);
+ if (surface === 'agents-panel') {
+ preferredHostReady = onPreferredSessionHostReady;
+ agentsHostVisibleChange = onVisibleChange;
+ } else {
+ terminalHostReady = onPreferredSessionHostReady;
+ terminalHostVisibleChange = onVisibleChange;
+ }
return (
<div
data-testid={surface === 'agents-panel' ? 'agents-panel' : 'terminal-dock'}
data-has-bridge={String(bridge != null)}
data-terminal-capable={String(terminalCapable === true)}
data-terminal-placement={terminalPlacement}
- data-reserve-right-reveal-gutter={String(reserveRightRevealTabGutter === true)}
data-visible={String(visible)}
data-launch-nonce={launch ? String(launch.nonce) : 'none'}
data-launch-stage={launch?.stagePaste ?? 'none'}
@@ -235,6 +365,9 @@ vi.doMock('./SessionsHost', () => ({
data-launch-sign-in={launch?.signInThreadId ?? 'none'}
data-thread-launch-nonce={threadLaunch ? String(threadLaunch.nonce) : 'none'}
data-thread-launch-agent={threadLaunch?.agentId ?? 'none'}
+ data-thread-launch-prompt={threadLaunch?.prompt ?? 'none'}
+ data-thread-launch-document={threadLaunch?.docName ?? 'none'}
+ data-thread-launch-title={threadLaunch?.titleHint ?? 'none'}
data-thread-launch-image-parts={String(collectImageParts(threadLaunch).length)}
>
{surface === 'agents-panel' ? (
@@ -263,7 +396,13 @@ vi.doMock('@/lib/terminal-telemetry', () => ({
}));
vi.doMock('./AuthModal', () => ({
- AuthModal: () => <div data-testid="auth-modal" />,
+ AuthModal: ({ open, identityPrompt }: { open: boolean; identityPrompt?: boolean }) => (
+ <div
+ data-testid="auth-modal"
+ data-open={String(open)}
+ data-identity-prompt={String(identityPrompt === true)}
+ />
+ ),
}));
vi.doMock('@/editor/components/TagDialog', () => ({
@@ -294,8 +433,9 @@ vi.doMock('./AutoSyncOnboardingDialog', () => ({
async function renderEditorPane() {
const { EditorPane } = await import('./EditorPane');
- render(<EditorPane />);
+ const view = render(<EditorPane />);
await act(async () => {});
+ return view;
}
describe('EditorPane auto-sync onboarding gate', () => {
@@ -459,6 +599,7 @@ describe('EditorPane auto-sync onboarding gate', () => {
type DockStateResult = {
terminalVisible: boolean;
agentPanelVisible: boolean;
+ editorVisible?: boolean;
placement?: 'bottom' | 'right';
rightWidth?: number;
};
@@ -518,13 +659,22 @@ function makeOkDesktopStub(
describe('EditorPane session-panel wiring', () => {
afterEach(() => {
+ for (const stop of authoredPreferredStops.splice(0)) stop();
cleanup();
localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ setDetectedRegisteredAgentSuggestions([]);
delete (window as { okDesktop?: unknown }).okDesktop;
terminalOpenedCalls.length = 0;
clearSelection();
activeProvider = undefined;
clearPendingSourceNavigationsForTest();
+ preferredHostReady = undefined;
+ agentsHostVisibleChange = undefined;
+ terminalHostReady = undefined;
+ terminalHostVisibleChange = undefined;
+ paneExtents = { ...PANES_WITH_EXTENT };
+ workspaceContentDir = '/tmp/project';
});
test('web host mounts the agents panel only — no shell can spawn, so no terminal dock', async () => {
@@ -597,7 +747,10 @@ describe('EditorPane session-panel wiring', () => {
act(() => desk.dispatchMenuAction('toggle-agent-panel'));
const agentsPush = desk.viewMenuPushes.at(-1);
- expect(agentsPush).toEqual({ agentPanelVisible: true });
+ expect(agentsPush).toEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
});
test('desktop: toggle-terminal flips terminal visibility and pushes the view-menu state', async () => {
@@ -606,15 +759,24 @@ describe('EditorPane session-panel wiring', () => {
await renderEditorPane();
expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
- expect(desk.viewMenuPushes).toContainEqual({ terminalVisible: false });
+ expect(desk.viewMenuPushes).toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
act(() => desk.dispatchMenuAction('toggle-terminal'));
expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('true');
- expect(desk.viewMenuPushes.at(-1)).toEqual({ terminalVisible: true });
+ expect(desk.viewMenuPushes.at(-1)).toEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
act(() => desk.dispatchMenuAction('toggle-terminal'));
expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
- expect(desk.viewMenuPushes.at(-1)).toEqual({ terminalVisible: false });
+ expect(desk.viewMenuPushes.at(-1)).toEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
});
test('desktop: move-terminal changes home while terminal toggles preserve it', async () => {
@@ -762,6 +924,30 @@ describe('EditorPane session-panel wiring', () => {
expect(nav.intent).toBe('jump');
});
+ test('desktop: view in source with the editor hidden shows the editor before it jumps', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ const markdown = '# Title\n\nfirst paragraph\n\ntarget paragraph';
+ const ydoc = new Y.Doc();
+ ydoc.getText('source').insert(0, markdown);
+ activeProvider = { document: ydoc };
+ const editor = makeJumpEditor(markdown, 3);
+ registerEditor('docs/notes', editor);
+ const editorShownAtJump: Array<string | null> = [];
+ const onFlip = () =>
+ editorShownAtJump.push(screen.getByTestId('editor-area').getAttribute('data-editor-visible'));
+ window.addEventListener(VIEW_IN_SOURCE_EVENT, onFlip);
+
+ await renderEditorPane();
+ act(() => paneVisibilityStore.request('editor', false));
+ act(() => desk.dispatchMenuAction('toggle-source'));
+
+ window.removeEventListener(VIEW_IN_SOURCE_EVENT, onFlip);
+ unregisterEditor('docs/notes', editor);
+
+ expect(editorShownAtJump).toEqual(['true']);
+ });
+
test('desktop: pushes the view-in-source capability for the context-menu row', async () => {
const desk = makeOkDesktopStub();
(window as { okDesktop?: unknown }).okDesktop = desk.stub;
@@ -867,9 +1053,6 @@ describe('EditorPane session-panel wiring', () => {
expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('true');
expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('true');
- expect(
- screen.getByTestId('terminal-dock').getAttribute('data-reserve-right-reveal-gutter'),
- ).toBe('false');
});
test('desktop: per-install right layout reaches both editor and stable terminal host', async () => {
@@ -888,9 +1071,6 @@ describe('EditorPane session-panel wiring', () => {
expect(screen.getByTestId('terminal-dock').getAttribute('data-terminal-placement')).toBe(
'right',
);
- expect(
- screen.getByTestId('terminal-dock').getAttribute('data-reserve-right-reveal-gutter'),
- ).toBe('true');
expect(desk.dockStateUpdates).toEqual([]);
});
@@ -980,6 +1160,119 @@ describe('EditorPane session-panel wiring', () => {
expect(agents.getAttribute('data-thread-launch-nonce')).not.toBe('none');
});
+ test('desktop: a narrow session close reports closed wide intent while the menu tracks the projection', async () => {
+ const notified: Array<{
+ agentPanelVisible?: boolean;
+ wideIntent?: { agentPanelVisible?: boolean };
+ }> = [];
+ (window as { okDesktop?: unknown }).okDesktop = {
+ config: { ptyAvailable: true },
+ onMenuAction: () => () => {},
+ editor: {
+ notifyViewMenuStateChanged(state: (typeof notified)[number]) {
+ notified.push(state);
+ },
+ },
+ terminal: {
+ getDockState: async () => ({ terminalVisible: false, agentPanelVisible: true }),
+ },
+ };
+ const originalMatchMedia = window.matchMedia;
+ const narrowQuery = originalMatchMedia('(width < 48rem)');
+ Object.defineProperty(narrowQuery, 'matches', { configurable: true, value: true });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) =>
+ query === '(width < 48rem)' ? narrowQuery : originalMatchMedia(query),
+ });
+ const lastWideAgents = () =>
+ notified.filter((state) => state.wideIntent?.agentPanelVisible !== undefined).at(-1);
+
+ try {
+ await renderEditorPane();
+ await act(async () => agentsHostVisibleChange?.(true));
+ expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('true');
+ expect(lastWideAgents()?.wideIntent?.agentPanelVisible).toBe(true);
+
+ await act(async () =>
+ (
+ agentsHostVisibleChange as
+ | ((visible: boolean, reason?: 'session-close') => void)
+ | undefined
+ )?.(false, 'session-close'),
+ );
+
+ expect(lastWideAgents()).toMatchObject({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
+ } finally {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: originalMatchMedia,
+ });
+ }
+ });
+
+ test('a narrow agent launch selects Chat while retaining its document and attachment intent', async () => {
+ const originalMatchMedia = window.matchMedia;
+ const narrowQuery = originalMatchMedia('(width < 48rem)');
+ Object.defineProperty(narrowQuery, 'matches', { configurable: true, value: true });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) =>
+ query === '(width < 48rem)' ? narrowQuery : originalMatchMedia(query),
+ });
+
+ try {
+ await renderEditorPane();
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('true');
+
+ await act(async () => {
+ requestAgentThreadLaunch({
+ agentSource: 'registry',
+ agentId: 'acme-agent',
+ prompt: 'describe the screenshot',
+ docName: TEST_DOC,
+ titleHint: 'Notes',
+ attachments: [
+ {
+ kind: 'image',
+ mimeType: 'image/png',
+ data: 'iVBORw==',
+ name: 'drop-me.png',
+ sizeBytes: 4,
+ },
+ ],
+ });
+ });
+
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('false');
+ expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('true');
+ expect(screen.getByTestId('agents-panel').getAttribute('data-thread-launch-agent')).toBe(
+ 'acme-agent',
+ );
+ expect(screen.getByTestId('agents-panel').getAttribute('data-thread-launch-prompt')).toBe(
+ 'describe the screenshot',
+ );
+ expect(screen.getByTestId('agents-panel').getAttribute('data-thread-launch-document')).toBe(
+ TEST_DOC,
+ );
+ expect(screen.getByTestId('agents-panel').getAttribute('data-thread-launch-title')).toBe(
+ 'Notes',
+ );
+ expect(
+ screen.getByTestId('agents-panel').getAttribute('data-thread-launch-image-parts'),
+ ).toBe('1');
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(true);
+ } finally {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: originalMatchMedia,
+ });
+ }
+ });
+
test('a launch request carrying an image attachment forwards it into the thread-launch intent', async () => {
await renderEditorPane();
@@ -1015,8 +1308,14 @@ describe('EditorPane session-panel wiring', () => {
await renderEditorPane();
expect(desk.viewMenuPushes).toContainEqual({ terminalPlacement: 'bottom' });
- expect(desk.viewMenuPushes).not.toContainEqual({ terminalVisible: false });
- expect(desk.viewMenuPushes).not.toContainEqual({ agentPanelVisible: false });
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
});
@@ -1172,6 +1471,300 @@ describe('EditorPane session-panel wiring', () => {
expect(preferred.count).toBe(1);
});
+ test('web host: a no-selection shortcut reaches the preferred request before a session host subscribes', async () => {
+ await renderEditorPane();
+ clearSelection();
+ window.getSelection()?.removeAllRanges();
+ const preferred = capturePreferredSessionRequests();
+ const input = captureActiveTerminalInput();
+ const event = new KeyboardEvent('keydown', shiftJKeydownInit());
+
+ expect(window.getSelection()?.toString()).toBe('');
+ act(() => {
+ window.dispatchEvent(event);
+ });
+ preferred.stop();
+ input.stop();
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(preferred.count).toBe(1);
+ expect(input.details).toEqual([]);
+ expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('false');
+ });
+
+ test('web host: a cold shortcut is delivered once when its session host becomes ready', async () => {
+ await renderEditorPane();
+ const keyEvent = new KeyboardEvent('keydown', shiftJKeydownInit());
+ act(() => {
+ window.dispatchEvent(keyEvent);
+ });
+ expect(keyEvent.defaultPrevented).toBe(true);
+
+ let launches = 0;
+ const stop = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ stop();
+
+ expect(launches).toBe(1);
+ });
+
+ test('web host: two cold shortcuts deliver two accepted requests without replay on another ready signal', async () => {
+ await renderEditorPane();
+ const first = new KeyboardEvent('keydown', shiftJKeydownInit());
+ const second = new KeyboardEvent('keydown', shiftJKeydownInit());
+ act(() => {
+ window.dispatchEvent(first);
+ window.dispatchEvent(second);
+ });
+ expect(first.defaultPrevented).toBe(true);
+ expect(second.defaultPrevented).toBe(true);
+
+ let launches = 0;
+ const stop = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ expect(launches).toBe(2);
+ act(() => preferredHostReady?.());
+ stop();
+
+ expect(launches).toBe(2);
+ });
+
+ test('web host: zero-width collapse keeps a cold request but explicit Hide cancels the next one', async () => {
+ await renderEditorPane();
+ act(() => agentsHostVisibleChange?.(true));
+ setPaneExtent('agents', false);
+ const first = new KeyboardEvent('keydown', shiftJKeydownInit());
+ act(() => window.dispatchEvent(first));
+ expect(first.defaultPrevented).toBe(true);
+
+ let launches = 0;
+ const stopFirst = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ expect(launches).toBe(1);
+ stopFirst();
+
+ const second = new KeyboardEvent('keydown', shiftJKeydownInit());
+ act(() => window.dispatchEvent(second));
+ expect(second.defaultPrevented).toBe(true);
+ act(() => agentsHostVisibleChange?.(false));
+ const stopSecond = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ stopSecond();
+
+ expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('false');
+ expect(launches).toBe(1);
+ });
+
+ test('web host: project switch and unmount discard the prior owner’s cold request', async () => {
+ const view = await renderEditorPane();
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+
+ let launches = 0;
+ const stopFirst = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ expect(launches).toBe(1);
+ stopFirst();
+
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ workspaceContentDir = '/tmp/other-project';
+ const { EditorPane } = await import('./EditorPane');
+ act(() => view.rerender(<EditorPane />));
+ const stopAfterSwitch = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ expect(launches).toBe(1);
+ stopAfterSwitch();
+
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ act(() => view.unmount());
+ render(<EditorPane />);
+ const stopAfterRemount = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ });
+ act(() => preferredHostReady?.());
+ stopAfterRemount();
+
+ expect(launches).toBe(1);
+ });
+
+ test('desktop: a pending shortcut follows a changed preference into an already ready terminal host', async () => {
+ setDetectedRegisteredAgentSuggestions([{ source: 'registry', id: 'acme-agent', name: 'Acme' }]);
+ saveStickyAgent(IN_APP_THREAD_ID);
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ await renderEditorPane();
+ expect(currentPreferredKind()).toBe('thread');
+ const launches: string[] = [];
+ const stopTerminal = trackPreferredStop(
+ Reflect.apply(subscribeToPreferredSessionRequests, undefined, [
+ () => launches.push('terminal'),
+ window,
+ () => currentPreferredKind() === 'cli',
+ ]) as () => void,
+ );
+ act(() => terminalHostReady?.());
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ expect(launches).toEqual([]);
+
+ act(() => saveStickyAgent(terminalCliId('claude')));
+ expect(currentPreferredKind()).toBe('cli');
+ expect(launches).toEqual(['terminal']);
+ act(() => terminalHostReady?.());
+ stopTerminal();
+ expect(launches).toEqual(['terminal']);
+ });
+
+ test('desktop: a pending shortcut follows catalog loss to the current CLI route', async () => {
+ setDetectedRegisteredAgentSuggestions([{ source: 'registry', id: 'acme-agent', name: 'Acme' }]);
+ saveStickyAgent(IN_APP_THREAD_ID);
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ const view = await renderEditorPane();
+ const { EditorPane } = await import('./EditorPane');
+ expect(currentPreferredKind()).toBe('thread');
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+
+ let launches = 0;
+ const stop = trackPreferredStop(
+ Reflect.apply(subscribeToPreferredSessionRequests, undefined, [
+ () => {
+ launches += 1;
+ },
+ window,
+ () => currentPreferredKind() === 'cli',
+ ]) as () => void,
+ );
+ expect(launches).toBe(0);
+
+ act(() => {
+ setDetectedRegisteredAgentSuggestions([]);
+ view.rerender(<EditorPane />);
+ });
+ expect(currentPreferredKind()).toBe('cli');
+ act(() => terminalHostReady?.());
+ stop();
+ expect(launches).toBe(1);
+ });
+
+ test('desktop: hiding the other pane keeps a pending shortcut, while hiding its current destination cancels it', async () => {
+ setDetectedRegisteredAgentSuggestions([{ source: 'registry', id: 'acme-agent', name: 'Acme' }]);
+ saveStickyAgent(IN_APP_THREAD_ID);
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ await renderEditorPane();
+ expect(currentPreferredKind()).toBe('thread');
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ act(() => saveStickyAgent(terminalCliId('claude')));
+ expect(currentPreferredKind()).toBe('cli');
+ act(() => agentsHostVisibleChange?.(false));
+
+ let launches = 0;
+ const subscribeTerminal = () =>
+ trackPreferredStop(
+ Reflect.apply(subscribeToPreferredSessionRequests, undefined, [
+ () => {
+ launches += 1;
+ },
+ window,
+ () => currentPreferredKind() === 'cli',
+ ]) as () => void,
+ );
+ const stopFirst = subscribeTerminal();
+ act(() => terminalHostReady?.());
+ expect(launches).toBe(1);
+ stopFirst();
+
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ act(() => terminalHostVisibleChange?.(false));
+ const stopSecond = subscribeTerminal();
+ act(() => terminalHostReady?.());
+ stopSecond();
+ expect(launches).toBe(1);
+ });
+
+ test('web host: a stale ready callback cannot drain requests from a new project or mount', async () => {
+ const view = await renderEditorPane();
+ const oldReady = preferredHostReady;
+ const { EditorPane } = await import('./EditorPane');
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ workspaceContentDir = '/tmp/other-project';
+ act(() => view.rerender(<EditorPane />));
+ const projectReady = preferredHostReady;
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+
+ let launches = 0;
+ const stop = trackPreferredStop(
+ subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ }),
+ );
+ act(() => oldReady?.());
+ const launchesAfterOldReady = launches;
+ act(() => projectReady?.());
+ expect(launches).toBe(1);
+ expect(launchesAfterOldReady).toBe(0);
+ stop();
+
+ act(() => view.unmount());
+ render(<EditorPane />);
+ const nextReady = preferredHostReady;
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ expect(launches).toBe(1);
+ const stopAfterRemount = trackPreferredStop(
+ subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ }),
+ );
+ act(() => projectReady?.());
+ const launchesAfterStaleReady = launches;
+ act(() => nextReady?.());
+ stopAfterRemount();
+ expect(launchesAfterStaleReady).toBe(1);
+ expect(launches).toBe(2);
+ });
+
+ test('web host: an unknown workspace binds its first project, then retires intent on a known-project switch', async () => {
+ workspaceContentDir = null;
+ const view = await renderEditorPane();
+ const { EditorPane } = await import('./EditorPane');
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ workspaceContentDir = '/tmp/project-a';
+ act(() => view.rerender(<EditorPane />));
+
+ let launches = 0;
+ const stop = trackPreferredStop(
+ subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ }),
+ );
+ act(() => preferredHostReady?.());
+ expect(launches).toBe(1);
+ stop();
+
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ expect(launches).toBe(1);
+ workspaceContentDir = '/tmp/project-b';
+ act(() => view.rerender(<EditorPane />));
+ const stopAfterSwitch = trackPreferredStop(
+ subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ }),
+ );
+ act(() => preferredHostReady?.());
+ expect(launches).toBe(1);
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+ stopAfterSwitch();
+ expect(launches).toBe(2);
+ });
+
test('desktop: ⌘J with a selection toggles the terminal and stages nothing', async () => {
const desk = makeOkDesktopStub();
(window as { okDesktop?: unknown }).okDesktop = desk.stub;
@@ -1207,6 +1800,63 @@ describe('EditorPane session-panel wiring', () => {
expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('false');
});
+ test('selection handoff reads the active document and editing surface after rerender', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ const view = await renderEditorPane();
+ const { EditorPane } = await import('./EditorPane');
+ seedSelection('old document selection');
+ const input = captureActiveTerminalInput();
+ try {
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ activeDocumentName = 'docs/other';
+ publishSelectionContext('docs/other', 'wysiwyg', {
+ surface: 'wysiwyg',
+ docName: 'docs/other',
+ markdown: 'wrong surface selection',
+ charLen: 23,
+ lineCount: 1,
+ });
+ publishSelectionContext('docs/other', 'source', {
+ surface: 'source',
+ docName: 'docs/other',
+ markdown: 'current source selection',
+ charLen: 24,
+ lineCount: 1,
+ });
+ act(() => view.rerender(<EditorPane />));
+ act(() =>
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ code: 'KeyM',
+ key: 'm',
+ altKey: true,
+ metaKey: true,
+ ctrlKey: true,
+ bubbles: true,
+ }),
+ ),
+ );
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit())));
+
+ expect(input.details).toHaveLength(3);
+ expect(input.details[1]).toMatchObject({ newTab: false, submit: false, target: 'agents' });
+ expect(input.details[2]).toMatchObject({ newTab: true, submit: false });
+ for (const detail of input.details.slice(1)) {
+ expect(detail.text).toContain('current source selection');
+ expect(detail.text).not.toContain('old document selection');
+ expect(detail.text).not.toContain('wrong surface selection');
+ expect(detail.text.endsWith('\n\n')).toBe(true);
+ }
+ } finally {
+ input.stop();
+ activeDocumentName = TEST_DOC;
+ publishSelectionContext('docs/other', 'wysiwyg', null);
+ publishSelectionContext('docs/other', 'source', null);
+ }
+ });
+
test('desktop: ⌘L with no selection still toggles the agents panel', async () => {
const desk = makeOkDesktopStub();
(window as { okDesktop?: unknown }).okDesktop = desk.stub;
@@ -1236,45 +1886,958 @@ describe('EditorPane session-panel wiring', () => {
});
});
-describe('EditorPane mode switch promotes the preview tab', () => {
+describe('EditorPane pane visibility for the header', () => {
afterEach(() => {
cleanup();
+ localStorage.clear();
delete (window as { okDesktop?: unknown }).okDesktop;
- promotePreviewTabMock.mockClear();
- activeProvider = undefined;
- clearPendingSourceNavigationsForTest();
+ terminalOpenedCalls.length = 0;
+ reportedPlacements = null;
+ paneExtents = { ...PANES_WITH_EXTENT };
+ clearSelection();
+ __resetPaneVisibilityStoreForTests();
});
- function pressModeToggle() {
- act(() => {
- window.dispatchEvent(
- new KeyboardEvent('keydown', {
- code: 'KeyM',
- key: 'm',
- altKey: true,
- metaKey: true,
- ctrlKey: true,
- bubbles: true,
- }),
- );
+ test('web host reports chat and no terminal', async () => {
+ await renderEditorPane();
+
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: true, onScreen: true },
+ agents: { open: false, onScreen: false },
+ terminal: null,
});
- }
+ });
- test('flipping a doc between source and WYSIWYG promotes its tab', async () => {
- activeProvider = { document: new Y.Doc() };
+ test('desktop host with a working shell reports both panes', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
await renderEditorPane();
- pressModeToggle();
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: true, onScreen: true },
+ agents: { open: false, onScreen: false },
+ terminal: { open: false, onScreen: false },
+ });
+ });
- expect(promotePreviewTabMock).toHaveBeenCalledWith('docs/notes');
+ test('desktop host without a working shell reports no terminal', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub(undefined, false).stub;
+ await renderEditorPane();
+
+ expect(paneVisibilityStore.getSnapshot().terminal).toBeNull();
+ expect(paneVisibilityStore.getSnapshot().agents).toEqual({ open: false, onScreen: false });
});
- test('a flip with no provider yet promotes nothing', async () => {
- activeProvider = undefined;
+ test('a note window reports neither pane', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = {
+ ...desk.stub,
+ config: { ...desk.stub.config, mode: 'note' },
+ };
await renderEditorPane();
- pressModeToggle();
+ expect(screen.getByTestId('editor-area')).toBeTruthy();
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: null,
+ agents: null,
+ terminal: null,
+ });
+ });
- expect(promotePreviewTabMock).not.toHaveBeenCalled();
+ test('the snapshot follows the other show and hide paths', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ const seen: string[] = [];
+ const stop = paneVisibilityStore.subscribe(() => {
+ const { agents, terminal } = paneVisibilityStore.getSnapshot();
+ seen.push(`agents=${agents?.open} terminal=${terminal?.open}`);
+ });
+
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ act(() => desk.dispatchMenuAction('toggle-terminal'));
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ stop();
+
+ expect(seen).toEqual([
+ 'agents=true terminal=false',
+ 'agents=true terminal=true',
+ 'agents=false terminal=true',
+ ]);
+ expect(paneVisibilityStore.getSnapshot().terminal).toEqual({ open: true, onScreen: true });
+ });
+
+ test('a pending extent report reads visibility after the parent rerenders', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ const pendingReport = reportPaneExtentChange;
+ expect(pendingReport).toBeDefined();
+
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ expect(paneVisibilityStore.getSnapshot().agents).toEqual({ open: true, onScreen: true });
+
+ paneExtents = { ...paneExtents, agents: false };
+ act(() => pendingReport?.());
+ expect(paneVisibilityStore.getSnapshot().agents).toEqual({ open: true, onScreen: false });
+ });
+
+ test('an open pane the layout collapses to zero size reads open but not on screen, at once', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub(async () => ({
+ terminalVisible: true,
+ agentPanelVisible: true,
+ })).stub;
+ await renderEditorPane();
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: true, onScreen: true },
+ agents: { open: true, onScreen: true },
+ terminal: { open: true, onScreen: true },
+ });
+
+ setPaneExtent('agents', false);
+
+ expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('true');
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: true, onScreen: true },
+ agents: { open: true, onScreen: false },
+ terminal: { open: true, onScreen: true },
+ });
+
+ setPaneExtent('agents', true);
+ expect(paneVisibilityStore.getSnapshot().agents).toEqual({ open: true, onScreen: true });
+ });
+
+ test('a hidden pane reads off even while the layout still gives it size', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ await renderEditorPane();
+
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: true, onScreen: true },
+ agents: { open: false, onScreen: false },
+ terminal: { open: false, onScreen: false },
+ });
+ });
+
+ 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,
+ agentPanelVisible: true,
+ })).stub;
+ await renderEditorPane();
+
+ act(() => paneVisibilityStore.request('terminal', false));
+
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
+ expect(paneVisibilityStore.getSnapshot().terminal).toEqual({ open: false, onScreen: false });
+ });
+
+ test('a header request shows and hides chat', async () => {
+ await renderEditorPane();
+ const agents = () => screen.getByTestId('agents-panel').getAttribute('data-visible');
+
+ act(() => paneVisibilityStore.request('agents', true));
+ expect(agents()).toBe('true');
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(true);
+
+ act(() => paneVisibilityStore.request('agents', true));
+ expect(agents()).toBe('true');
+
+ act(() => paneVisibilityStore.request('agents', false));
+ expect(agents()).toBe('false');
+ expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(false);
+ });
+
+ test('desktop: a header request shows and hides the terminal and publishes the level to the view menu', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ const terminal = () => screen.getByTestId('terminal-dock').getAttribute('data-visible');
+
+ act(() => paneVisibilityStore.request('terminal', true));
+ expect(terminal()).toBe('true');
+ expect(desk.viewMenuPushes.at(-1)).toEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
+
+ act(() => paneVisibilityStore.request('terminal', false));
+ expect(terminal()).toBe('false');
+ expect(desk.viewMenuPushes.at(-1)).toEqual({
+ terminalVisible: false,
+ wideIntent: { terminalVisible: false },
+ });
+
+ act(() => paneVisibilityStore.request('agents', true));
+ expect(desk.viewMenuPushes.at(-1)).toEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
+ });
+
+ test('desktop: a header show records one terminal open and a header hide records none', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ await renderEditorPane();
+ expect(terminalOpenedCalls).toHaveLength(0);
+
+ act(() => paneVisibilityStore.request('terminal', true));
+ expect(terminalOpenedCalls).toHaveLength(1);
+
+ act(() => paneVisibilityStore.request('terminal', false));
+ expect(terminalOpenedCalls).toHaveLength(1);
+ });
+
+ test('desktop without a working shell ignores a terminal request', async () => {
+ const desk = makeOkDesktopStub(undefined, false);
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ act(() => paneVisibilityStore.request('terminal', true));
+
+ expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
+ expect(terminalOpenedCalls).toHaveLength(0);
+ });
+
+ test('a note window ignores header requests', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = {
+ ...desk.stub,
+ config: { ...desk.stub.config, mode: 'note' },
+ };
+ await renderEditorPane();
+ expect(desk.viewMenuPushes).toContainEqual({
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: false },
+ });
+
+ act(() => paneVisibilityStore.request('agents', true));
+ act(() => paneVisibilityStore.request('terminal', true));
+
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
+ });
+
+ test('with text selected a header request opens chat and stages nothing, while the chat shortcut still stages it', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ seedSelection('run the build');
+ const agents = () => screen.getByTestId('agents-panel').getAttribute('data-visible');
+ const input = captureActiveTerminalInput();
+
+ act(() => paneVisibilityStore.request('agents', true));
+ expect(agents()).toBe('true');
+ expect(input.texts).toEqual([]);
+
+ act(() => paneVisibilityStore.request('agents', false));
+ expect(agents()).toBe('false');
+ expect(input.texts).toEqual([]);
+
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ input.stop();
+ expect(agents()).toBe('false');
+ expect(input.details).toHaveLength(1);
+ expect(input.details[0]?.target).toBe('agents');
+ expect(input.details[0]?.text).toContain('run the build');
+ });
+
+ test('with the editor hidden, ⌘/Ctrl+L toggles chat and never stages the hidden selection', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ seedSelection('run the build');
+ const agents = () => screen.getByTestId('agents-panel').getAttribute('data-visible');
+ act(() => paneVisibilityStore.request('editor', false));
+ const input = captureActiveTerminalInput();
+
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ expect(agents()).toBe('true');
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ expect(agents()).toBe('false');
+ input.stop();
+
+ expect(input.texts).toEqual([]);
+ expect(desk.viewMenuPushes).toContainEqual({ hasEditorSelection: false });
+ });
+
+ test('a retained selection cannot stage text while narrow Chat covers Editor', async () => {
+ const originalMatchMedia = window.matchMedia;
+ const narrowQuery = originalMatchMedia('(width < 48rem)');
+ Object.defineProperty(narrowQuery, 'matches', { configurable: true, value: true });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) =>
+ query === '(width < 48rem)' ? narrowQuery : originalMatchMedia(query),
+ });
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ try {
+ await renderEditorPane();
+ seedSelection('run the build');
+ act(() => paneVisibilityStore.request('agents', true));
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('false');
+ const input = captureActiveTerminalInput();
+
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ input.stop();
+
+ expect(input.texts).toEqual([]);
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('true');
+ expect(desk.viewMenuPushes).toContainEqual({ hasEditorSelection: false });
+ } finally {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: originalMatchMedia,
+ });
+ }
+ });
+
+ test('with the editor hidden, ⇧⌘J opens a plain new session and never stages the hidden selection', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ await renderEditorPane();
+ seedSelection('run the build');
+ act(() => paneVisibilityStore.request('editor', false));
+ const input = captureActiveTerminalInput();
+ const preferred = capturePreferredSessionRequests();
+
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit()));
+ });
+ input.stop();
+ preferred.stop();
+
+ expect(input.texts).toEqual([]);
+ expect(preferred.count).toBe(1);
+ });
+
+ test('with the editor shown again, ⌘/Ctrl+L stages the selection as before', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ seedSelection('run the build');
+ act(() => paneVisibilityStore.request('editor', false));
+ act(() => paneVisibilityStore.request('editor', true));
+ const input = captureActiveTerminalInput();
+
+ act(() => desk.dispatchMenuAction('toggle-agent-panel'));
+ input.stop();
+
+ expect(input.details).toHaveLength(1);
+ expect(input.details[0]?.text).toContain('run the build');
+ });
+
+ test('a header hide leaves focus where it was', async () => {
+ const editorRegion = document.createElement('div');
+ editorRegion.tabIndex = -1;
+ document.body.append(editorRegion);
+ reportedPlacements = {
+ terminal: { container: null, isShowing: false },
+ agents: { container: document.createElement('div'), isShowing: true },
+ editorRegion,
+ };
+ await renderEditorPane();
+ act(() => paneVisibilityStore.request('agents', true));
+ const headerButton = document.createElement('button');
+ document.body.append(headerButton);
+ headerButton.focus();
+
+ act(() => paneVisibilityStore.request('agents', false));
+
+ expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('false');
+ expect(document.activeElement).toBe(headerButton);
+ headerButton.remove();
+ editorRegion.remove();
+ });
+
+ test('a project window shows the editor by default and applies header hide and show requests', async () => {
+ await renderEditorPane();
+ const editorArea = screen.getByTestId('editor-area');
+ expect(editorArea.getAttribute('data-editor-visible')).toBe('true');
+ expect(paneVisibilityStore.getSnapshot().editor).toEqual({ open: true, onScreen: true });
+
+ act(() => paneVisibilityStore.request('editor', false));
+ expect(editorArea.getAttribute('data-editor-visible')).toBe('false');
+ expect(paneVisibilityStore.getSnapshot().editor).toEqual({ open: false, onScreen: false });
+
+ act(() => paneVisibilityStore.request('editor', true));
+ expect(editorArea.getAttribute('data-editor-visible')).toBe('true');
+ expect(paneVisibilityStore.getSnapshot().editor).toEqual({ open: true, onScreen: true });
+ });
+
+ test('a single-file window keeps its Editor return destination and restricts Hide', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = {
+ ...desk.stub,
+ config: { ...desk.stub.config, singleFile: true },
+ };
+ const { EditorPane } = await import('./EditorPane');
+ const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
+ render(
+ <SingleFileModeProvider>
+ <EditorPane />
+ </SingleFileModeProvider>,
+ );
+ await act(async () => {});
+
+ expect(paneVisibilityStore.getSnapshot().editor).toEqual({ open: true, onScreen: true });
+ act(() => paneVisibilityStore.request('editor', false));
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('true');
+ });
+
+ test('a narrow single-file window rejects an empty restored selection', async () => {
+ const originalMatchMedia = window.matchMedia;
+ const narrowQuery = originalMatchMedia('(width < 48rem)');
+ Object.defineProperty(narrowQuery, 'matches', { configurable: true, value: true });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) =>
+ query === '(width < 48rem)' ? narrowQuery : originalMatchMedia(query),
+ });
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = {
+ ...desk.stub,
+ config: { ...desk.stub.config, singleFile: true },
+ };
+ const key = narrowWorkspaceSessionKey('/tmp/project', 'desktop');
+ sessionStorage.setItem(key, JSON.stringify({ version: 1, selected: null }));
+
+ try {
+ const { EditorPane } = await import('./EditorPane');
+ const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
+ render(
+ <SingleFileModeProvider>
+ <EditorPane />
+ </SingleFileModeProvider>,
+ );
+ await act(async () => {});
+
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('true');
+ } finally {
+ sessionStorage.removeItem(key);
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: originalMatchMedia,
+ });
+ }
+ });
+
+ test('delayed browser single-file configuration replaces an empty restored selection', async () => {
+ const originalMatchMedia = window.matchMedia;
+ const originalFetch = globalThis.fetch;
+ const narrowQuery = originalMatchMedia('(width < 48rem)');
+ Object.defineProperty(narrowQuery, 'matches', { configurable: true, value: true });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) =>
+ query === '(width < 48rem)' ? narrowQuery : originalMatchMedia(query),
+ });
+ let resolveConfig: (response: Response) => void = () => {};
+ globalThis.fetch = vi.fn((input: RequestInfo | URL) =>
+ String(input) === '/api/config'
+ ? new Promise<Response>((resolve) => {
+ resolveConfig = resolve;
+ })
+ : Promise.resolve(new Response(null, { status: 404 })),
+ );
+ const key = narrowWorkspaceSessionKey('/tmp/project', 'web');
+ sessionStorage.setItem(key, JSON.stringify({ version: 1, selected: null }));
+
+ try {
+ const { EditorPane } = await import('./EditorPane');
+ const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
+ render(
+ <SingleFileModeProvider>
+ <EditorPane />
+ </SingleFileModeProvider>,
+ );
+ await act(async () => {});
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('false');
+
+ await act(async () => {
+ resolveConfig(new Response(JSON.stringify({ singleFile: true }), { status: 200 }));
+ });
+ expect(screen.getByTestId('editor-area').getAttribute('data-editor-visible')).toBe('true');
+ } finally {
+ sessionStorage.removeItem(key);
+ globalThis.fetch = originalFetch;
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: originalMatchMedia,
+ });
+ }
+ });
+
+ test('a pane hiding while the editor is hidden sends focus to the header Editor button, not the page', async () => {
+ const editorRegion = document.createElement('div');
+ editorRegion.tabIndex = -1;
+ document.body.append(editorRegion);
+ reportedPlacements = {
+ terminal: { container: null, isShowing: false },
+ agents: { container: document.createElement('div'), isShowing: true },
+ editorRegion,
+ };
+ const editorButton = document.createElement('button');
+ editorButton.setAttribute('data-header-pane-button', 'editor');
+ document.body.append(editorButton);
+ await renderEditorPane();
+ act(() => paneVisibilityStore.request('editor', false));
+
+ act(() => sessionsHostFocusRequests.at(-1)?.());
+
+ expect(document.activeElement).toBe(editorButton);
+ editorButton.remove();
+ editorRegion.remove();
+ });
+});
+
+describe('EditorPane saves and restores whether the editor is shown', () => {
+ afterEach(() => {
+ cleanup();
+ localStorage.clear();
+ delete (window as { okDesktop?: unknown }).okDesktop;
+ __resetPaneVisibilityStoreForTests();
+ });
+
+ const editorVisibleAttr = () =>
+ screen.getByTestId('editor-area').getAttribute('data-editor-visible');
+
+ test('desktop: a saved hidden editor comes back hidden, published only once the restore settles', async () => {
+ const desk = makeOkDesktopStub(async () => ({
+ terminalVisible: false,
+ agentPanelVisible: false,
+ editorVisible: false,
+ }));
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ expect(editorVisibleAttr()).toBe('false');
+ expect(desk.viewMenuPushes).toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: true,
+ wideIntent: { editorVisible: true },
+ });
+ });
+
+ test('desktop: a saved hidden editor that lands after the settle bound still comes back hidden', async () => {
+ let release: (value: DockStateResult) => void = () => {};
+ const desk = makeOkDesktopStub(
+ () =>
+ new Promise<DockStateResult>((resolve) => {
+ release = resolve;
+ }),
+ );
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ await renderEditorPane();
+ await act(async () => {
+ vi.advanceTimersByTime(RESTORE_SETTLE_TIMEOUT_MS + 1);
+ });
+ expect(editorVisibleAttr()).toBe('true');
+
+ await act(async () => {
+ release({ terminalVisible: false, agentPanelVisible: false, editorVisible: false });
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+
+ expect(editorVisibleAttr()).toBe('false');
+ expect(desk.viewMenuPushes).toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: true,
+ wideIntent: { editorVisible: true },
+ });
+ });
+
+ async function renderPastTheSettleBound() {
+ let release: (value: DockStateResult) => void = () => {};
+ const desk = makeOkDesktopStub(
+ () =>
+ new Promise<DockStateResult>((resolve) => {
+ release = resolve;
+ }),
+ );
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ await renderEditorPane();
+ await act(async () => {
+ vi.advanceTimersByTime(RESTORE_SETTLE_TIMEOUT_MS + 1);
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(editorVisibleAttr()).toBe('true');
+ const land = (value: DockStateResult) => act(async () => release(value));
+ return { desk, land };
+ }
+
+ test('desktop: a show requested after the settle bound is not undone by a late saved hidden editor', async () => {
+ const { desk, land } = await renderPastTheSettleBound();
+ act(() => paneVisibilityStore.request('editor', true));
+ await land({ terminalVisible: false, agentPanelVisible: false, editorVisible: false });
+
+ expect(editorVisibleAttr()).toBe('true');
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ });
+
+ test('desktop: a hide after the settle bound is not undone by a late saved shown editor', async () => {
+ const { desk, land } = await renderPastTheSettleBound();
+ act(() => paneVisibilityStore.request('editor', false));
+ expect(editorVisibleAttr()).toBe('false');
+ await land({ terminalVisible: false, agentPanelVisible: false, editorVisible: true });
+
+ expect(editorVisibleAttr()).toBe('false');
+ const editorPushes = desk.viewMenuPushes.filter((push) => 'editorVisible' in push);
+ expect(editorPushes.at(-1)).toEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ });
+
+ test("desktop: View menu toggles after the settle bound are the user's choice, and a late saved hidden editor does not undo them", async () => {
+ const { desk, land } = await renderPastTheSettleBound();
+ act(() => desk.dispatchMenuAction('toggle-editor'));
+ expect(editorVisibleAttr()).toBe('false');
+ act(() => desk.dispatchMenuAction('toggle-editor'));
+ expect(editorVisibleAttr()).toBe('true');
+ await land({ terminalVisible: false, agentPanelVisible: false, editorVisible: false });
+
+ expect(editorVisibleAttr()).toBe('true');
+ const editorPushes = desk.viewMenuPushes.filter((push) => 'editorVisible' in push);
+ expect(editorPushes.at(-1)).toEqual({
+ editorVisible: true,
+ wideIntent: { editorVisible: true },
+ });
+ });
+
+ test('desktop: a late saved layout with the editor hidden and chat open keeps the editor shown', async () => {
+ const { desk, land } = await renderPastTheSettleBound();
+ await land({ terminalVisible: false, agentPanelVisible: true, editorVisible: false });
+
+ expect(editorVisibleAttr()).toBe('true');
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ });
+
+ test('desktop: a late saved layout with the editor hidden and the terminal open keeps the editor shown', async () => {
+ const { desk, land } = await renderPastTheSettleBound();
+ await land({ terminalVisible: true, agentPanelVisible: false, editorVisible: false });
+
+ expect(editorVisibleAttr()).toBe('true');
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ terminalVisible: true,
+ wideIntent: { terminalVisible: true },
+ });
+ });
+
+ test('desktop: a record from before the editor field opens with the editor shown', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ expect(editorVisibleAttr()).toBe('true');
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ });
+
+ test('desktop: the editor stays shown through the restore wait, and an open during the wait keeps it shown', async () => {
+ let release: (value: DockStateResult) => void = () => {};
+ const desk = makeOkDesktopStub(
+ () =>
+ new Promise<DockStateResult>((resolve) => {
+ release = resolve;
+ }),
+ );
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ expect(editorVisibleAttr()).toBe('true');
+ expect(paneVisibilityStore.getSnapshot().editor).toEqual({ open: true, onScreen: true });
+ expect(desk.viewMenuPushes.some((push) => 'editorVisible' in push)).toBe(false);
+
+ act(() => paneVisibilityStore.request('editor', true));
+ await act(async () => {
+ release({ terminalVisible: false, agentPanelVisible: false, editorVisible: false });
+ });
+
+ expect(editorVisibleAttr()).toBe('true');
+ });
+
+ test('desktop: a deep link that opens a document before the editor pane mounts keeps a saved-hidden editor shown', async () => {
+ const desk = makeOkDesktopStub(async () => ({
+ terminalVisible: false,
+ agentPanelVisible: false,
+ editorVisible: false,
+ }));
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ revealEditor();
+
+ await renderEditorPane();
+
+ expect(editorVisibleAttr()).toBe('true');
+ expect(desk.viewMenuPushes).not.toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ });
+
+ test('desktop: a reveal in a single-file window leaves nothing behind for a later project window', async () => {
+ const singleFile = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = {
+ ...singleFile.stub,
+ config: { ...singleFile.stub.config, singleFile: true },
+ };
+ const { EditorPane } = await import('./EditorPane');
+ const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
+ render(
+ <SingleFileModeProvider>
+ <EditorPane />
+ </SingleFileModeProvider>,
+ );
+ await act(async () => {});
+ act(() => revealEditor());
+ cleanup();
+
+ const project = makeOkDesktopStub(async () => ({
+ terminalVisible: false,
+ agentPanelVisible: false,
+ editorVisible: false,
+ }));
+ (window as { okDesktop?: unknown }).okDesktop = project.stub;
+ await renderEditorPane();
+
+ expect(editorVisibleAttr()).toBe('false');
+ });
+
+ test('desktop: a document opened during the restore wait keeps a saved-hidden editor shown', async () => {
+ let release: (value: DockStateResult) => void = () => {};
+ const desk = makeOkDesktopStub(
+ () =>
+ new Promise<DockStateResult>((resolve) => {
+ release = resolve;
+ }),
+ );
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ act(() => revealEditor());
+ await act(async () => {
+ release({ terminalVisible: false, agentPanelVisible: false, editorVisible: false });
+ });
+
+ expect(editorVisibleAttr()).toBe('true');
+ });
+
+ test('desktop: every pane saved hidden reopens to nothing shown', async () => {
+ const desk = makeOkDesktopStub(async () => ({
+ terminalVisible: false,
+ agentPanelVisible: false,
+ editorVisible: false,
+ }));
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: { open: false, onScreen: false },
+ agents: { open: false, onScreen: false },
+ terminal: { open: false, onScreen: false },
+ });
+ });
+
+ test('desktop: the View menu toggle hides and shows the editor and publishes the level', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ act(() => desk.dispatchMenuAction('toggle-editor'));
+ expect(editorVisibleAttr()).toBe('false');
+ expect(desk.viewMenuPushes).toContainEqual({
+ editorVisible: false,
+ wideIntent: { editorVisible: false },
+ });
+ const pushesWhileHidden = desk.viewMenuPushes.length;
+ act(() => desk.dispatchMenuAction('toggle-editor'));
+ expect(editorVisibleAttr()).toBe('true');
+ expect(desk.viewMenuPushes.slice(pushesWhileHidden)).toContainEqual({
+ editorVisible: true,
+ wideIntent: { editorVisible: true },
+ });
+ });
+
+ test('web: the editor level survives a reload in both directions, under its own key', async () => {
+ localStorage.setItem('ok-editor-visible-v1', 'false');
+ await renderEditorPane();
+ expect(editorVisibleAttr()).toBe('false');
+
+ act(() => paneVisibilityStore.request('editor', true));
+ cleanup();
+ await renderEditorPane();
+ expect(editorVisibleAttr()).toBe('true');
+
+ act(() => paneVisibilityStore.request('editor', false));
+ cleanup();
+ await renderEditorPane();
+ expect(editorVisibleAttr()).toBe('false');
+ expect(localStorage.getItem('ok-editor-visible-v1')).toBe('false');
+ });
+});
+
+describe('EditorPane mode switch promotes the preview tab', () => {
+ afterEach(() => {
+ cleanup();
+ delete (window as { okDesktop?: unknown }).okDesktop;
+ promotePreviewTabMock.mockClear();
+ activeProvider = undefined;
+ clearPendingSourceNavigationsForTest();
+ });
+
+ function pressModeToggle() {
+ act(() => {
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ code: 'KeyM',
+ key: 'm',
+ altKey: true,
+ metaKey: true,
+ ctrlKey: true,
+ bubbles: true,
+ }),
+ );
+ });
+ }
+
+ test('flipping a doc between source and WYSIWYG promotes its tab', async () => {
+ activeProvider = { document: new Y.Doc() };
+ await renderEditorPane();
+
+ pressModeToggle();
+
+ expect(promotePreviewTabMock).toHaveBeenCalledWith('docs/notes');
+ });
+
+ test('a mode flip after the provider changes reads the current document', async () => {
+ const firstDocument = new Y.Doc();
+ const secondDocument = new Y.Doc();
+ const firstSource = vi.spyOn(firstDocument, 'getText');
+ const secondSource = vi.spyOn(secondDocument, 'getText');
+ activeProvider = { document: firstDocument };
+ const view = await renderEditorPane();
+
+ pressModeToggle();
+ expect(firstSource).toHaveBeenCalledWith('source');
+
+ activeProvider = { document: secondDocument };
+ const { EditorPane } = await import('./EditorPane');
+ act(() => view.rerender(<EditorPane />));
+ firstSource.mockClear();
+ secondSource.mockClear();
+ pressModeToggle();
+
+ expect(secondSource).toHaveBeenCalledWith('source');
+ expect(firstSource).not.toHaveBeenCalled();
+ expect(promotePreviewTabMock).toHaveBeenCalledTimes(2);
+ expect(promotePreviewTabMock).toHaveBeenNthCalledWith(2, 'docs/notes');
+ });
+
+ test('a flip with no provider yet promotes nothing', async () => {
+ activeProvider = undefined;
+ await renderEditorPane();
+
+ pressModeToggle();
+
+ expect(promotePreviewTabMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('EditorPane auth prompts', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test.each([
+ { requested: 'identity', identityPrompt: 'true' },
+ { requested: 'auth', identityPrompt: 'false' },
+ ] as const)(
+ 'a $requested request from outside the pane opens the auth modal at that step',
+ async ({ requested, identityPrompt }) => {
+ const { authPromptStore } = await import('@/lib/auth-prompt-store');
+ await renderEditorPane();
+ expect(screen.getByTestId('auth-modal').getAttribute('data-open')).toBe('false');
+
+ await act(async () => {
+ authPromptStore.request(requested);
+ });
+
+ const modal = screen.getByTestId('auth-modal');
+ expect(modal.getAttribute('data-open')).toBe('true');
+ expect(modal.getAttribute('data-identity-prompt')).toBe(identityPrompt);
+ expect(authPromptStore.getSnapshot()).toBeNull();
+ },
+ );
+
+ test('a request that names no step opens the sign-in step', async () => {
+ const { authPromptStore } = await import('@/lib/auth-prompt-store');
+ await renderEditorPane();
+
+ await act(async () => {
+ authPromptStore.request();
+ });
+
+ const modal = screen.getByTestId('auth-modal');
+ expect(modal.getAttribute('data-open')).toBe('true');
+ expect(modal.getAttribute('data-identity-prompt')).toBe('false');
});
});
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 4e4c456d0..1a3f127eb 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -3,7 +3,17 @@ import type { AttachmentPart } from '@inkeep/open-knowledge-core/acp/thread-prot
import { isEditableTextDocFile } from '@inkeep/open-knowledge-core/constants/code-languages';
import type { TerminalCli, TerminalLaunchCommand } from '@inkeep/open-knowledge-core/handoff';
import type { TerminalPlacement } from '@inkeep/open-knowledge-core/terminal-layout';
-import { lazy, Suspense, useEffect, useEffectEvent, useRef, useState } from 'react';
+import {
+ lazy,
+ type ReactNode,
+ Suspense,
+ useEffect,
+ useEffectEvent,
+ useLayoutEffect,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react';
import { getEditorForDoc } from '@/editor/active-editor';
import { EmojiInsertPopover } from '@/editor/components/EmojiInsertPopover';
import { TagDialog } from '@/editor/components/TagDialog';
@@ -21,23 +31,43 @@ import { useInstalledClis } from '@/hooks/use-installed-clis';
import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';
import { useSyncAuthPrompt } from '@/hooks/use-sync-auth-prompt';
import { useWorktreeAutoSyncNotice } from '@/hooks/use-worktree-autosync-notice';
+import { LAUNCHER_KIND_PANE } from '@/lib/acp/launcher-selection';
+import { usePreferredSessionSelection } from '@/lib/acp/use-preferred-session-selection';
+import type { AuthPromptStep } from '@/lib/auth-prompt-store';
+import { loadBoolPref, saveBoolPref } from '@/lib/bool-pref';
import { useConfigContext } from '@/lib/config-provider';
import { readWebDockSessionOrder } from '@/lib/dock-session-persistence';
+import { focusAwayFromHiddenEditor } from '@/lib/editor-hidden-focus';
import { matchesKeyboardShortcut, matchesRendererShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import {
+ isExplicitInitialDocumentNavigation,
+ narrowWorkspaceSessionKey,
+ readNarrowWorkspaceSession,
+ writeNarrowWorkspaceSession,
+} from '@/lib/narrow-workspace-session';
import { isNoteWindow } from '@/lib/note-window-mode';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
+import {
+ assertNeverPaneId,
+ isPaneId,
+ type PaneId,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
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';
import { useSyncStatus } from '@/presence/use-sync-status';
import { AuthModal } from './AuthModal';
import { AutoSyncOnboardingDialog } from './AutoSyncOnboardingDialog';
import { resolveAutoSyncOnboarding } from './auto-sync-onboarding-gate';
import { type PanelTab, TABS } from './DocPanel';
-import { EditorArea, type SessionPlacements } from './EditorArea';
+import { EditorArea, type EditorAreaHandle, type SessionPlacements } from './EditorArea';
import { EditorHeader } from './EditorHeader';
import { EditorModeToggle } from './EditorModeToggle';
import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';
@@ -95,6 +125,275 @@ export interface ThreadLaunchIntent {
export type EditorMode = EditorModeValue;
+type ModeChangeState = {
+ docName: string | null;
+ provider: HocuspocusProvider | null;
+ mode: EditorModeValue;
+ setMode: (mode: EditorModeValue) => void;
+ setPersistedMode: (mode: EditorModeValue) => void;
+};
+
+function useModeChangeHandler(state: ModeChangeState) {
+ const current = useRef(state);
+ useLayoutEffect(() => {
+ current.current = state;
+ });
+ const [handleModeChange] = useState(() => (mode: EditorModeValue) => {
+ const currentState = current.current;
+ if (currentState.docName && currentState.provider && currentState.mode !== mode) {
+ captureModeSwitchAnchor({
+ from: currentState.mode,
+ to: mode,
+ docName: currentState.docName,
+ ytext: currentState.provider.document.getText('source'),
+ });
+ requestPreviewTabPromotion(currentState.docName);
+ }
+ currentState.setMode(mode);
+ currentState.setPersistedMode(mode);
+ });
+ return handleModeChange;
+}
+
+type PaneSelectionState = {
+ exclusive: boolean;
+ readyNarrowSessionKey: string | null;
+ narrowSessionKey: string | null;
+ narrowSelection: PaneId | null;
+ agentsVisible: boolean;
+ terminalAvailable: boolean;
+ terminalVisible: boolean;
+ lastInteractedPaneRef: { current: PaneId | null };
+ narrowRecentPanesRef: { current: PaneId[] };
+ narrowHiddenPanesRef: { current: Set<PaneId> };
+ narrowInteractedSinceMountRef: { current: boolean };
+ setNarrowSelection: (selected: PaneId | null) => void;
+};
+
+type NarrowRecordState = Pick<
+ PaneSelectionState,
+ | 'exclusive'
+ | 'readyNarrowSessionKey'
+ | 'narrowSessionKey'
+ | 'lastInteractedPaneRef'
+ | 'narrowRecentPanesRef'
+ | 'narrowHiddenPanesRef'
+>;
+
+function persistNarrowSessionForState(state: NarrowRecordState, selected: PaneId | null) {
+ if (
+ !state.exclusive ||
+ state.readyNarrowSessionKey !== state.narrowSessionKey ||
+ state.narrowSessionKey === null
+ )
+ return;
+ writeNarrowWorkspaceSession(state.narrowSessionKey, {
+ selected,
+ lastInteracted: state.lastInteractedPaneRef.current,
+ recent: state.narrowRecentPanesRef.current,
+ hidden: [...state.narrowHiddenPanesRef.current],
+ });
+}
+
+function selectPaneForState(state: PaneSelectionState, pane: PaneId) {
+ state.narrowInteractedSinceMountRef.current = true;
+ state.lastInteractedPaneRef.current = pane;
+ state.narrowHiddenPanesRef.current.delete(pane);
+ state.narrowRecentPanesRef.current = [
+ pane,
+ ...state.narrowRecentPanesRef.current.filter((recent) => recent !== pane),
+ ];
+ if (state.exclusive) {
+ state.setNarrowSelection(pane);
+ persistNarrowSessionForState(state, pane);
+ }
+}
+
+function hidePaneForState(state: PaneSelectionState, pane: PaneId) {
+ state.narrowInteractedSinceMountRef.current = true;
+ state.narrowHiddenPanesRef.current.add(pane);
+ if (!state.exclusive) return;
+ if (state.narrowSelection !== pane) {
+ persistNarrowSessionForState(state, state.narrowSelection);
+ return;
+ }
+ if (pane !== 'editor') {
+ selectPaneForState(state, 'editor');
+ return;
+ }
+ const eligible = (candidate: PaneId) =>
+ candidate !== 'editor' &&
+ !state.narrowHiddenPanesRef.current.has(candidate) &&
+ (candidate === 'agents'
+ ? state.agentsVisible || state.narrowRecentPanesRef.current.includes('agents')
+ : state.terminalAvailable &&
+ (state.terminalVisible || state.narrowRecentPanesRef.current.includes('terminal')));
+ const fallbackOrder: readonly PaneId[] = [
+ ...state.narrowRecentPanesRef.current,
+ 'agents',
+ 'terminal',
+ ];
+ const next = fallbackOrder.find(eligible);
+ if (next === undefined) {
+ state.setNarrowSelection(null);
+ persistNarrowSessionForState(state, null);
+ return;
+ }
+ selectPaneForState(state, next);
+}
+
+type PreferredRequestCancellationState = {
+ kind: ReturnType<typeof usePreferredSessionSelection>['kind'];
+ ownerRef: { current: { pending: number } };
+};
+
+function cancelPendingPreferredSessionsForState(
+ state: PreferredRequestCancellationState,
+ pane: PaneId,
+) {
+ if (LAUNCHER_KIND_PANE[state.kind] === pane) {
+ state.ownerRef.current.pending = 0;
+ }
+}
+
+type PaneVisibilityState = {
+ selection: PaneSelectionState;
+ cancellation: PreferredRequestCancellationState;
+ setAgentsVisible: (visible: boolean) => void;
+ setTerminalVisible: (visible: boolean) => void;
+};
+
+function usePaneVisibilityHandlers(state: PaneVisibilityState) {
+ const current = useRef(state);
+ useLayoutEffect(() => {
+ current.current = state;
+ });
+ const [selectPane] = useState(() => (pane: PaneId) => {
+ selectPaneForState(current.current.selection, pane);
+ });
+ const [hidePane] = useState(() => (pane: PaneId) => {
+ hidePaneForState(current.current.selection, pane);
+ });
+ const [applyPaneRequest] = useState(() => (pane: PaneId, open: boolean) => {
+ const currentState = current.current;
+ if (open) {
+ selectPaneForState(currentState.selection, pane);
+ return;
+ }
+ cancelPendingPreferredSessionsForState(currentState.cancellation, pane);
+ hidePaneForState(currentState.selection, pane);
+ });
+ const [handleAgentsVisibleChange] = useState(
+ () => (visible: boolean, reason?: 'session-close') => {
+ const currentState = current.current;
+ const selection = currentState.selection;
+ if (!visible && reason !== 'session-close')
+ cancelPendingPreferredSessionsForState(currentState.cancellation, 'agents');
+ if (!selection.exclusive) {
+ if (visible) selectPaneForState(selection, 'agents');
+ else hidePaneForState(selection, 'agents');
+ currentState.setAgentsVisible(visible);
+ return;
+ }
+ if (reason === 'session-close') currentState.setAgentsVisible(false);
+ if (visible) selectPaneForState(selection, 'agents');
+ else hidePaneForState(selection, 'agents');
+ },
+ );
+ const [handleTerminalVisibleChange] = useState(
+ () => (visible: boolean, reason?: 'session-close') => {
+ const currentState = current.current;
+ const selection = currentState.selection;
+ if (!visible && reason !== 'session-close')
+ cancelPendingPreferredSessionsForState(currentState.cancellation, 'terminal');
+ if (!selection.exclusive) {
+ if (visible && selection.terminalAvailable) selectPaneForState(selection, 'terminal');
+ else if (!visible) hidePaneForState(selection, 'terminal');
+ currentState.setTerminalVisible(visible);
+ return;
+ }
+ if (reason === 'session-close') currentState.setTerminalVisible(false);
+ if (visible && selection.terminalAvailable) selectPaneForState(selection, 'terminal');
+ else if (!visible) hidePaneForState(selection, 'terminal');
+ },
+ );
+ return {
+ selectPane,
+ hidePane,
+ applyPaneRequest,
+ handleAgentsVisibleChange,
+ handleTerminalVisibleChange,
+ };
+}
+
+type SelectionHandoffState = {
+ activeDocName: string | null;
+ editingSurface: ReturnType<typeof editingSurfaceFor>;
+ effectiveEditorVisible: boolean;
+};
+
+function useSelectionHandoffHandlers(state: SelectionHandoffState) {
+ const current = useRef(state);
+ useLayoutEffect(() => {
+ current.current = state;
+ });
+ const [sendSelectionToTerminal] = useState(() => (newTab: boolean, target?: 'agents') => {
+ const { activeDocName, editingSurface, effectiveEditorVisible } = current.current;
+ if (!effectiveEditorVisible || activeDocName == null) return false;
+ const snapshot = getSelectionContext(activeDocName, editingSurface);
+ const selectionMarkdown = snapshot?.markdown ?? '';
+ if (selectionMarkdown.trim() === '') return false;
+ const staged = `${composeTerminalSelectionPaste(activeDocName, selectionMarkdown)}\n\n`;
+ requestActiveTerminalInput(staged, { newTab, submit: false, target });
+ return true;
+ });
+ const [sendSelectionToAgents] = useState(() => () => sendSelectionToTerminal(false, 'agents'));
+ return { sendSelectionToTerminal, sendSelectionToAgents };
+}
+
+type PaneExtentPublisherState = {
+ editorAreaRef: { current: EditorAreaHandle | null };
+ editorVisible: boolean;
+ agentsVisible: boolean;
+ terminalVisible: boolean;
+ terminalAvailable: boolean;
+ noteWindow: boolean;
+ exclusive: boolean;
+};
+
+function usePaneExtentPublisher(state: PaneExtentPublisherState) {
+ const current = useRef(state);
+ useLayoutEffect(() => {
+ current.current = state;
+ });
+ const [publish] = useState(() => () => {
+ const latest = current.current;
+ const onScreen = latest.editorAreaRef.current?.panesOnScreen() ?? {
+ editor: latest.editorVisible,
+ agents: false,
+ terminal: false,
+ };
+ paneVisibilityStore.publish(
+ {
+ editor: latest.noteWindow
+ ? null
+ : { open: latest.editorVisible, onScreen: latest.editorVisible },
+ agents: latest.noteWindow
+ ? null
+ : { open: latest.agentsVisible, onScreen: latest.agentsVisible && onScreen.agents },
+ terminal: latest.terminalAvailable
+ ? {
+ open: latest.terminalVisible,
+ onScreen: latest.terminalVisible && onScreen.terminal,
+ }
+ : null,
+ },
+ latest.exclusive,
+ );
+ });
+ return publish;
+}
+
function NoteWindowModeToggle({
provider,
editorMode,
@@ -114,6 +413,49 @@ function NoteWindowModeToggle({
);
}
+type WorkspaceHeaderState = {
+ noteWindow: boolean;
+ activeDocName: string | null;
+ activeProvider: HocuspocusProvider | null;
+ editorMode: EditorModeValue;
+ onModeChange: (mode: EditorModeValue) => void;
+};
+
+function WorkspaceHeader({
+ tabs,
+ trailing,
+ state,
+}: {
+ tabs: ReactNode;
+ trailing: ReactNode;
+ state: WorkspaceHeaderState;
+}) {
+ return (
+ <EditorHeader
+ trailing={trailing}
+ noteModeToggle={
+ state.noteWindow &&
+ state.activeDocName !== null &&
+ !isEditableTextDocFile(state.activeDocName) ? (
+ <NoteWindowModeToggle
+ provider={state.activeProvider}
+ editorMode={state.editorMode}
+ onModeChange={state.onModeChange}
+ />
+ ) : null
+ }
+ >
+ {tabs}
+ </EditorHeader>
+ );
+}
+
+function createWorkspaceHeaderRenderer(state: WorkspaceHeaderState) {
+ return (tabs: ReactNode, chrome: { readonly trailing: ReactNode }) => (
+ <WorkspaceHeader tabs={tabs} trailing={chrome.trailing} state={state} />
+ );
+}
+
interface RestoreVisibilityGate {
pendingWithhold: boolean;
levelEstablished: boolean;
@@ -121,6 +463,18 @@ interface RestoreVisibilityGate {
}
const RESTORE_UNESTABLISHED_LEVEL = false;
+const WEB_EDITOR_VISIBLE_KEY = 'ok-editor-visible-v1';
+const NARROW_WORKSPACE_QUERY = '(width < 48rem)';
+
+function subscribeNarrowWorkspace(listener: () => void): () => void {
+ const query = window.matchMedia(NARROW_WORKSPACE_QUERY);
+ query.addEventListener('change', listener);
+ return () => query.removeEventListener('change', listener);
+}
+
+function narrowWorkspaceSnapshot(): boolean {
+ return window.matchMedia(NARROW_WORKSPACE_QUERY).matches;
+}
function makeRestoreVisibilityGate(mountLevel: boolean): RestoreVisibilityGate {
return { pendingWithhold: false, levelEstablished: false, lastLevel: mountLevel };
@@ -150,29 +504,87 @@ function consumeRestoreVisibilityGate(gate: { current: RestoreVisibilityGate }):
return gate.current.levelEstablished;
}
-interface EditorPaneProps {
- onOpenSearch?: () => void;
-}
-
-export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
+export function EditorPane() {
const [persistedMode, setPersistedMode] = useEditorMode();
const [editorMode, setEditorMode] = useState<EditorMode>(persistedMode);
const [authModalOpen, setAuthModalOpen] = useState(false);
- const [authInitialStep, setAuthInitialStep] = useState<'auth' | 'identity'>('auth');
+ const [authInitialStep, setAuthInitialStep] = useState<AuthPromptStep>('auth');
const syncStatus = useGitSyncStatus();
- useSyncAuthPrompt(syncStatus?.remote, () => {
- setAuthInitialStep('auth');
+ useSyncAuthPrompt(syncStatus?.remote, (step) => {
+ setAuthInitialStep(step);
setAuthModalOpen(true);
});
const [activeTab, setActiveTab] = useState<PanelTab>(TABS[0].id);
const [autoSyncOnboardingDismissed, setAutoSyncOnboardingDismissed] = useState(false);
const desktopBridge = typeof window !== 'undefined' ? (window.okDesktop ?? null) : null;
const noteWindow = isNoteWindow();
+ const singleFile = useSingleFileMode();
+ const workspace = useWorkspace();
+ const belowMainBreakpoint = useSyncExternalStore(
+ subscribeNarrowWorkspace,
+ narrowWorkspaceSnapshot,
+ () => false,
+ );
+ const exclusive = belowMainBreakpoint && !noteWindow;
+ const [narrowSelection, setNarrowSelection] = useState<PaneId | null>('editor');
+ const [readyNarrowSessionKey, setReadyNarrowSessionKey] = useState<string | null>(null);
+ const lastInteractedPaneRef = useRef<PaneId | null>(null);
+ const narrowRecentPanesRef = useRef<PaneId[]>([]);
+ const narrowHiddenPanesRef = useRef<Set<PaneId>>(new Set());
+ const narrowInteractedSinceMountRef = useRef(false);
+ const loadedNarrowSessionKeyRef = useRef<string | null>(null);
+ const initialExclusiveRef = useRef(exclusive);
+ const [layoutRestoreFocusHold, setLayoutRestoreFocusHold] = useState(false);
+ const layoutRestoreFocusHoldRef = useRef(false);
+ const wasExclusiveRef = useRef(exclusive);
+ const editorToggleable = !noteWindow && !singleFile;
+ const [editorShown, setEditorShown] = useState(() =>
+ desktopBridge == null ? loadBoolPref(WEB_EDITOR_VISIBLE_KEY, true) : true,
+ );
+ const editorChosenSinceMountRef = useRef(false);
+ const editorVisible = !editorToggleable || editorShown;
const terminalAvailable =
!noteWindow &&
desktopBridge != null &&
desktopBridge.terminal != null &&
desktopBridge.config.ptyAvailable === true;
+ const narrowSessionKey =
+ workspace === null
+ ? null
+ : narrowWorkspaceSessionKey(workspace.contentDir, desktopBridge === null ? 'web' : 'desktop');
+ const preferredSessionOwnerKey = workspace?.contentDir ?? null;
+ useEffect(() => {
+ if (narrowSessionKey === null || loadedNarrowSessionKeyRef.current === narrowSessionKey) return;
+ loadedNarrowSessionKeyRef.current = narrowSessionKey;
+ if (initialExclusiveRef.current && !narrowInteractedSinceMountRef.current) {
+ if (isExplicitInitialDocumentNavigation()) {
+ lastInteractedPaneRef.current = 'editor';
+ setNarrowSelection('editor');
+ } else {
+ const stored = readNarrowWorkspaceSession(narrowSessionKey, terminalAvailable);
+ if (stored !== undefined) {
+ lastInteractedPaneRef.current = stored.lastInteracted;
+ narrowRecentPanesRef.current = stored.recent;
+ narrowHiddenPanesRef.current = new Set(stored.hidden);
+ setNarrowSelection(singleFile && stored.selected === null ? 'editor' : stored.selected);
+ }
+ }
+ }
+ setReadyNarrowSessionKey(narrowSessionKey);
+ }, [narrowSessionKey, terminalAvailable, singleFile]);
+ useEffect(() => {
+ persistNarrowSessionForState(
+ {
+ exclusive,
+ readyNarrowSessionKey,
+ narrowSessionKey,
+ lastInteractedPaneRef,
+ narrowRecentPanesRef,
+ narrowHiddenPanesRef,
+ },
+ narrowSelection,
+ );
+ }, [exclusive, readyNarrowSessionKey, narrowSessionKey, narrowSelection]);
const [terminalVisible, setTerminalVisible] = useState<boolean>(RESTORE_UNESTABLISHED_LEVEL);
const [terminalRestoreRevealNonce, setTerminalRestoreRevealNonce] = useState(0);
const [terminalPlacement, setTerminalPlacement] = useState<TerminalPlacement>(() =>
@@ -190,7 +602,100 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
? (readWebDockSessionOrder('agents')?.agentPanelVisible ?? false)
: RESTORE_UNESTABLISHED_LEVEL,
);
+ useLayoutEffect(() => {
+ if (exclusive && !wasExclusiveRef.current) {
+ const last = lastInteractedPaneRef.current;
+ const candidates: readonly PaneId[] = [
+ ...(last === null ? [] : [last]),
+ ...narrowRecentPanesRef.current,
+ 'editor',
+ ...(agentsVisible ? ['agents' as const] : []),
+ ...(terminalVisible ? ['terminal' as const] : []),
+ ];
+ const next = candidates.find(
+ (pane) =>
+ !narrowHiddenPanesRef.current.has(pane) && (pane !== 'terminal' || terminalAvailable),
+ );
+ setNarrowSelection(next ?? null);
+ } else if (!exclusive && wasExclusiveRef.current) {
+ layoutRestoreFocusHoldRef.current = true;
+ setLayoutRestoreFocusHold(true);
+ }
+ wasExclusiveRef.current = exclusive;
+ }, [exclusive, terminalAvailable, agentsVisible, terminalVisible]);
+ const effectiveEditorVisible = exclusive ? narrowSelection === 'editor' : editorVisible;
+ const effectiveAgentsVisible = exclusive ? narrowSelection === 'agents' : agentsVisible;
+ const effectiveTerminalVisible = exclusive
+ ? narrowSelection === 'terminal' && terminalAvailable
+ : terminalVisible;
const installedClis = useInstalledClis();
+ const preferredSessionSelection = usePreferredSessionSelection({
+ installedClis,
+ terminalAvailable,
+ threadsAvailable: true,
+ });
+ const lastPreferredSessionKindRef = useRef(preferredSessionSelection.kind);
+ const preferredRequestOwnerRef = useRef<{
+ key: string | null;
+ hasKnownKey: boolean;
+ pending: number;
+ active: boolean;
+ readyCallback: (() => void) | null;
+ }>({
+ key: preferredSessionOwnerKey,
+ hasKnownKey: preferredSessionOwnerKey !== null,
+ pending: 0,
+ active: true,
+ readyCallback: null,
+ });
+ useLayoutEffect(() => {
+ const owner = preferredRequestOwnerRef.current;
+ if (preferredSessionOwnerKey === null) {
+ if (owner.hasKnownKey) {
+ owner.key = null;
+ owner.hasKnownKey = false;
+ owner.pending = 0;
+ }
+ } else if (!owner.hasKnownKey) {
+ owner.key = preferredSessionOwnerKey;
+ owner.hasKnownKey = true;
+ } else if (owner.key !== preferredSessionOwnerKey) {
+ owner.key = preferredSessionOwnerKey;
+ owner.pending = 0;
+ }
+ }, [preferredSessionOwnerKey]);
+ useLayoutEffect(() => {
+ const owner = preferredRequestOwnerRef.current;
+ owner.active = true;
+ return () => {
+ owner.active = false;
+ owner.pending = 0;
+ owner.readyCallback = null;
+ };
+ }, []);
+ const drainPreferredSessions = useEffectEvent(() => {
+ const owner = preferredRequestOwnerRef.current;
+ if (!owner.active) return;
+ while (owner.pending > 0) {
+ owner.pending -= 1;
+ if (!requestPreferredSession()) {
+ owner.pending += 1;
+ return;
+ }
+ }
+ });
+ const onPreferredSessionHostReady = () => {
+ if (preferredRequestOwnerRef.current.readyCallback !== onPreferredSessionHostReady) return;
+ drainPreferredSessions();
+ };
+ useLayoutEffect(() => {
+ preferredRequestOwnerRef.current.readyCallback = onPreferredSessionHostReady;
+ });
+ useEffect(() => {
+ if (lastPreferredSessionKindRef.current === preferredSessionSelection.kind) return;
+ lastPreferredSessionKindRef.current = preferredSessionSelection.kind;
+ drainPreferredSessions();
+ }, [preferredSessionSelection.kind]);
const [dockRestoreSettled, setDockRestoreSettled] = useState(false);
const restoreRevealRef = useRef(false);
const terminalRestoreGateRef = useRef<RestoreVisibilityGate>(
@@ -199,6 +704,9 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
const agentsRestoreGateRef = useRef<RestoreVisibilityGate>(
makeRestoreVisibilityGate(agentsVisible),
);
+ const editorRestoreGateRef = useRef<RestoreVisibilityGate>(
+ makeRestoreVisibilityGate(editorShown),
+ );
const [terminalLaunch, setTerminalLaunch] = useState<TerminalLaunchIntent | null>(null);
const [terminalCommand, setTerminalCommand] = useState<{
id: TerminalCommandId;
@@ -213,12 +721,122 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
});
const launchNonceRef = useRef(0);
- function launchNewChat() {
- requestPreferredSession();
+ const editorAreaRef = useRef<EditorAreaHandle>(null);
+ const paneSelectionState: PaneSelectionState = {
+ exclusive,
+ readyNarrowSessionKey,
+ narrowSessionKey,
+ narrowSelection,
+ agentsVisible,
+ terminalAvailable,
+ terminalVisible,
+ lastInteractedPaneRef,
+ narrowRecentPanesRef,
+ narrowHiddenPanesRef,
+ narrowInteractedSinceMountRef,
+ setNarrowSelection,
+ };
+ const preferredCancellationState: PreferredRequestCancellationState = {
+ kind: preferredSessionSelection.kind,
+ ownerRef: preferredRequestOwnerRef,
+ };
+
+ const {
+ selectPane,
+ hidePane,
+ applyPaneRequest,
+ handleAgentsVisibleChange,
+ handleTerminalVisibleChange,
+ } = usePaneVisibilityHandlers({
+ selection: paneSelectionState,
+ cancellation: preferredCancellationState,
+ setAgentsVisible,
+ setTerminalVisible,
+ });
+
+ useEffect(() => {
+ if (exclusive || noteWindow) return;
+ const recordInteraction = (event: Event) => {
+ if (event.type === 'focusin') {
+ if (layoutRestoreFocusHoldRef.current) return;
+ } else if (layoutRestoreFocusHoldRef.current) {
+ layoutRestoreFocusHoldRef.current = false;
+ setLayoutRestoreFocusHold(false);
+ }
+ if (event.type === 'keydown' && event.defaultPrevented) return;
+ if (!(event.target instanceof Element)) return;
+ const card = event.target.closest<HTMLElement>('[data-slot="pane-card"][data-pane]');
+ const pane = card?.getAttribute('data-pane');
+ if (!isPaneId(pane)) return;
+ selectPane(pane);
+ };
+ document.addEventListener('focusin', recordInteraction, true);
+ document.addEventListener('pointerdown', recordInteraction, true);
+ document.addEventListener('keydown', recordInteraction, true);
+ return () => {
+ document.removeEventListener('focusin', recordInteraction, true);
+ document.removeEventListener('pointerdown', recordInteraction, true);
+ document.removeEventListener('keydown', recordInteraction, true);
+ };
+ }, [exclusive, noteWindow, selectPane]);
+
+ useEffect(() => {
+ if (exclusive && singleFile && narrowSelection === null) selectPane('editor');
+ }, [exclusive, singleFile, narrowSelection, selectPane]);
+
+ const publishPaneVisibility = usePaneExtentPublisher({
+ editorAreaRef,
+ editorVisible: effectiveEditorVisible,
+ agentsVisible: effectiveAgentsVisible,
+ terminalVisible: effectiveTerminalVisible,
+ terminalAvailable,
+ noteWindow,
+ exclusive,
+ });
+
+ useLayoutEffect(publishPaneVisibility);
+
+ useLayoutEffect(() => {
+ return paneVisibilityStore.subscribeRequests(({ pane, open }) => {
+ if (noteWindow) return;
+ if (exclusive) {
+ if (pane === 'terminal' && !terminalAvailable) return;
+ 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;
+ applyPaneRequest(pane, open);
+ editorChosenSinceMountRef.current = true;
+ setEditorShown(open);
+ return;
+ case 'agents':
+ applyPaneRequest(pane, open);
+ setAgentsVisible(open);
+ return;
+ case 'terminal':
+ applyPaneRequest(pane, open);
+ if (terminalAvailable) setTerminalVisible(open);
+ return;
+ default:
+ return assertNeverPaneId(pane);
+ }
+ });
+ }, [noteWindow, terminalAvailable, editorToggleable, exclusive, applyPaneRequest]);
+
+ function focusEditorOrFallback() {
+ if (effectiveEditorVisible) placements.editorRegion?.focus();
+ else focusAwayFromHiddenEditor();
}
- function revealAgents() {
- setAgentsVisible(true);
+ function launchNewChat() {
+ if (!requestPreferredSession()) preferredRequestOwnerRef.current.pending += 1;
}
const { projectConfig, projectLocalConfig, projectLocalSynced, projectSynced } =
@@ -226,6 +844,11 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
const { activeDocName, activeProvider } = useDocumentContext();
const editingSurface = editingSurfaceFor(activeDocName, editorMode);
+ const { sendSelectionToTerminal, sendSelectionToAgents } = useSelectionHandoffHandlers({
+ activeDocName,
+ editingSurface,
+ effectiveEditorVisible,
+ });
const autoSyncOnboardingVariant = resolveAutoSyncOnboarding({
autoSyncOnboardingDismissed,
@@ -249,34 +872,44 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
return () => window.removeEventListener(RAW_MDX_NAV_EVENT, onRawMdxNav);
}, [activeDocName]);
- function sendSelectionToTerminal(newTab: boolean, target?: 'agents'): boolean {
- if (activeDocName == null) return false;
- const snapshot = getSelectionContext(activeDocName, editingSurface);
- const selectionMarkdown = snapshot?.markdown ?? '';
- if (selectionMarkdown.trim() === '') return false;
- const staged = `${composeTerminalSelectionPaste(activeDocName, selectionMarkdown)}\n\n`;
- requestActiveTerminalInput(staged, { newTab, submit: false, target });
- return true;
- }
- const sendSelectionToTerminalEvent = useEffectEvent(sendSelectionToTerminal);
- const sendSelectionToAgentsEvent = useEffectEvent(() => sendSelectionToTerminal(false, 'agents'));
const launchNewChatEvent = useEffectEvent(() => launchNewChat());
+ const toggleEditorEvent = useEffectEvent(() => {
+ if (!editorToggleable) return;
+ if (exclusive) {
+ if (effectiveEditorVisible) hidePane('editor');
+ else selectPane('editor');
+ return;
+ }
+ editorChosenSinceMountRef.current = true;
+ if (editorShown) hidePane('editor');
+ else selectPane('editor');
+ setEditorShown(!editorShown);
+ });
+ const toggleAgentsEvent = useEffectEvent(() =>
+ handleAgentsVisibleChange(!effectiveAgentsVisible),
+ );
+ const toggleTerminalEvent = useEffectEvent(() =>
+ handleTerminalVisibleChange(!effectiveTerminalVisible),
+ );
+ const showTerminalEvent = useEffectEvent(() => handleTerminalVisibleChange(true));
useEffect(() => {
if (noteWindow) return;
return subscribeLocalMenuAction((action) => {
if (action === 'toggle-terminal') {
- setTerminalVisible((visible) => !visible);
+ toggleTerminalEvent();
} else if (action === 'move-terminal') {
setTerminalPlacement((placement) => (placement === 'bottom' ? 'right' : 'bottom'));
} else if (action === 'new-terminal') {
- setTerminalVisible(true);
+ showTerminalEvent();
} else if (action === 'toggle-agent-panel') {
- if (sendSelectionToAgentsEvent()) return;
- setAgentsVisible((visible) => !visible);
+ if (sendSelectionToAgents()) return;
+ toggleAgentsEvent();
+ } else if (action === 'toggle-editor') {
+ toggleEditorEvent();
}
});
- }, [noteWindow]);
+ }, [noteWindow, sendSelectionToAgents]);
useEffect(() => {
const hasNativeMenu = window.okDesktop != null;
@@ -285,7 +918,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
if (isOverlayLayerOpen()) return;
if (!terminalAvailable) return;
event.preventDefault();
- setTerminalVisible((visible) => !visible);
+ toggleTerminalEvent();
}
window.addEventListener('keydown', handleKeyDown, { capture: true });
return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
@@ -297,35 +930,39 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
if (!matchesKeyboardShortcut(event, 'toggle-agent-panel')) return;
if (isOverlayLayerOpen()) return;
event.preventDefault();
- if (sendSelectionToAgentsEvent()) return;
- setAgentsVisible((visible) => !visible);
+ if (sendSelectionToAgents()) return;
+ toggleAgentsEvent();
}
window.addEventListener('keydown', handleKeyDown, { capture: true });
return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
- }, []);
+ }, [sendSelectionToAgents]);
useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
if (!matchesKeyboardShortcut(event, 'new-terminal-tab')) return;
if (isOverlayLayerOpen()) return;
event.preventDefault();
- if (!sendSelectionToTerminalEvent(true)) launchNewChatEvent();
+ if (!sendSelectionToTerminal(true)) launchNewChatEvent();
}
window.addEventListener('keydown', handleKeyDown, { capture: true });
return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
- }, []);
+ }, [sendSelectionToTerminal]);
useEffect(() => {
return subscribeToTerminalCommandRequests((id) => {
- setTerminalVisible(true);
+ if (!terminalAvailable) return;
+ selectPane('terminal');
+ if (!exclusive) setTerminalVisible(true);
launchNonceRef.current += 1;
setTerminalCommand({ id, nonce: launchNonceRef.current });
});
- }, []);
+ }, [exclusive, terminalAvailable, selectPane]);
useEffect(() => {
return subscribeToTerminalLaunchRequests((request) => {
- setTerminalVisible(true);
+ if (!terminalAvailable) return;
+ selectPane('terminal');
+ if (!exclusive) setTerminalVisible(true);
launchNonceRef.current += 1;
const nonce = launchNonceRef.current;
const signIn =
@@ -349,11 +986,15 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
},
);
});
- }, []);
+ }, [exclusive, terminalAvailable, selectPane]);
useEffect(() => {
return subscribeToAgentThreadLaunchRequests((detail: AgentThreadLaunchDetail) => {
- setAgentsVisible(true);
+ selectPane('agents');
+ if (!exclusive) {
+ if (agentsVisible) paneVisibilityStore.request('agents', true);
+ else setAgentsVisible(true);
+ }
threadLaunchNonceRef.current += 1;
setThreadLaunch({
agentSource: detail.agentSource,
@@ -365,7 +1006,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
nonce: threadLaunchNonceRef.current,
});
});
- }, []);
+ }, [exclusive, agentsVisible, selectPane]);
useEffect(() => {
if (!terminalVisible) setTerminalLaunch(null);
@@ -376,9 +1017,11 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
noteRestoreVisibilityLevel(terminalRestoreGateRef, terminalVisible);
if (!dockRestoreSettled) return;
if (!consumeRestoreVisibilityGate(terminalRestoreGateRef)) return;
- setViewMenuState({ terminalVisible });
- window.okDesktop.editor.notifyViewMenuStateChanged({ terminalVisible });
- }, [terminalVisible, dockRestoreSettled]);
+ window.okDesktop.editor.notifyViewMenuStateChanged({
+ terminalVisible: effectiveTerminalVisible,
+ wideIntent: { terminalVisible },
+ });
+ }, [terminalVisible, effectiveTerminalVisible, dockRestoreSettled]);
useEffect(() => {
if (window.okDesktop == null) return;
@@ -392,16 +1035,42 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
noteRestoreVisibilityLevel(agentsRestoreGateRef, agentsVisible);
if (!dockRestoreSettled) return;
if (!consumeRestoreVisibilityGate(agentsRestoreGateRef)) return;
- setViewMenuState({ agentPanelVisible: agentsVisible });
- window.okDesktop.editor.notifyViewMenuStateChanged({ agentPanelVisible: agentsVisible });
- }, [agentsVisible, dockRestoreSettled]);
+ window.okDesktop.editor.notifyViewMenuStateChanged({
+ agentPanelVisible: effectiveAgentsVisible,
+ wideIntent: { agentPanelVisible: agentsVisible },
+ });
+ }, [agentsVisible, effectiveAgentsVisible, dockRestoreSettled]);
+
+ useEffect(() => {
+ if (desktopBridge != null || !editorToggleable) return;
+ saveBoolPref(WEB_EDITOR_VISIBLE_KEY, editorShown, true);
+ }, [desktopBridge, editorToggleable, editorShown]);
+
+ useEffect(() => {
+ if (window.okDesktop == null || !editorToggleable) return;
+ noteRestoreVisibilityLevel(editorRestoreGateRef, editorShown);
+ if (!dockRestoreSettled) return;
+ if (!consumeRestoreVisibilityGate(editorRestoreGateRef)) return;
+ window.okDesktop.editor.notifyViewMenuStateChanged({
+ editorVisible: effectiveEditorVisible,
+ wideIntent: { editorVisible: editorShown },
+ });
+ }, [editorShown, effectiveEditorVisible, dockRestoreSettled, editorToggleable]);
+
+ useEffect(() => {
+ setViewMenuState({
+ editorVisible: effectiveEditorVisible,
+ agentPanelVisible: effectiveAgentsVisible,
+ terminalVisible: effectiveTerminalVisible,
+ });
+ }, [effectiveEditorVisible, effectiveAgentsVisible, effectiveTerminalVisible]);
useEffect(() => {
let last: boolean | null = null;
const publish = () => {
const snapshot =
activeDocName === null ? null : getSelectionContext(activeDocName, editingSurface);
- const hasEditorSelection = (snapshot?.markdown ?? '').trim() !== '';
+ const hasEditorSelection = effectiveEditorVisible && (snapshot?.markdown ?? '').trim() !== '';
if (hasEditorSelection === last) return;
last = hasEditorSelection;
setViewMenuState({ hasEditorSelection });
@@ -409,7 +1078,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
};
publish();
return subscribeSelectionContext(publish);
- }, [activeDocName, editingSurface]);
+ }, [activeDocName, editingSurface, effectiveEditorVisible]);
useEffect(() => {
if (noteWindow) {
@@ -428,16 +1097,26 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
abandoned = true;
armRestoreVisibilityGate(terminalRestoreGateRef);
armRestoreVisibilityGate(agentsRestoreGateRef);
+ armRestoreVisibilityGate(editorRestoreGateRef);
console.warn(
- `[dock] dock-state restore exceeded its ${RESTORE_SETTLE_TIMEOUT_MS}ms bound; the agents panel and terminal start closed and only that un-restored level is withheld from the view menu and the dock record, so a later reveal or toggle still publishes`,
+ `[dock] dock-state restore exceeded its ${RESTORE_SETTLE_TIMEOUT_MS}ms bound; the agents panel and terminal start closed and the editor starts shown until the read lands; a read that still lands reveals nothing, and hides the editor only when the saved layout had no pane open and the user has not chosen an editor level since mount; each level still unrestored is withheld from the view menu and the dock record, so a later reveal or toggle still publishes`,
);
setDockRestoreSettled(true);
}, RESTORE_SETTLE_TIMEOUT_MS);
void bridge.terminal
.getDockState()
.then((state) => {
- if (cancelled || abandoned) return;
+ if (cancelled) return;
+ if (abandoned) {
+ const savedLayoutHadNoPaneOpen =
+ state.editorVisible === false &&
+ !state.terminalVisible &&
+ state.agentPanelVisible !== true;
+ if (savedLayoutHadNoPaneOpen && !editorChosenSinceMountRef.current) setEditorShown(false);
+ return;
+ }
setAgentsVisible((current) => (current ? current : state.agentPanelVisible === true));
+ if (!editorChosenSinceMountRef.current) setEditorShown(state.editorVisible !== false);
if (!state.terminalVisible) return;
restoreRevealRef.current = true;
setTerminalRestoreRevealNonce((nonce) => nonce + 1);
@@ -448,9 +1127,10 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
if (!abandoned) {
armRestoreVisibilityGate(terminalRestoreGateRef);
armRestoreVisibilityGate(agentsRestoreGateRef);
+ armRestoreVisibilityGate(editorRestoreGateRef);
}
console.error(
- '[dock] dock-state restore failed; the agents panel and terminal start closed and only that un-restored level is withheld from the view menu and the dock record, so a later reveal or toggle still publishes:',
+ '[dock] dock-state restore failed; the agents panel and terminal start closed and the editor starts shown without its saved state applied; each un-restored level is withheld from the view menu and the dock record, so a later reveal or toggle still publishes:',
err,
);
})
@@ -464,6 +1144,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
window.clearTimeout(restoreDeadline);
resetRestoreVisibilityGate(terminalRestoreGateRef);
resetRestoreVisibilityGate(agentsRestoreGateRef);
+ resetRestoreVisibilityGate(editorRestoreGateRef);
};
}, [noteWindow]);
@@ -480,19 +1161,13 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
useWorktreeAutoSyncNotice();
- function handleModeChange(mode: EditorModeValue) {
- if (activeDocName && activeProvider && editorMode !== mode) {
- captureModeSwitchAnchor({
- from: editorMode,
- to: mode,
- docName: activeDocName,
- ytext: activeProvider.document.getText('source'),
- });
- requestPreviewTabPromotion(activeDocName);
- }
- setEditorMode(mode);
- setPersistedMode(mode);
- }
+ const handleModeChange = useModeChangeHandler({
+ docName: activeDocName,
+ provider: activeProvider,
+ mode: editorMode,
+ setMode: setEditorMode,
+ setPersistedMode,
+ });
const toggleEditorModeEvent = useEffectEvent(() => {
handleModeChange(editorMode === 'source' ? 'wysiwyg' : 'source');
@@ -502,6 +1177,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
const requestViewInSourceEvent = useEffectEvent(() => {
if (!canViewInSource || !activeDocName || !activeProvider) return;
+ revealEditorBeforeActing();
const editor = getEditorForDoc(activeDocName);
if (!editor) return;
requestViewInSource({
@@ -555,47 +1231,32 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
<AgentThreadClientBinder />
</Suspense>
{}
- <div className="flex min-h-0 flex-1 overflow-hidden">
+ <div className="flex min-h-0 flex-1">
<div className="flex min-w-0 flex-1 flex-col">
<EditorArea
+ ref={editorAreaRef}
+ onPaneExtentChange={publishPaneVisibility}
editorMode={editorMode}
onModeChange={handleModeChange}
activeTab={activeTab}
onActiveTabChange={setActiveTab}
terminalBridge={terminalAvailable ? desktopBridge : null}
- terminalVisible={noteWindow ? false : terminalVisible}
+ editorVisible={effectiveEditorVisible}
+ terminalVisible={noteWindow ? false : effectiveTerminalVisible}
terminalPlacement={terminalPlacement}
terminalRightWidth={terminalRightWidth}
- onTerminalVisibleChange={setTerminalVisible}
+ onTerminalVisibleChange={handleTerminalVisibleChange}
onTerminalRightWidthChange={setTerminalRightWidth}
- agentsVisible={noteWindow ? false : agentsVisible}
- onAgentsVisibleChange={setAgentsVisible}
+ agentsVisible={noteWindow ? false : effectiveAgentsVisible}
+ onAgentsVisibleChange={handleAgentsVisibleChange}
onSessionPlacements={setPlacements}
- onRevealAgents={noteWindow ? undefined : revealAgents}
- renderWorkspaceHeader={(tabs) => (
- <EditorHeader
- noteModeToggle={
- noteWindow && activeDocName !== null && !isEditableTextDocFile(activeDocName) ? (
- <NoteWindowModeToggle
- provider={activeProvider}
- editorMode={editorMode}
- onModeChange={handleModeChange}
- />
- ) : null
- }
- onSignIn={() => {
- setAuthInitialStep('auth');
- setAuthModalOpen(true);
- }}
- onSetIdentity={() => {
- setAuthInitialStep('identity');
- setAuthModalOpen(true);
- }}
- onOpenSearch={onOpenSearch}
- >
- {tabs}
- </EditorHeader>
- )}
+ renderWorkspaceHeader={createWorkspaceHeaderRenderer({
+ noteWindow,
+ activeDocName,
+ activeProvider,
+ editorMode,
+ onModeChange: handleModeChange,
+ })}
/>
</div>
</div>
@@ -606,14 +1267,17 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
surface="agents-panel"
bridge={desktopBridge}
terminalCapable={terminalAvailable}
- visible={agentsVisible}
- onVisibleChange={setAgentsVisible}
+ visible={effectiveAgentsVisible}
+ wideVisible={agentsVisible}
+ onVisibleChange={handleAgentsVisibleChange}
+ onPreferredSessionHostReady={onPreferredSessionHostReady}
agentsVisibilityRestoreSettled={desktopBridge == null || dockRestoreSettled}
threadLaunch={threadLaunch}
installedClis={installedClis}
container={placements.agents.container}
isShowing={placements.agents.isShowing}
- onRequestEditorFocus={() => placements.editorRegion?.focus()}
+ revealFocusHold={layoutRestoreFocusHold}
+ onRequestEditorFocus={focusEditorOrFallback}
/>
</Suspense>
)}
@@ -623,18 +1287,19 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
surface="terminal-dock"
terminalPlacement={terminalPlacement}
onTerminalPlacementChange={setTerminalPlacement}
- reserveRightRevealTabGutter={terminalPlacement === 'right' && !agentsVisible}
bridge={desktopBridge}
terminalCapable
- visible={terminalVisible}
+ visible={effectiveTerminalVisible}
terminalRestoreRevealNonce={terminalRestoreRevealNonce}
- onVisibleChange={setTerminalVisible}
+ onVisibleChange={handleTerminalVisibleChange}
+ onPreferredSessionHostReady={onPreferredSessionHostReady}
launch={terminalLaunch}
commandLaunch={terminalCommand}
installedClis={installedClis}
container={placements.terminal.container}
isShowing={placements.terminal.isShowing}
- onRequestEditorFocus={() => placements.editorRegion?.focus()}
+ revealFocusHold={layoutRestoreFocusHold}
+ onRequestEditorFocus={focusEditorOrFallback}
/>
</Suspense>
) : null}
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
index e1f4d2f87..27b439ac6 100644
--- a/packages/app/src/components/EditorTabs.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -1,9 +1,14 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { isMacOS } from '@tiptap/core';
import type { ComponentProps, ReactNode } from 'react';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, onTestFinished, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { assetTabId, folderTabId, skillFileTabId } from '@/editor/editor-tabs';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
expectVisualClassTokens,
@@ -456,19 +461,15 @@ function resetState() {
async function renderEditorTabs({
dropIndicatorIndex = null,
- reserveLeadingChrome = false,
+ leading,
}: {
dropIndicatorIndex?: number | null;
- reserveLeadingChrome?: boolean;
+ leading?: ReactNode;
} = {}) {
const { EditorTabs } = await import('./EditorTabs');
return render(
<TooltipProvider>
- <EditorTabs
- dropIndicatorIndex={dropIndicatorIndex}
- paneId="pane-a"
- reserveLeadingChrome={reserveLeadingChrome}
- />
+ <EditorTabs dropIndicatorIndex={dropIndicatorIndex} paneId="pane-a" leading={leading} />
</TooltipProvider>,
);
}
@@ -896,19 +897,33 @@ describe('EditorTabs runtime behavior', () => {
expectVisualClassTokens(newTabButton.className, ['[-webkit-app-region:no-drag]']);
});
- test('keeps restored-tab chrome alignment immediate', async () => {
- const { container } = await renderEditorTabs({ reserveLeadingChrome: true });
+ test('a leading control sits in the tab row ahead of the tabs, as an ordinary row item', async () => {
+ const { container } = await renderEditorTabs({
+ leading: <button type="button">Files</button>,
+ });
const root = container.firstElementChild as HTMLElement;
-
- expectVisualClassTokens(root.className, [
- 'pl-[calc(var(--editor-header-leading-offset,0px)+var(--editor-header-leading-width,0px)+0.5rem)]',
- ]);
+ const leading = screen.getByRole('button', { name: 'Files' });
+ const firstTab = container.querySelector('[data-editor-tab-sortable]') as HTMLElement;
+
+ expect(leading.parentElement).toBe(root);
+ expect(root.firstElementChild).toBe(leading);
+ expect(
+ leading.compareDocumentPosition(firstTab) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expectVisualClassTokens(root.className, ['flex', 'h-11', 'ps-2']);
expectVisualClassTokensAbsent(root.className, [
- 'motion-safe:group-data-[sidebar-transition-ready]/editor-header:transition-[padding-left]',
- 'motion-safe:transition-[padding-left]',
+ 'pl-[calc(var(--editor-header-leading-offset,0px)+var(--editor-header-leading-width,0px)+0.5rem)]',
+ 'pr-[var(--editor-header-trailing-width,0px)]',
]);
});
+ test('without a leading control the row opens straight onto the tabs', async () => {
+ const { container } = await renderEditorTabs();
+ const root = container.firstElementChild as HTMLElement;
+
+ expect(root.firstElementChild?.hasAttribute('data-editor-tab-overflow-root')).toBe(true);
+ });
+
test('keeps every tab kind at the same wider resting width whether active or inactive', async () => {
const { container } = await renderEditorTabs();
const root = container.firstElementChild as HTMLElement;
@@ -1567,6 +1582,59 @@ describe('EditorTabs runtime behavior', () => {
});
});
+describe('EditorTabs shortcuts with the editor hidden', () => {
+ beforeEach(() => {
+ resetState();
+ __resetPaneVisibilityStoreForTests();
+ });
+
+ afterEach(() => {
+ cleanup();
+ __resetPaneVisibilityStoreForTests();
+ });
+
+ test.each([
+ {
+ shortcut: 'tab-new',
+ keys: () => ({ key: 't', ...primaryShortcutModifier() }),
+ performs: openNewTab,
+ },
+ {
+ shortcut: 'tab-reopen-closed',
+ keys: () => ({ key: 'T', shiftKey: true, ...primaryShortcutModifier() }),
+ performs: reopenClosedTab,
+ },
+ { shortcut: 'tab-next', keys: () => ({ key: 'Tab', ctrlKey: true }), performs: activateTab },
+ {
+ shortcut: 'tab-previous',
+ keys: () => ({ key: 'Tab', ctrlKey: true, shiftKey: true }),
+ performs: activateTab,
+ },
+ {
+ shortcut: 'jump to tab 1',
+ keys: () => ({ key: '1', ...primaryShortcutModifier() }),
+ performs: activateTab,
+ },
+ ])('$shortcut shows a hidden editor before acting', async ({ keys, performs }) => {
+ const log: Array<PaneVisibilityRequest | 'act'> = [];
+ paneVisibilityStore.subscribeRequests((request) => log.push(request));
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ performs.mockImplementation(() => log.push('act'));
+ onTestFinished(() => {
+ performs.mockReset();
+ });
+ await renderEditorTabs();
+
+ fireEvent.keyDown(window, keys());
+
+ expect(log).toEqual([{ pane: 'editor', open: true }, 'act']);
+ });
+});
+
describe('EditorTabs global chords — overlay gate', () => {
beforeEach(() => {
resetState();
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index c6e941dcd..56664b199 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -64,6 +64,7 @@ import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
import { openDocInNoteWindow } from '@/lib/open-note-window';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
+import { revealEditorBeforeActing } from '@/lib/reveal-editor';
import { cn } from '@/lib/utils';
import {
type EditorTabDragData,
@@ -687,16 +688,14 @@ interface EditorTabsProps {
dropIndicatorIndex?: number | null;
paneId: string;
onSplitComplete?: (paneId: string, tabId: string) => void;
- reserveLeadingChrome?: boolean;
- reserveTrailingChrome?: boolean;
+ leading?: ReactNode;
}
export function EditorTabs({
dropIndicatorIndex = null,
paneId,
onSplitComplete,
- reserveLeadingChrome = false,
- reserveTrailingChrome = false,
+ leading,
}: EditorTabsProps) {
const { t } = useLingui();
const context = useDocumentContext();
@@ -866,21 +865,25 @@ export function EditorTabs({
if (matchesKeyboardShortcut(event, 'tab-new')) {
event.preventDefault();
+ revealEditorBeforeActing();
context.openNewTabInPane(resolvedPaneId);
return;
}
if (matchesKeyboardShortcut(event, 'tab-reopen-closed')) {
event.preventDefault();
+ revealEditorBeforeActing();
reopenClosedTab();
return;
}
if (matchesKeyboardShortcut(event, 'tab-next')) {
event.preventDefault();
+ revealEditorBeforeActing();
activateTabByOffset(1);
return;
}
if (matchesKeyboardShortcut(event, 'tab-previous')) {
event.preventDefault();
+ revealEditorBeforeActing();
activateTabByOffset(-1);
return;
}
@@ -888,6 +891,7 @@ export function EditorTabs({
const jumpIndex = jumpTabIndexFromShortcut(event, currentVisibleTabIds.length);
if (jumpIndex === null) return;
event.preventDefault();
+ revealEditorBeforeActing();
activateVisibleTab(currentVisibleTabIds[jumpIndex]);
}
@@ -954,14 +958,11 @@ export function EditorTabs({
data-editor-pane-tabs={resolvedPaneId}
data-electron-drag={isElectronHost ? '' : undefined}
className={cn(
- 'flex h-12 w-full min-w-0 touch-manipulation items-center overflow-hidden',
- reserveLeadingChrome
- ? 'pl-[calc(var(--editor-header-leading-offset,0px)+var(--editor-header-leading-width,0px)+0.5rem)]'
- : 'pl-2',
- reserveTrailingChrome && 'pr-[var(--editor-header-trailing-width,0px)]',
+ 'flex h-11 w-full min-w-0 touch-manipulation items-center overflow-hidden ps-2',
isElectronHost && '[-webkit-app-region:drag]',
)}
>
+ {leading}
<div
data-editor-tab-overflow-root=""
data-electron-drag={isElectronHost ? '' : undefined}
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index 6edcce4cf..fb8e2018f 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -5,7 +5,6 @@ import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
-import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
@@ -91,8 +90,6 @@ describe('EditorToolbar runtime layout', () => {
showAddPropertyButton={true}
onAddProperty={() => {}}
frontmatterProblems={frontmatterProblems}
- isPanelCollapsed={false}
- onTogglePanel={() => {}}
/>
</TooltipProvider>,
);
@@ -155,29 +152,7 @@ describe('EditorToolbar runtime layout', () => {
expect(screen.getByRole('button', { name: /add properties/i })).toBeTruthy();
});
- test('renders the document-panel shortcut as a Kbd keycap', async () => {
- const user = userEvent.setup();
- await renderToolbar();
-
- await user.hover(
- screen.getByRole('button', {
- name: `Hide panel (${formatShortcutLabel('toggle-document-panel')})`,
- }),
- );
- const tooltip = await screen.findByRole('tooltip', {
- name: `Hide panel ${formatShortcutLabel('toggle-document-panel')}`,
- });
- expect(tooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(
- formatShortcut('toggle-document-panel'),
- );
- });
-
- test('hides the document-panel toggle in a note window', async () => {
- Object.defineProperty(window, 'okDesktop', {
- configurable: true,
- value: { config: { mode: 'note' } },
- });
-
+ test('carries no document-panel toggle, which lives in the tab bar', async () => {
await renderToolbar();
expect(document.querySelector('[data-doc-panel-toggle]')).toBeNull();
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index c9c3f1539..7060e26a3 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -9,24 +9,16 @@ import { isEditableTextDocFile } from '@inkeep/open-knowledge-core/constants/cod
import { isExcalidrawDocFile } from '@inkeep/open-knowledge-core/constants/upload';
import type { LintDiagnostic } from '@inkeep/open-knowledge-core/markdown/lint';
import type { SkillScope } from '@inkeep/open-knowledge-core/schemas/api';
-import { useLingui } from '@lingui/react/macro';
-import { PanelRightClose, PanelRightOpen } from 'lucide-react';
import { lazy, Suspense } from 'react';
import { AddPropertiesButton } from '@/components/AddPropertiesButton';
-import { Button } from '@/components/ui/button.tsx';
-import { Kbd } from '@/components/ui/kbd';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import type { EditorModeValue } from '@/editor/use-editor-mode.ts';
import { useConfigContextOptional } from '@/lib/config-context';
-import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
-import { isNoteWindow } from '@/lib/note-window-mode';
import {
NO_RESERVED_KEYS,
SKILL_RESERVED_KEYS,
withoutReservedProperties,
} from '@/lib/reserved-property-keys';
-import { cn } from '@/lib/utils';
import { EditorBreadcrumb } from './EditorBreadcrumb';
import { EditorModeToggle } from './EditorModeToggle';
import { NotInSidebarIndicator } from './NotInSidebarIndicator';
@@ -55,9 +47,6 @@ interface EditorToolbarProps {
showAddPropertyButton: boolean;
onAddProperty: () => void;
frontmatterProblems?: readonly LintDiagnostic[];
- isPanelCollapsed: boolean;
- onTogglePanel: () => void;
- reserveRightGutter?: boolean;
}
export function EditorToolbar({
@@ -69,15 +58,8 @@ export function EditorToolbar({
showAddPropertyButton,
onAddProperty,
frontmatterProblems = NO_FRONTMATTER_PROBLEMS,
- isPanelCollapsed,
- onTogglePanel,
- reserveRightGutter = false,
}: EditorToolbarProps) {
- const { t } = useLingui();
const slidesPluginEnabled = useConfigContextOptional()?.merged?.slides?.enabled === true;
- const panelShortcut = formatShortcut('toggle-document-panel');
- const panelShortcutLabel = formatShortcutLabel('toggle-document-panel');
- const showPanelToggle = !isNoteWindow();
const managed = activeDocName ? parseManagedArtifactName(activeDocName) : null;
const projectSkillName = activeDocName ? parseProjectSkillContentDocName(activeDocName) : null;
const activeSkill: { scope: SkillScope; name: string } | null =
@@ -135,12 +117,7 @@ export function EditorToolbar({
</div>
</div>
{}
- <div
- className={cn(
- 'pointer-events-auto absolute top-0 right-0 flex min-w-0 max-w-[calc(50%_-_3rem)] items-center justify-end gap-1 py-2 pr-2',
- reserveRightGutter && 'pr-9',
- )}
- >
+ <div className="pointer-events-auto absolute top-0 right-0 flex min-w-0 max-w-[calc(50%_-_3rem)] items-center justify-end gap-1 py-2 pr-2">
{activeSkill && activeDocName ? (
<Suspense fallback={null}>
<SkillToolbarControls
@@ -169,32 +146,6 @@ export function EditorToolbar({
<SlidesToolbarControls provider={activeProvider} docName={activeDocName} />
</Suspense>
) : null}
- {showPanelToggle ? (
- <Tooltip>
- <Button
- data-doc-panel-toggle=""
- variant="ghost"
- size="icon"
- onClick={onTogglePanel}
- aria-expanded={!isPanelCollapsed}
- aria-controls="doc-panel"
- aria-label={
- isPanelCollapsed
- ? t`Show panel (${panelShortcutLabel})`
- : t`Hide panel (${panelShortcutLabel})`
- }
- asChild
- >
- <TooltipTrigger>
- {isPanelCollapsed ? <PanelRightOpen /> : <PanelRightClose />}
- </TooltipTrigger>
- </Button>
- <TooltipContent side="bottom">
- <span>{isPanelCollapsed ? t`Show panel` : t`Hide panel`}</span>{' '}
- <Kbd aria-label={panelShortcutLabel}>{panelShortcut}</Kbd>
- </TooltipContent>
- </Tooltip>
- ) : null}
</div>
<div
aria-hidden
diff --git a/packages/app/src/components/EditorWorkspace.dom.test.tsx b/packages/app/src/components/EditorWorkspace.dom.test.tsx
index cbe42e78f..db761561e 100644
--- a/packages/app/src/components/EditorWorkspace.dom.test.tsx
+++ b/packages/app/src/components/EditorWorkspace.dom.test.tsx
@@ -174,26 +174,28 @@ vi.doMock('@/lib/single-file-mode', () => ({
vi.doMock('./EditorTabs', () => ({
EditorTabs: ({
dropIndicatorIndex,
+ leading,
paneId,
- reserveLeadingChrome,
- reserveTrailingChrome,
}: {
dropIndicatorIndex?: number | null;
+ leading?: ReactNode;
paneId: string;
- reserveLeadingChrome?: boolean;
- reserveTrailingChrome?: boolean;
}) => (
- <div
- data-editor-pane-tabs={paneId}
- data-drop-indicator-index={dropIndicatorIndex ?? undefined}
- data-reserve-leading-chrome={reserveLeadingChrome || undefined}
- data-reserve-trailing-chrome={reserveTrailingChrome || undefined}
- >
+ <div data-editor-pane-tabs={paneId} data-drop-indicator-index={dropIndicatorIndex ?? undefined}>
+ {leading}
Tabs {paneId}
</div>
),
}));
+vi.doMock('./FileListToggle', () => ({
+ FileListToggle: () => (
+ <button type="button" data-testid="file-list-toggle">
+ Files
+ </button>
+ ),
+}));
+
const { EditorWorkspace } = await import('./EditorWorkspace');
function renderWorkspace(portaledPaneBody?: ReactNode) {
@@ -386,9 +388,15 @@ describe('EditorWorkspace', () => {
expect(headerGroups[0]?.style.flexGrow).toBe('60');
expect(headerGroups[1]?.classList.contains('basis-0')).toBe(true);
expect(headerGroups[1]?.style.flexGrow).toBe('40');
+ expect(
+ headerGroups[0]?.classList.contains('[&>*]:pe-[var(--editor-header-trailing-width,0px)]'),
+ ).toBe(false);
+ expect(
+ headerGroups[1]?.classList.contains('[&>*]:pe-[var(--editor-header-trailing-width,0px)]'),
+ ).toBe(true);
expect(container.querySelectorAll('[data-editor-header-pane-separator]')).toHaveLength(1);
- expect(headerGroups[0]?.querySelector('[data-reserve-leading-chrome="true"]')).toBeTruthy();
- expect(headerGroups[1]?.querySelector('[data-reserve-trailing-chrome="true"]')).toBeTruthy();
+ expect(screen.getAllByTestId('file-list-toggle')).toHaveLength(1);
+ expect(headerGroups[0]?.contains(screen.getByTestId('file-list-toggle'))).toBe(true);
if (!workspace || !headerCanvas) throw new Error('Expected workspace and header canvas');
workspace.scrollLeft = 96;
diff --git a/packages/app/src/components/EditorWorkspace.tsx b/packages/app/src/components/EditorWorkspace.tsx
index 964f970a8..d297a21c1 100644
--- a/packages/app/src/components/EditorWorkspace.tsx
+++ b/packages/app/src/components/EditorWorkspace.tsx
@@ -25,6 +25,13 @@ import {
} from 'react';
import { docNameForNavigationTarget } from '@/components/navigation-targets';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { useDocumentContext } from '@/editor/DocumentContext';
import type { EditorPaneState, PaneSide } from '@/editor/editor-panes';
import { openSidebarDropPayload } from '@/editor/sidebar-drop';
@@ -33,6 +40,7 @@ import {
subscribeNoteWindowDeleted,
} from '@/lib/note-window-deleted-store';
import { isNoteWindow } from '@/lib/note-window-mode';
+import { paneVisibilityStore } from '@/lib/pane-visibility-store';
import { hasSidebarDragType, parseSidebarDragPayload } from '@/lib/sidebar-drag';
import { useSingleFileMode } from '@/lib/single-file-mode';
import { cn } from '@/lib/utils';
@@ -46,6 +54,7 @@ import {
TAB_KEYBOARD_DRAG_CODES,
TAB_SELECTED_SURFACE_CLASS,
} from './editor-tabs-chrome';
+import { FileListToggle } from './FileListToggle';
import { NoteWindowDeletedState } from './NoteWindowDeletedState';
const MIN_EDITOR_PANE_WIDTH = 300;
@@ -87,13 +96,19 @@ function PaneStripDropTarget({
children,
index,
isFocused,
+ isLast,
paneId,
+ projected,
+ selected,
size,
}: {
children: ReactNode;
index: number;
isFocused: boolean;
+ isLast: boolean;
paneId: string;
+ projected: boolean;
+ selected: boolean;
size: number;
}) {
const { setNodeRef } = useDroppable({
@@ -105,7 +120,13 @@ function PaneStripDropTarget({
ref={setNodeRef}
data-editor-pane-tab-group={paneId}
data-editor-pane-focused={isFocused || undefined}
- className="relative h-full min-w-0 shrink basis-0"
+ data-editor-pane-selected={projected && selected ? '' : undefined}
+ aria-hidden={projected && !selected ? true : undefined}
+ inert={projected && !selected}
+ className={cn(
+ 'relative h-full min-w-0 shrink basis-0',
+ isLast && '[&>*]:pe-[var(--editor-header-trailing-width,0px)]',
+ )}
style={{ flexGrow: size }}
>
{children}
@@ -384,6 +405,14 @@ export function EditorWorkspace({
() => new Map(),
);
const [parkingHost, setParkingHost] = useState<HTMLElement | null>(null);
+ const [workspaceElement, setWorkspaceElement] = useState<HTMLDivElement | null>(null);
+ const [workspaceWidth, setWorkspaceWidth] = useState(0);
+ const pendingGroupTabFocusRef = useRef<{ paneId: string; tabId: string } | null>(null);
+ const exclusive = useSyncExternalStore(
+ paneVisibilityStore.subscribe,
+ paneVisibilityStore.isExclusive,
+ () => false,
+ );
const focusFrameRef = useRef<number | null>(null);
const [headerCanvas, setHeaderCanvas] = useState<HTMLDivElement | null>(null);
const resolvedPaneLayoutRef = useRef<{
@@ -410,10 +439,47 @@ export function EditorWorkspace({
keyboardCodes: TAB_KEYBOARD_DRAG_CODES,
}),
);
+ const narrowForPanes = (width: number) =>
+ width > 0 && width < panes.length * MIN_EDITOR_PANE_WIDTH + panes.length - 1;
+ const projected =
+ !singleDocumentSurface && panes.length > 1 && (exclusive || narrowForPanes(workspaceWidth));
const canvasStyle = {
- '--editor-workspace-min-width': `max(100%, ${panes.length * MIN_EDITOR_PANE_WIDTH}px)`,
+ '--editor-workspace-min-width':
+ projected || panes.length === 1
+ ? '100%'
+ : `max(100%, ${panes.length * MIN_EDITOR_PANE_WIDTH}px)`,
} as CSSProperties;
+ const liveWorkspaceWidthRef = useRef(0);
+ const syncWorkspaceWidth = useEffectEvent(() => {
+ const liveWidth = liveWorkspaceWidthRef.current;
+ if (Math.abs(liveWidth - workspaceWidth) <= 1) return;
+ if (narrowForPanes(liveWidth) !== narrowForPanes(workspaceWidth)) setWorkspaceWidth(liveWidth);
+ });
+ useLayoutEffect(() => {
+ syncWorkspaceWidth();
+ });
+ useLayoutEffect(() => {
+ if (!workspaceElement) return;
+ let frame: number | null = null;
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry && entry.contentRect.width > 0) {
+ const nextWidth = entry.contentRect.width;
+ if (frame !== null) cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ liveWorkspaceWidthRef.current = nextWidth;
+ syncWorkspaceWidth();
+ });
+ }
+ });
+ observer.observe(workspaceElement);
+ return () => {
+ observer.disconnect();
+ if (frame !== null) cancelAnimationFrame(frame);
+ };
+ }, [workspaceElement]);
+
function applyHeaderLayout(layout: Record<string, number>) {
const groups = headerCanvas?.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]');
groups?.forEach((group) => {
@@ -601,7 +667,12 @@ export function EditorWorkspace({
function syncHeaderLayout(layout: Record<string, number>) {
resolvedPaneLayoutRef.current = { paneKey, layout };
- applyHeaderLayout(layout);
+ if (!projected) applyHeaderLayout(layout);
+ }
+
+ function groupOptionLabel(paneId: string): string {
+ const number = panes.findIndex((pane) => pane.id === paneId) + 1;
+ return t`Pane ${number}`;
}
function paneLabel(paneId: string): string {
@@ -621,15 +692,21 @@ export function EditorWorkspace({
return paneLabel(data.paneId);
}
+ function paneLeadingControl(pane: EditorPaneState, index: number): ReactNode {
+ if (projected) return pane.id === focusedPaneId ? <FileListToggle /> : undefined;
+ return index === 0 ? <FileListToggle /> : undefined;
+ }
+
const paneGroup = (
<ResizablePanelGroup
key={paneKey}
id="editor-workspace-panes"
orientation="horizontal"
+ disabled={projected}
defaultLayout={savedLayout}
onLayoutChange={syncHeaderLayout}
onLayoutChanged={(layout, meta) => {
- if (!meta.isUserInteraction) return;
+ if (!meta.isUserInteraction || projected) return;
resizePanes(
new Map(panes.map((pane) => [pane.id, layout[`editor-pane:${pane.id}`] ?? pane.size])),
);
@@ -641,6 +718,7 @@ export function EditorWorkspace({
<ResizableHandle
withHandle
data-editor-pane-resize-handle=""
+ data-editor-pane-projected={projected ? '' : undefined}
data-editor-pane-before={panes[index - 1]?.id}
data-editor-pane-after={pane.id}
>
@@ -653,8 +731,12 @@ export function EditorWorkspace({
) : null}
<ResizablePanel
id={`editor-pane:${pane.id}`}
+ data-editor-pane-panel=""
+ data-editor-pane-selected={projected && pane.id === focusedPaneId ? '' : undefined}
+ aria-hidden={projected && pane.id !== focusedPaneId ? true : undefined}
+ inert={projected && pane.id !== focusedPaneId}
defaultSize={`${pane.size}%`}
- minSize={`${MIN_EDITOR_PANE_WIDTH}px`}
+ minSize={projected || panes.length === 1 ? '0px' : `${MIN_EDITOR_PANE_WIDTH}px`}
>
<WorkspacePane
drag={drag}
@@ -676,12 +758,13 @@ export function EditorWorkspace({
<div
ref={setHeaderCanvas}
data-editor-header-tab-canvas=""
+ data-editor-pane-projected={projected ? '' : undefined}
className="flex h-full min-w-(--editor-workspace-min-width)"
style={canvasStyle}
>
{panes.map((pane, index) => (
<Fragment key={pane.id}>
- {index > 0 ? (
+ {index > 0 && !projected ? (
<div
aria-hidden="true"
data-editor-header-pane-separator=""
@@ -692,14 +775,16 @@ export function EditorWorkspace({
paneId={pane.id}
index={visibleOrderForPane(pane).length}
isFocused={pane.id === focusedPaneId}
+ isLast={projected ? pane.id === focusedPaneId : index === panes.length - 1}
+ projected={projected}
+ selected={pane.id === focusedPaneId}
size={pane.size}
>
<EditorTabs
dropIndicatorIndex={dropIndicator?.paneId === pane.id ? dropIndicator.index : null}
paneId={pane.id}
onSplitComplete={requestTabFocus}
- reserveLeadingChrome={index === 0}
- reserveTrailingChrome={index === panes.length - 1}
+ leading={paneLeadingControl(pane, index)}
/>
</PaneStripDropTarget>
</Fragment>
@@ -792,14 +877,55 @@ export function EditorWorkspace({
},
}}
>
- {renderHeader(headerTabs)}
+ {renderHeader(
+ <>
+ {projected ? (
+ <Select
+ value={focusedPaneId}
+ onValueChange={(paneId) => {
+ focusPane(paneId);
+ const pane = panes.find((candidate) => candidate.id === paneId);
+ const tabId = pane?.activeTabId ?? pane?.activeNewTabId;
+ pendingGroupTabFocusRef.current = tabId ? { paneId, tabId } : null;
+ }}
+ >
+ <SelectTrigger
+ aria-label={t`Editor pane`}
+ data-editor-group-selector=""
+ size="sm"
+ className="mx-1 my-auto w-24 shrink-0"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ onCloseAutoFocus={(event) => {
+ const pending = pendingGroupTabFocusRef.current;
+ pendingGroupTabFocusRef.current = null;
+ if (!pending) return;
+ event.preventDefault();
+ requestTabFocus(pending.paneId, pending.tabId);
+ }}
+ >
+ {panes.map((pane) => (
+ <SelectItem key={pane.id} value={pane.id}>
+ {groupOptionLabel(pane.id)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : null}
+ {headerTabs}
+ </>,
+ )}
<div
+ ref={setWorkspaceElement}
data-editor-workspace=""
className="relative min-h-0 flex-1 overflow-x-auto overflow-y-hidden"
onScroll={syncHeaderScroll}
>
<div
data-editor-workspace-canvas=""
+ data-editor-pane-projected={projected ? '' : undefined}
className="h-full min-w-[var(--editor-workspace-min-width)]"
style={canvasStyle}
>
diff --git a/packages/app/src/components/ExcalidrawDocEditor.tsx b/packages/app/src/components/ExcalidrawDocEditor.tsx
index ea263c1e0..614621b99 100644
--- a/packages/app/src/components/ExcalidrawDocEditor.tsx
+++ b/packages/app/src/components/ExcalidrawDocEditor.tsx
@@ -81,7 +81,7 @@ export function ExcalidrawDocEditor({ provider }: { provider: HocuspocusProvider
};
return (
- <main
+ <section
className="relative flex h-full min-h-0 flex-col bg-background"
aria-label={t`Excalidraw canvas`}
data-excalidraw-doc-editor=""
@@ -94,6 +94,6 @@ export function ExcalidrawDocEditor({ provider }: { provider: HocuspocusProvider
langCode={excalidrawLangCode(i18n.locale)}
/>
</div>
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/FeedbackCard.tsx b/packages/app/src/components/FeedbackCard.tsx
index a41e1a1cf..d3b917d4f 100644
--- a/packages/app/src/components/FeedbackCard.tsx
+++ b/packages/app/src/components/FeedbackCard.tsx
@@ -11,7 +11,11 @@ import { FeedbackForm } from './FeedbackForm';
export function FeedbackCard({ onClose }: { onClose: () => void }) {
const { t } = useLingui();
return (
- <Card asChild size="sm" className="mx-1 mb-1">
+ <Card
+ asChild
+ size="sm"
+ className="floating-card-surface subtle-scrollbar min-h-0 rounded-lg overflow-y-auto overscroll-contain ring-0 ring-transparent"
+ >
<section aria-label={t`Share feedback`}>
<CardContent>
<FeedbackForm
diff --git a/packages/app/src/components/FeedbackForm.tsx b/packages/app/src/components/FeedbackForm.tsx
index 759ba1f44..0e8aae317 100644
--- a/packages/app/src/components/FeedbackForm.tsx
+++ b/packages/app/src/components/FeedbackForm.tsx
@@ -153,81 +153,94 @@ export const FeedbackForm = ({
}
};
+ const ratingSection = (
+ <>
+ {(title || onDismiss) && (
+ <div className="flex items-start justify-between gap-2">
+ {title ? (
+ <p className={cn('font-medium', compact ? 'text-sm' : 'text-1sm')}>{title}</p>
+ ) : (
+ <span />
+ )}
+ {onDismiss ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={onDismiss}
+ aria-label={t`Close`}
+ className={cn(
+ '-mr-1.5 size-7 shrink-0 text-muted-foreground opacity-60',
+ compact ? '-my-1' : '-mt-1',
+ )}
+ >
+ <X className="size-4" />
+ </Button>
+ ) : null}
+ </div>
+ )}
+ {}
+ <FormField
+ control={form.control}
+ name="rating"
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <ToggleGroup
+ type="single"
+ variant="outline"
+ spacing={2}
+ aria-label={t`Rate your experience`}
+ value={field.value ?? ''}
+ onValueChange={(value) => {
+ if (!value) return;
+ field.onChange(value);
+ if (value === 'positive') form.setValue('reasons', []);
+ }}
+ className="w-full"
+ >
+ <ToggleGroupItem
+ value="positive"
+ className={cn(
+ 'h-auto flex-1 justify-center gap-2 py-2',
+ compact && 'text-1sm',
+ selectedStateClassName,
+ )}
+ >
+ <ThumbsUp className="size-4" />
+ <Trans>Good</Trans>
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="negative"
+ className={cn(
+ 'h-auto flex-1 justify-center gap-2 py-2',
+ compact && 'text-1sm',
+ selectedStateClassName,
+ )}
+ >
+ <ThumbsDown className="size-4" />
+ <Trans>Not great</Trans>
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </>
+ );
+
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
onPaste={attachmentIntake.onPaste}
- className={cn(compact ? 'space-y-3' : 'space-y-5', className)}
+ className={cn(compact ? 'flex flex-col gap-5' : 'space-y-5', className)}
>
- {(title || onDismiss) && (
- <div className="flex items-start justify-between gap-2">
- {title ? <p className="font-medium text-1sm">{title}</p> : <span />}
- {onDismiss ? (
- <Button
- type="button"
- variant="ghost"
- size="icon"
- onClick={onDismiss}
- aria-label={t`Close`}
- className="-mr-1.5 -mt-1 size-7 shrink-0 text-muted-foreground opacity-60"
- >
- <X className="size-4" />
- </Button>
- ) : null}
- </div>
- )}
- {}
- <FormField
- control={form.control}
- name="rating"
- render={({ field }) => (
- <FormItem>
- <FormControl>
- <ToggleGroup
- type="single"
- variant="outline"
- spacing={2}
- aria-label={t`Rate your experience`}
- value={field.value ?? ''}
- onValueChange={(value) => {
- if (!value) return;
- field.onChange(value);
- if (value === 'positive') form.setValue('reasons', []);
- }}
- className="w-full"
- >
- <ToggleGroupItem
- value="positive"
- className={cn(
- 'h-auto flex-1 justify-center py-2',
- compact ? 'gap-1.5 text-xs' : 'gap-2',
- selectedStateClassName,
- )}
- >
- <ThumbsUp className="size-4" />
- <Trans>Good</Trans>
- </ToggleGroupItem>
- <ToggleGroupItem
- value="negative"
- className={cn(
- 'h-auto flex-1 justify-center py-2',
- compact ? 'gap-1.5 text-xs' : 'gap-2',
- selectedStateClassName,
- )}
- >
- <ThumbsDown className="size-4" />
- <Trans>Not great</Trans>
- </ToggleGroupItem>
- </ToggleGroup>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
+ {compact ? <div className="flex flex-col gap-2">{ratingSection}</div> : ratingSection}
{showBeyondRating && (
<>
- <div className="space-y-3">
+ <div className={compact ? 'space-y-5' : 'space-y-3'}>
{}
{rating === 'negative' && (
<FormField
@@ -251,7 +264,7 @@ export const FeedbackForm = ({
<ToggleGroupItem
key={reason.value}
value={reason.value}
- className={pillClassName}
+ className={cn(pillClassName, compact && 'text-1sm')}
>
{t(reason.label)}
</ToggleGroupItem>
diff --git a/packages/app/src/components/FileListHost.dom.test.tsx b/packages/app/src/components/FileListHost.dom.test.tsx
new file mode 100644
index 000000000..15d54789b
--- /dev/null
+++ b/packages/app/src/components/FileListHost.dom.test.tsx
@@ -0,0 +1,107 @@
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { useEffect, useState } from 'react';
+import { afterEach, expect, test } from 'vitest';
+import { FileListHostProvider, useAttachFileListHost, useFileListHost } from './FileListHost';
+
+let fileListMounts = 0;
+let fileListUnmounts = 0;
+
+afterEach(() => {
+ cleanup();
+ fileListMounts = 0;
+ fileListUnmounts = 0;
+});
+
+function CountingFileList() {
+ const [expandedFolder] = useState(() => `folder-${fileListMounts}`);
+ useEffect(() => {
+ fileListMounts += 1;
+ return () => {
+ fileListUnmounts += 1;
+ };
+ }, []);
+ return <nav data-testid="file-list" data-expanded-folder={expandedFolder} />;
+}
+
+function EditorCardSlot() {
+ const host = useFileListHost();
+ const [slot, setSlot] = useState<HTMLDivElement | null>(null);
+ useAttachFileListHost(host, slot);
+ if (host == null) return null;
+ return <div data-testid="file-list-slot" ref={setSlot} />;
+}
+
+function Shell({ enabled = true, cardMounted = true }) {
+ return (
+ <FileListHostProvider enabled={enabled} fileList={<CountingFileList />}>
+ {cardMounted ? <EditorCardSlot /> : <div data-testid="skeleton" />}
+ </FileListHostProvider>
+ );
+}
+
+test('draws the file list inside the editor card slot', () => {
+ render(<Shell />);
+
+ const slot = screen.getByTestId('file-list-slot');
+ expect(slot.contains(screen.getByTestId('file-list'))).toBe(true);
+ expect(fileListMounts).toBe(1);
+});
+
+test('keeps the file list mounted, with its state, while the slot is gone and after it returns', () => {
+ const { rerender } = render(<Shell />);
+ const fileList = screen.getByTestId('file-list');
+
+ rerender(<Shell cardMounted={false} />);
+ expect(screen.queryByTestId('file-list-slot')).toBeNull();
+ expect(fileListMounts).toBe(1);
+ expect(fileListUnmounts).toBe(0);
+
+ rerender(<Shell />);
+ expect(screen.getByTestId('file-list-slot').contains(fileList)).toBe(true);
+ expect(screen.getByTestId('file-list')).toBe(fileList);
+ expect(fileList.getAttribute('data-expanded-folder')).toBe('folder-0');
+ expect(fileListMounts).toBe(1);
+ expect(fileListUnmounts).toBe(0);
+});
+
+test('mounts the file list before any slot exists, so its listeners run from the first render', () => {
+ render(<Shell cardMounted={false} />);
+
+ expect(fileListMounts).toBe(1);
+ expect(screen.queryByTestId('file-list')).toBeNull();
+});
+
+test('renders no file list and no slot when the window has none', () => {
+ render(<Shell enabled={false} />);
+
+ expect(screen.queryByTestId('file-list-slot')).toBeNull();
+ expect(screen.queryByTestId('file-list')).toBeNull();
+ expect(fileListMounts).toBe(0);
+});
+
+test('moving to a new slot carries the same file list element across', () => {
+ function TwoSlots({ second }: { second: boolean }) {
+ return (
+ <FileListHostProvider enabled fileList={<CountingFileList />}>
+ {second ? (
+ <section data-testid="second">
+ <EditorCardSlot />
+ </section>
+ ) : (
+ <section data-testid="first">
+ <EditorCardSlot />
+ </section>
+ )}
+ </FileListHostProvider>
+ );
+ }
+ const { rerender } = render(<TwoSlots second={false} />);
+ const fileList = screen.getByTestId('file-list');
+
+ act(() => {
+ rerender(<TwoSlots second />);
+ });
+
+ expect(screen.getByTestId('second').contains(fileList)).toBe(true);
+ expect(fileListMounts).toBe(1);
+});
diff --git a/packages/app/src/components/FileListHost.tsx b/packages/app/src/components/FileListHost.tsx
new file mode 100644
index 000000000..ed3a1e589
--- /dev/null
+++ b/packages/app/src/components/FileListHost.tsx
@@ -0,0 +1,44 @@
+import { createContext, type ReactNode, use, useLayoutEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { moveHostPreservingScroll, observeHostScrollRestore } from '@/lib/preserve-subtree-scroll';
+
+const FileListHostContext = createContext<HTMLElement | null>(null);
+
+function createFileListHostElement(): HTMLElement | null {
+ if (typeof document === 'undefined') return null;
+ const host = document.createElement('div');
+ host.className = 'contents';
+ host.setAttribute('data-file-list-host', '');
+ return host;
+}
+
+export function FileListHostProvider({
+ enabled,
+ fileList,
+ children,
+}: {
+ readonly enabled: boolean;
+ readonly fileList: ReactNode;
+ readonly children: ReactNode;
+}) {
+ const [host] = useState(createFileListHostElement);
+ const activeHost = enabled ? host : null;
+ return (
+ <FileListHostContext value={activeHost}>
+ {activeHost != null ? createPortal(fileList, activeHost) : null}
+ {children}
+ </FileListHostContext>
+ );
+}
+
+export function useFileListHost(): HTMLElement | null {
+ return use(FileListHostContext);
+}
+
+export function useAttachFileListHost(host: HTMLElement | null, slot: HTMLElement | null): void {
+ useLayoutEffect(() => {
+ if (host == null || slot == null) return;
+ if (host.parentElement !== slot) moveHostPreservingScroll(host, slot);
+ return observeHostScrollRestore(host, slot);
+ }, [host, slot]);
+}
diff --git a/packages/app/src/components/FileListToggle.dom.test.tsx b/packages/app/src/components/FileListToggle.dom.test.tsx
new file mode 100644
index 000000000..731a55a98
--- /dev/null
+++ b/packages/app/src/components/FileListToggle.dom.test.tsx
@@ -0,0 +1,127 @@
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { type ReactNode, useState } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { SidebarProvider } from '@/components/ui/sidebar';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+function setElectronHost(enabled: boolean) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: enabled ? {} : undefined,
+ });
+}
+
+async function renderToggle(initiallyOpen: boolean) {
+ const { FileListToggle } = await import('./FileListToggle');
+ function Harness() {
+ const [open, setOpen] = useState(initiallyOpen);
+ return (
+ <SidebarProvider open={open} onOpenChange={setOpen}>
+ <TooltipProvider delayDuration={0}>
+ <FileListToggle />
+ </TooltipProvider>
+ </SidebarProvider>
+ );
+ }
+ return render(<Harness />);
+}
+
+function toggleButton() {
+ return document.querySelector('[data-sidebar="trigger"]') as HTMLElement;
+}
+
+describe('FileListToggle', () => {
+ afterEach(() => {
+ cleanup();
+ setElectronHost(false);
+ });
+
+ test('its tooltip says what the next press does and shows the shortcut as a keycap', async () => {
+ const user = userEvent.setup();
+ await renderToggle(true);
+
+ await user.hover(toggleButton());
+ const hide = await screen.findByRole('tooltip', {
+ name: `Hide Files ${formatShortcutLabel('toggle-files-sidebar')}`,
+ });
+ expect(hide.querySelector('[data-slot="kbd"]')?.textContent).toBe(
+ formatShortcut('toggle-files-sidebar'),
+ );
+
+ cleanup();
+ await renderToggle(false);
+ await user.hover(toggleButton());
+ const show = await screen.findByRole('tooltip', {
+ name: `Show Files ${formatShortcutLabel('toggle-files-sidebar')}`,
+ });
+ expect(show.querySelector('[data-slot="kbd"]')?.textContent).toBe(
+ formatShortcut('toggle-files-sidebar'),
+ );
+ });
+
+ test('its tooltip opens below the toggle, clear of the window buttons above it', async () => {
+ const user = userEvent.setup();
+ await renderToggle(true);
+
+ await user.hover(toggleButton());
+ await screen.findByRole('tooltip');
+ const content = document.querySelector('[data-slot="tooltip-content"]');
+
+ expect(content?.getAttribute('data-side')).toBe('bottom');
+ });
+
+ test('pressing it closes the file list and pressing it again reopens it', async () => {
+ const user = userEvent.setup();
+ await renderToggle(true);
+
+ expect(toggleButton().getAttribute('aria-expanded')).toBe('true');
+ await user.click(toggleButton());
+ expect(toggleButton().getAttribute('aria-expanded')).toBe('false');
+ await user.click(toggleButton());
+ expect(toggleButton().getAttribute('aria-expanded')).toBe('true');
+ });
+
+ test('on Electron the space around the toggle drags the window while the toggle itself opts out', async () => {
+ setElectronHost(true);
+ const { container } = await renderToggle(true);
+ const zone = container.querySelector('[data-file-list-toggle]') as HTMLElement;
+
+ expect(zone.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(zone.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokens(toggleButton().className, ['[-webkit-app-region:no-drag]']);
+ });
+
+ test('on the web the toggle carries no window-drag treatment', async () => {
+ const { container } = await renderToggle(true);
+ const zone = container.querySelector('[data-file-list-toggle]') as HTMLElement;
+
+ expect(zone.getAttribute('data-electron-drag')).toBeNull();
+ expectVisualClassTokensAbsent(zone.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokensAbsent(toggleButton().className, ['[-webkit-app-region:no-drag]']);
+ });
+
+ test('a divider separates the toggle from whatever follows it', async () => {
+ const { container } = await renderToggle(true);
+
+ const separator = container.querySelector('[data-slot="separator"]') as HTMLElement;
+ expect(
+ toggleButton().compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/components/FileListToggle.tsx b/packages/app/src/components/FileListToggle.tsx
new file mode 100644
index 000000000..7477924a1
--- /dev/null
+++ b/packages/app/src/components/FileListToggle.tsx
@@ -0,0 +1,42 @@
+import { useLingui } from '@lingui/react/macro';
+import { Kbd } from '@/components/ui/kbd';
+import { Separator } from '@/components/ui/separator';
+import { SidebarTrigger, useSidebar } from '@/components/ui/sidebar';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import { cn } from '@/lib/utils';
+
+export function FileListToggle() {
+ const { t } = useLingui();
+ const { state } = useSidebar();
+ const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
+
+ return (
+ <div
+ data-file-list-toggle=""
+ data-electron-drag={isElectronHost ? '' : undefined}
+ className={cn(
+ 'flex h-full shrink-0 items-center gap-1 pe-1',
+ isElectronHost && '[-webkit-app-region:drag]',
+ )}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <SidebarTrigger
+ className={cn(
+ 'shrink-0 text-muted-foreground',
+ isElectronHost && '[-webkit-app-region:no-drag]',
+ )}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <span>{state === 'expanded' ? t`Hide Files` : t`Show Files`}</span>{' '}
+ <Kbd aria-label={formatShortcutLabel('toggle-files-sidebar')}>
+ {formatShortcut('toggle-files-sidebar')}
+ </Kbd>
+ </TooltipContent>
+ </Tooltip>
+ <Separator orientation="vertical" className="h-4 shrink-0 data-vertical:self-center" />
+ </div>
+ );
+}
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
index 208982f6b..37f51cfba 100644
--- a/packages/app/src/components/FileSidebar.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -13,10 +13,7 @@ import { __resetSkillsSectionVisibleCacheForTests } from '@/components/skills-se
import { TooltipProvider } from '@/components/ui/tooltip';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-import {
- expectVisualClassTokens,
- expectVisualClassTokensAbsent,
-} from '@/test-utils/visual-contract';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
function PassThrough({ children }: { children?: ReactNode }) {
return <>{children}</>;
@@ -107,7 +104,6 @@ let mergedConfig: {
};
let projectLocalBindingNull = false;
let projectLocalSynced = true;
-let sidebarSearchThrows = false;
let projectPatchResult: { ok: true } | { ok: false; error: unknown } = { ok: true };
let openInAgentSubmenuProps: Array<{
input: unknown;
@@ -115,7 +111,6 @@ let openInAgentSubmenuProps: Array<{
let toastSuccesses: unknown[][] = [];
let toastErrors: unknown[][] = [];
let toastInfos: unknown[][] = [];
-let pillRenderErrors: unknown[][] = [];
const treeListeners = new Set<() => void>();
const treeCalls = {
@@ -128,7 +123,6 @@ const treeCalls = {
const projectLocalPatch = vi.fn((_patch: unknown) => projectPatchResult);
const showItemInFolderMock = vi.fn((_path: string) => Promise.resolve());
const notifyViewMenuStateChangedMock = vi.fn((_snapshot: unknown) => {});
-const onOpenSearch = vi.fn(() => {});
function setFolderState(next: FolderState) {
folderState = next;
@@ -198,24 +192,24 @@ vi.doMock('@/components/ProjectSwitcher', () => ({
ProjectSwitcher: () => <button type="button">Project switcher</button>,
}));
-vi.doMock('@/components/SidebarSearchBar', () => ({
- SidebarSearchBar: ({ onClick }: { onClick: () => void }) => {
- if (sidebarSearchThrows) throw new Error('search pill render failed');
- return (
- <button data-testid="sidebar-search" type="button" onClick={onClick}>
- Search
- </button>
- );
- },
- onPillRenderError: (...args: unknown[]) => {
- pillRenderErrors.push(args);
- },
-}));
-
vi.doMock('@/components/UpdateNotices', () => ({
UpdateNotices: () => <div data-testid="update-notices" />,
}));
+vi.doMock('@/components/OnboardingCard', async () => ({
+ ...(await vi.importActual<typeof import('@/components/OnboardingCard')>(
+ '@/components/OnboardingCard',
+ )),
+ OnboardingCardMount: () => <div data-testid="onboarding-card-mount" />,
+}));
+
+vi.doMock('@/components/FeedbackCard', async () => ({
+ ...(await vi.importActual<typeof import('@/components/FeedbackCard')>(
+ '@/components/FeedbackCard',
+ )),
+ FeedbackCardMount: () => <div data-testid="feedback-card-mount" />,
+}));
+
vi.doMock('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
OpenInAgentEmptySpaceSubmenu: (props: { input: unknown }) => {
openInAgentSubmenuProps.push(props);
@@ -453,7 +447,7 @@ vi.doMock('sonner', () => ({
async function renderSidebar() {
const { FileSidebar } = await import('./FileSidebar');
- return render(<FileSidebar onOpenSearch={onOpenSearch} />, {
+ return render(<FileSidebar />, {
wrapper: ({ children }) => <TooltipProvider delayDuration={0}>{children}</TooltipProvider>,
});
}
@@ -474,13 +468,11 @@ describe('FileSidebar runtime behavior', () => {
mergedConfig = { appearance: { sidebar: { showHiddenFiles: false } } };
projectLocalBindingNull = false;
projectLocalSynced = true;
- sidebarSearchThrows = false;
projectPatchResult = { ok: true };
openInAgentSubmenuProps = [];
toastSuccesses = [];
toastErrors = [];
toastInfos = [];
- pillRenderErrors = [];
treeListeners.clear();
for (const fn of [
treeCalls.collapseAll,
@@ -491,7 +483,6 @@ describe('FileSidebar runtime behavior', () => {
projectLocalPatch,
showItemInFolderMock,
notifyViewMenuStateChangedMock,
- onOpenSearch,
]) {
fn.mockClear();
}
@@ -515,63 +506,48 @@ describe('FileSidebar runtime behavior', () => {
});
});
- test('web mode header holds only search and omits navigation history', async () => {
- await renderSidebar();
-
- const header = screen.getByTestId('sidebar-header');
- expect(screen.queryByText('Files')).toBeNull();
- expect(header.children).toHaveLength(1);
- expect(header.contains(screen.getByTestId('sidebar-search'))).toBe(true);
- expect(header.contains(screen.getByTestId('sidebar-toolbar'))).toBe(false);
- expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
- expectVisualClassTokens(header.className, ['justify-between']);
- expectVisualClassTokensAbsent(header.className, [
- '[-webkit-app-region:drag]',
- 'overflow-x-clip',
- ]);
- expect(header.getAttribute('data-electron-drag')).toBeNull();
- expect(screen.queryByTestId('sidebar-traffic-light-reserve')).toBeNull();
- expect(screen.queryByText('Project switcher')).toBeNull();
-
- fireEvent.click(screen.getByTestId('sidebar-search'));
- expect(onOpenSearch).toHaveBeenCalledTimes(1);
- });
+ for (const host of [
+ { label: 'on the web', electron: false, state: 'expanded' },
+ { label: 'in an expanded Electron window', electron: true, state: 'expanded' },
+ { label: 'in a collapsed Electron window', electron: true, state: 'collapsed' },
+ ] as const) {
+ test(`${host.label} the file list has no top bar, and the project row is its first row`, async () => {
+ if (host.electron) installBridge();
+ sidebarState = host.state;
+ const { container } = await renderSidebar();
+
+ expect(screen.queryByTestId('sidebar-header')).toBeNull();
+ const content = screen.getByTestId('sidebar-content');
+ const projectRow = container.querySelector('[data-sidebar-project-row]') as HTMLElement;
+ const conflicts = screen.getByTestId('conflicts-section');
+ const rowsAbove = Array.from(content.querySelectorAll('*')).filter(
+ (element) =>
+ element !== conflicts &&
+ !conflicts.contains(element) &&
+ !element.contains(projectRow) &&
+ (element.compareDocumentPosition(projectRow) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0,
+ );
+ expect(rowsAbove, 'only the sync-conflicts slot may sit above the project row').toEqual([]);
+ expect(projectRow.textContent).toContain('open-knowledge');
+ expect(projectRow.contains(screen.getByTestId('sidebar-toolbar'))).toBe(true);
+ expectVisualClassTokens(projectRow.className, ['h-11']);
+ expect(screen.queryByRole('button', { name: /^Search/ })).toBeNull();
+ expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
+ expect(screen.queryByTestId('sidebar-traffic-light-reserve')).toBeNull();
+ expect(screen.queryByText('Project switcher')).toBeNull();
+ });
+ }
- test('expanded Electron header contains the traffic-light reserve, one navigation pair, and search', async () => {
+ test('in an expanded Electron window the file list toolbar opts out of window dragging', async () => {
const user = userEvent.setup();
installBridge();
await renderSidebar();
- const header = screen.getByTestId('sidebar-header');
const toolbar = screen.getByTestId('sidebar-toolbar');
- const searchCluster = screen.getByTestId('sidebar-search').parentElement as HTMLElement;
-
- expect(screen.queryByText('Files')).toBeNull();
- expect(screen.getByText('Project switcher')).toBeTruthy();
- expect(header.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(header.className, [
- 'justify-between',
- 'overflow-x-clip',
- '[-webkit-app-region:drag]',
- ]);
- const reserve = screen.getByTestId('sidebar-traffic-light-reserve');
- expectVisualClassTokens(reserve.className, [
- 'w-[var(--ok-titlebar-reserve-left,0px)]',
- 'shrink-0',
- 'self-stretch',
- ]);
expectVisualClassTokens(toolbar.className, ['[&>*]:[-webkit-app-region:no-drag]']);
- expectVisualClassTokens(searchCluster.className, ['[&>*]:[-webkit-app-region:no-drag]']);
expect(screen.getByTestId('sidebar-rail').getAttribute('data-enable-toggle')).toBe('false');
-
- const navigation = screen.getByTestId('navigation-history-controls');
- expect(header.children).toHaveLength(2);
- expect(header.children.item(0)).toBe(reserve);
- expect(header.children.item(1)).toBe(searchCluster);
- expect(searchCluster.contains(navigation)).toBe(true);
- expect(header.contains(toolbar)).toBe(false);
- expect(within(header).getByRole('button', { name: 'Back' })).toBeTruthy();
- expect(within(header).getByRole('button', { name: 'Forward' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Back' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Forward' })).toBeNull();
await user.hover(screen.getByRole('button', { name: 'New folder' }));
const newFolderTooltip = await screen.findByRole('tooltip', {
@@ -582,20 +558,17 @@ describe('FileSidebar runtime behavior', () => {
);
});
- test('collapsed Electron sidebar removes navigation and fades the header, search included', async () => {
+ test('Electron footer keeps only the onboarding checklist, leaving update notices and feedback to the corner stack and the project switcher to the app header', async () => {
installBridge();
- sidebarState = 'collapsed';
await renderSidebar();
- expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
- const header = screen.getByTestId('sidebar-header');
- expectVisualClassTokens(header.className, [
- 'opacity-0',
- 'motion-safe:transition-opacity',
- 'motion-safe:duration-100',
- 'motion-safe:ease-out',
+ const footer = screen.getByTestId('sidebar-footer');
+ expect(Array.from(footer.children).map((child) => child.getAttribute('data-testid'))).toEqual([
+ 'onboarding-card-mount',
]);
- expect(header.contains(screen.getByTestId('sidebar-search'))).toBe(true);
+ expect(screen.queryByTestId('update-notices')).toBeNull();
+ expect(screen.queryByTestId('feedback-card-mount')).toBeNull();
+ expect(screen.queryByText('Project switcher')).toBeNull();
});
test('toolbar buttons name their shortcut as a keycap in the tooltip', async () => {
@@ -681,7 +654,7 @@ describe('FileSidebar runtime behavior', () => {
const menu = screen.getByTestId('tree-options-menu');
expect(within(menu).getByRole('button', { name: 'Expand all' })).toBeTruthy();
const collapseAll = within(menu).getByRole('button', { name: 'Collapse all' });
- expect(within(menu).getAllByTestId('dropdown-menu-separator')).toHaveLength(2);
+ expect(within(menu).getAllByTestId('dropdown-menu-separator')).toHaveLength(3);
const group = within(menu).getByRole('group', { name: 'Show' });
const checkboxes = within(group).getAllByRole('menuitemcheckbox');
@@ -698,6 +671,8 @@ describe('FileSidebar runtime behavior', () => {
const grouping = within(menu).getByTestId('tree-options-group-skills');
expect(within(group).queryByTestId('tree-options-group-skills')).toBeNull();
expect(group.compareDocumentPosition(grouping) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ const hide = within(menu).getByRole('button', { name: 'Hide Files' });
+ expect(grouping.compareDocumentPosition(hide) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
test('tree-options trigger stays visible with zero folders and the popover keeps its state-independent items', async () => {
@@ -709,8 +684,9 @@ describe('FileSidebar runtime behavior', () => {
const menu = screen.getByTestId('tree-options-menu');
expect(within(menu).queryByRole('button', { name: 'Expand all' })).toBeNull();
expect(within(menu).queryByRole('button', { name: 'Collapse all' })).toBeNull();
- expect(within(menu).getAllByTestId('dropdown-menu-separator')).toHaveLength(1);
+ expect(within(menu).getAllByTestId('dropdown-menu-separator')).toHaveLength(2);
expect(within(menu).getAllByRole('menuitemcheckbox')).toHaveLength(5);
+ expect(within(menu).getByRole('button', { name: 'Hide Files' })).toBeTruthy();
});
test('each Show checkbox reflects its config leaf and writes it through the project-local binding', async () => {
@@ -813,7 +789,7 @@ describe('FileSidebar runtime behavior', () => {
projectLocalSynced = true;
const { FileSidebar } = await import('./FileSidebar');
- rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
+ rendered.rerender(<FileSidebar />);
const readyCheckbox = within(screen.getByTestId('tree-options-menu')).getByTestId(
'tree-options-show-hidden-files',
@@ -992,7 +968,7 @@ describe('FileSidebar runtime behavior', () => {
mergedConfig = null;
const { FileSidebar } = await import('./FileSidebar');
- rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
+ rendered.rerender(<FileSidebar />);
expect(screen.getByTestId('skills-dock')).toBeTruthy();
});
@@ -1003,7 +979,7 @@ describe('FileSidebar runtime behavior', () => {
mergedConfig = null;
const { FileSidebar } = await import('./FileSidebar');
- rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
+ rendered.rerender(<FileSidebar />);
expect(screen.queryByTestId('skills-dock')).toBeNull();
});
@@ -1017,26 +993,4 @@ describe('FileSidebar runtime behavior', () => {
expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
expect(screen.getAllByRole('button', { name: 'New file' }).length).toBeGreaterThan(0);
});
-
- test('search pill render failures are contained to the pill row and reset when sidebar state changes', async () => {
- const originalConsoleError = console.error;
- console.error = vi.fn(() => {}) as never;
- try {
- sidebarSearchThrows = true;
- const rendered = await renderSidebar();
-
- await waitFor(() => expect(pillRenderErrors.length).toBeGreaterThan(0));
- expect(screen.queryByTestId('sidebar-search')).toBeNull();
- expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
- expect(screen.getByTestId('sidebar-footer')).toBeTruthy();
-
- sidebarSearchThrows = false;
- sidebarState = 'collapsed';
- const { FileSidebar } = await import('./FileSidebar');
- rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
- expect(await screen.findByTestId('sidebar-search')).toBeTruthy();
- } finally {
- console.error = originalConsoleError;
- }
- });
});
diff --git a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
index 210def10d..144f670b3 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -1,9 +1,14 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { type ReactNode, useEffect } from 'react';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, onTestFinished, test, vi } from 'vitest';
import { __resetSkillsSectionVisibleCacheForTests } from '@/components/skills-section-visible-cache';
import { TooltipProvider } from '@/components/ui/tooltip';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import type { ResolvedNavigationTarget } from './navigation-targets';
type MenuAction =
@@ -163,19 +168,6 @@ vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: noAgentsInstalled ? noAgentStates : installedAgentStates }),
}));
-vi.doMock('@/components/ProjectSwitcher', () => ({
- ProjectSwitcher: () => null,
-}));
-
-vi.doMock('@/components/SidebarSearchBar', () => ({
- SidebarSearchBar: () => <button type="button">Search</button>,
- onPillRenderError: () => {},
-}));
-
-vi.doMock('@/components/UpdateNotices', () => ({
- UpdateNotices: () => null,
-}));
-
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
@@ -232,9 +224,35 @@ const { registerAgent, reloadRegisteredAgentsFromStorage } = await import(
const { saveStickyAgent } = await import('@/lib/unified-agent-store');
function renderSidebar() {
- return render(<FileSidebar onOpenSearch={() => {}} />, { wrapper: TooltipProvider });
+ return render(<FileSidebar />, { wrapper: TooltipProvider });
+}
+
+function actWhenCalled(
+ mock: { mockImplementation(fn: () => void): unknown; mockReset(): unknown },
+ act: () => void,
+): () => void {
+ mock.mockImplementation(act);
+ return () => {
+ mock.mockReset();
+ };
}
+const REVEAL_BEFORE_ACTING: ReadonlyArray<{
+ action: string;
+ observeAct: (act: () => void) => () => void;
+}> = [
+ { action: 'new-doc', observeAct: (act) => actWhenCalled(treeCalls.startCreating, act) },
+ { action: 'new-folder', observeAct: (act) => actWhenCalled(treeCalls.startCreating, act) },
+ {
+ action: 'new-from-template',
+ observeAct: (act) => actWhenCalled(treeCalls.startCreatingFromTemplate, act),
+ },
+ { action: 'rename', observeAct: (act) => subscribeToFileTreeMenuActionRename(act) },
+ { action: 'duplicate', observeAct: (act) => subscribeToFileTreeMenuActionDuplicate(act) },
+ { action: 'move-to-trash', observeAct: (act) => subscribeToFileTreeMenuActionDelete(act) },
+ { action: 'toggle-sidebar', observeAct: (act) => actWhenCalled(toggleSidebarMock, act) },
+];
+
describe('FileSidebar menu-action runtime routing', () => {
beforeEach(() => {
menuActionCallback = null;
@@ -291,12 +309,34 @@ describe('FileSidebar menu-action runtime routing', () => {
afterEach(() => {
cleanup();
+ __resetPaneVisibilityStoreForTests();
Object.defineProperty(window, 'okDesktop', {
configurable: true,
value: undefined,
});
});
+ test.each(REVEAL_BEFORE_ACTING)(
+ '$action shows a hidden editor before acting',
+ async ({ action, observeAct }) => {
+ const log: Array<PaneVisibilityRequest | 'act'> = [];
+ paneVisibilityStore.subscribeRequests((request) => log.push(request));
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ const stopObserving = observeAct(() => log.push('act'));
+ onTestFinished(stopObserving);
+ renderSidebar();
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.(action as MenuAction);
+
+ expect(log).toEqual([{ pane: 'editor', open: true }, 'act']);
+ },
+ );
+
test('duplicate menu action emits the active target on the FileTree event bus', async () => {
const received: ResolvedNavigationTarget[] = [];
const unsubscribe = subscribeToFileTreeMenuActionDuplicate((target) => {
@@ -432,7 +472,7 @@ describe('FileSidebar menu-action runtime routing', () => {
mediaKind: 'image',
} satisfies ResolvedNavigationTarget;
activeTarget = imageTarget;
- rendered.rerender(<FileSidebar onOpenSearch={() => {}} />);
+ rendered.rerender(<FileSidebar />);
await waitFor(() => expect(menuActionCallback).not.toBeNull());
menuActionCallback?.('rename' as MenuAction);
@@ -561,7 +601,7 @@ describe('FileSidebar menu-action runtime routing', () => {
);
projectLocalSynced = true;
- rendered.rerender(<FileSidebar onOpenSearch={() => {}} />);
+ rendered.rerender(<FileSidebar />);
menuActionCallback?.('toggle-show-hidden-files' as MenuAction);
expect(projectLocalPatch).toHaveBeenCalledWith({
appearance: { sidebar: { showHiddenFiles: true } },
@@ -605,7 +645,7 @@ describe('FileSidebar menu-action runtime routing', () => {
);
projectLocalSynced = true;
- rendered.rerender(<FileSidebar onOpenSearch={() => {}} />);
+ rendered.rerender(<FileSidebar />);
const ready = within(screen.getByTestId('tree-options-menu')).getByTestId(
'tree-options-show-hidden-files',
@@ -663,7 +703,7 @@ describe('FileSidebar menu-action runtime routing', () => {
for (const { action, key, defaultValue } of toggleRoundTrips) {
mergedConfig = { appearance: { sidebar: {} } };
- rerender(<FileSidebar onOpenSearch={() => {}} />);
+ rerender(<FileSidebar />);
projectLocalPatch.mockClear();
menuActionCallback?.(action as MenuAction);
@@ -672,7 +712,7 @@ describe('FileSidebar menu-action runtime routing', () => {
});
mergedConfig = { appearance: { sidebar: { [key]: !defaultValue } } };
- rerender(<FileSidebar onOpenSearch={() => {}} />);
+ rerender(<FileSidebar />);
projectLocalPatch.mockClear();
menuActionCallback?.(action as MenuAction);
diff --git a/packages/app/src/components/FileSidebar.share.dom.test.tsx b/packages/app/src/components/FileSidebar.share.dom.test.tsx
index c1dbc40de..1d80bfd84 100644
--- a/packages/app/src/components/FileSidebar.share.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.share.dom.test.tsx
@@ -163,15 +163,6 @@ vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-vi.doMock('@/components/ProjectSwitcher', () => ({ ProjectSwitcher: () => null }));
-
-vi.doMock('@/components/SidebarSearchBar', () => ({
- SidebarSearchBar: () => <button type="button">Search</button>,
- onPillRenderError: () => {},
-}));
-
-vi.doMock('@/components/UpdateNotices', () => ({ UpdateNotices: () => null }));
-
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
@@ -204,7 +195,7 @@ vi.doMock('sonner', () => ({
const { FileSidebar } = await import('./FileSidebar');
function renderSidebar() {
- return render(<FileSidebar onOpenSearch={() => {}} />, { wrapper: TooltipProvider });
+ return render(<FileSidebar />, { wrapper: TooltipProvider });
}
describe('FileSidebar project-root Share', () => {
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index 4d0a5e891..7060fdf73 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -10,6 +10,7 @@ import {
FolderPlus,
FoldVertical,
ListCollapse,
+ PanelLeftClose,
Share2,
SquarePen,
UnfoldVertical,
@@ -23,10 +24,8 @@ import {
useRef,
useState,
} from 'react';
-import { ErrorBoundary } from 'react-error-boundary';
import { toast } from 'sonner';
import { ConflictsSection } from '@/components/ConflictsSection';
-import { FeedbackCardMount } from '@/components/FeedbackCard';
import { FileTree, type FileTreeHandle } from '@/components/FileTree';
import { defaultInitialDir, hasOkPathSegment } from '@/components/file-tree-utils';
import { subscribeToFilesSectionReveal } from '@/components/files-section-reveal-store';
@@ -39,10 +38,7 @@ import {
useHandoffDispatch,
} from '@/components/handoff/useHandoffDispatch';
import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
-import { NavigationHistoryControls } from '@/components/NavigationHistoryControls';
import { OnboardingCardMount } from '@/components/OnboardingCard';
-import { ProjectSwitcher } from '@/components/ProjectSwitcher';
-import { onPillRenderError, SidebarSearchBar } from '@/components/SidebarSearchBar';
import {
SidebarToolbarButton as ToolbarButton,
type SidebarToolbarButtonProps as ToolbarButtonProps,
@@ -53,7 +49,6 @@ import {
writeCachedSkillsSectionVisible,
} from '@/components/skills-section-visible-cache';
import { TemplateMenuRows } from '@/components/template-menu-rows';
-import { UpdateNotices } from '@/components/UpdateNotices';
import { Button } from '@/components/ui/button';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
@@ -84,9 +79,6 @@ import {
SidebarFooter,
SidebarGroup,
SidebarGroupLabel,
- SidebarHeader,
- SidebarMenu,
- SidebarMenuItem,
SidebarRail,
useSidebar,
} from '@/components/ui/sidebar';
@@ -125,6 +117,7 @@ import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import { ProfilerBoundary } from '@/lib/perf';
import { revealInFileManagerLabel } from '@/lib/platform-labels';
+import { revealEditorBeforeActing } from '@/lib/reveal-editor';
import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
import { buildFolderShareInput, runShareAction } from '@/lib/share/run-share-action';
import { useStickyAgent } from '@/lib/unified-agent-store';
@@ -132,10 +125,6 @@ import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils';
import { setViewMenuState } from '@/lib/view-menu-state-store';
-interface FileSidebarProps {
- onOpenSearch: () => void;
-}
-
const EMPTY_FOLDER_STATE: { folderCount: number; expandedCount: number } = {
folderCount: 0,
expandedCount: 0,
@@ -149,10 +138,10 @@ export function isInteractiveSidebarControl(target: EventTarget | null): boolean
return target.closest(SIDEBAR_INTERACTIVE_CONTROL_SELECTOR) !== null;
}
-export function FileSidebar({ onOpenSearch }: FileSidebarProps) {
+export function FileSidebar() {
return (
<ProfilerBoundary name="file-sidebar">
- <FileSidebarInner onOpenSearch={onOpenSearch} />
+ <FileSidebarInner />
</ProfilerBoundary>
);
}
@@ -187,10 +176,11 @@ function SettingsLoadingMenuGroupTooltip({
);
}
-function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
+function FileSidebarInner() {
const { t } = useLingui();
const settingsLoadingReasonId = useId();
const [tree, setTree] = useState<FileTreeHandle | null>(null);
+ const suppressTreeMenuFocusRestoreRef = useRef(false);
const { activeDocName, activeTarget } = useDocumentContext();
const activeCreateDir =
@@ -203,11 +193,8 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
- const { state: sidebarState, toggleSidebar } = useSidebar();
+ const { state: sidebarState, toggleSidebar, setOpen, dismissCover } = useSidebar();
const isEmbedded = useIsEmbedded();
- const isExpanded = sidebarState === 'expanded';
- const isCollapsed = sidebarState === 'collapsed';
- const shouldFadeChrome = isElectronHost && isCollapsed;
const [folderState, setFolderState] = useState(EMPTY_FOLDER_STATE);
@@ -409,31 +396,37 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
switch (action) {
case 'new-doc': {
if (!workspace || !tree) return;
+ revealEditorBeforeActing();
tree.startCreating('file', initialCreateDir);
return;
}
case 'new-folder': {
if (!workspace || !tree) return;
+ revealEditorBeforeActing();
tree.startCreating('folder', initialCreateDir);
return;
}
case 'new-from-template': {
if (!workspace || !tree) return;
+ revealEditorBeforeActing();
tree.startCreatingFromTemplate(initialCreateDir);
return;
}
case 'rename': {
if (!activeTarget || isOkManagedTarget) return;
+ revealEditorBeforeActing();
emitFileTreeMenuActionRename(activeTarget);
return;
}
case 'duplicate': {
if (!activeTarget || isOkManagedTarget) return;
+ revealEditorBeforeActing();
emitFileTreeMenuActionDuplicate(activeTarget);
return;
}
case 'move-to-trash': {
if (!activeTarget || isOkManagedTarget) return;
+ revealEditorBeforeActing();
emitFileTreeMenuActionDelete(activeTarget);
return;
}
@@ -521,30 +514,37 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
return;
}
case 'toggle-show-ok-folders': {
+ revealEditorBeforeActing();
patchSidebarVisibility({ showOkFolders: !showOkFolders });
return;
}
case 'toggle-show-hidden-files': {
+ revealEditorBeforeActing();
patchSidebarVisibility({ showHiddenFiles: !showHiddenFiles });
return;
}
case 'toggle-show-only-markdown-files': {
+ revealEditorBeforeActing();
patchSidebarVisibility({ showOnlyMarkdownFiles: !showOnlyMarkdownFiles });
return;
}
case 'toggle-show-skills-section': {
+ revealEditorBeforeActing();
patchSidebarVisibility({ showSkillsSection: !showSkillsSection });
return;
}
case 'expand-all-tree': {
+ revealEditorBeforeActing();
tree?.expandAll();
return;
}
case 'collapse-all-tree': {
+ revealEditorBeforeActing();
tree?.collapseAll();
return;
}
case 'toggle-sidebar': {
+ revealEditorBeforeActing();
toggleSidebar();
return;
}
@@ -584,7 +584,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
]);
return (
- <Sidebar variant="inset">
+ <Sidebar variant="inset" className="pt-0">
{pendingSettingsReason ? (
<span id={settingsLoadingReasonId} className="sr-only">
{pendingSettingsReason}
@@ -596,45 +596,12 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
{/* biome-ignore lint/a11y/noStaticElementInteractions: ContextMenuTrigger
* delegation surface — display:contents wrapper for the asChild Slot's
* single-child requirement. Keyboard equivalents live on the individual
- * interactive controls inside (toolbar buttons, search-pill button,
- * project switcher trigger, Pierre tree rows, sidebar rail); this wrapper
+ * interactive controls inside (toolbar buttons, Pierre tree rows,
+ * sidebar rail); this wrapper
* has no perceivable interactive surface of its own. The onContextMenu
* handler delegates the button-target opt-out for the sidebar-wide
* context menu — same a11y semantics as a Radix Slot. */}
<div className="contents" onContextMenu={handleSidebarSurfaceContextMenu}>
- <SidebarHeader
- data-electron-drag={isElectronHost ? '' : undefined}
- className={cn(
- 'flex-row h-12 items-center py-0 pl-3 pr-2',
- 'justify-between',
- isElectronHost && 'overflow-x-clip',
- isElectronHost &&
- 'motion-safe:transition-opacity motion-safe:duration-100 motion-safe:ease-out',
- isElectronHost && isExpanded && 'motion-safe:delay-100',
- shouldFadeChrome && 'opacity-0',
- isElectronHost && '[-webkit-app-region:drag]',
- )}
- >
- {isElectronHost ? (
- <div
- aria-hidden="true"
- data-testid="sidebar-traffic-light-reserve"
- className="w-[var(--ok-titlebar-reserve-left,0px)] shrink-0 self-stretch"
- />
- ) : null}
- <div className="ml-auto flex shrink-0 items-center gap-0.5 [&>*]:[-webkit-app-region:no-drag]">
- {}
- {isElectronHost && isExpanded ? <NavigationHistoryControls /> : null}
- {}
- <ErrorBoundary
- fallbackRender={() => null}
- onError={onPillRenderError}
- resetKeys={[sidebarState]}
- >
- <SidebarSearchBar onClick={onOpenSearch} />
- </ErrorBoundary>
- </div>
- </SidebarHeader>
<SidebarContent>
<ConflictsSection />
{}
@@ -644,9 +611,12 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
onOpenChange={setFilesOpen}
className="group/files flex min-h-0 flex-col data-[state=open]:min-h-48 data-[state=open]:flex-1"
>
- <SidebarGroup className="min-h-0 flex-1 px-0">
+ <SidebarGroup className="min-h-0 flex-1 px-0 pt-0">
{}
- <SidebarGroupLabel className="shrink-0 gap-1 rounded-none">
+ <SidebarGroupLabel
+ data-sidebar-project-row=""
+ className="h-11 shrink-0 gap-1 rounded-none"
+ >
<CollapsibleTrigger
data-sidebar-root-context
className="flex min-w-0 flex-1 items-center gap-1.5"
@@ -672,113 +642,136 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
icon={ListCollapse}
label={t`Tree view options`}
/>
- <DropdownMenuContent
- align="end"
- className="min-w-52"
- data-testid="tree-options-menu"
- >
- {showExpandAll ? (
- <DropdownMenuItem onSelect={() => tree?.expandAll()}>
- <UnfoldVertical aria-hidden="true" />
- <Trans>Expand all</Trans>
- </DropdownMenuItem>
- ) : null}
- {showCollapseAll ? (
- <DropdownMenuItem onSelect={() => tree?.collapseAll()}>
- <FoldVertical aria-hidden="true" />
- <Trans>Collapse all</Trans>
- </DropdownMenuItem>
- ) : null}
- {showTreeStateSection ? <DropdownMenuSeparator /> : null}
- {}
- <SettingsLoadingMenuGroupTooltip reason={pendingSettingsReason}>
- <DropdownMenuGroup aria-label={t`Show`}>
- <DropdownMenuLabel>
- <Trans>Show</Trans>
- </DropdownMenuLabel>
- <DropdownMenuCheckboxItem
- checked={showHiddenFiles}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showHiddenFiles: checked })
- }
- aria-disabled={pendingSettingsReason ? true : undefined}
- onSelect={preventPendingSettingsSelection}
- aria-describedby={
- pendingSettingsReason ? settingsLoadingReasonId : undefined
- }
- data-testid="tree-options-show-hidden-files"
- >
- <Trans>Hidden files</Trans>
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={showOkFolders}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showOkFolders: checked })
- }
- aria-disabled={pendingSettingsReason ? true : undefined}
- onSelect={preventPendingSettingsSelection}
- aria-describedby={
- pendingSettingsReason ? settingsLoadingReasonId : undefined
- }
- data-testid="tree-options-show-ok-folders"
- >
- <Trans>.ok folders</Trans>
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={showOnlyMarkdownFiles}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showOnlyMarkdownFiles: checked })
- }
- aria-disabled={pendingSettingsReason ? true : undefined}
- onSelect={preventPendingSettingsSelection}
- aria-describedby={
- pendingSettingsReason ? settingsLoadingReasonId : undefined
- }
- data-testid="tree-options-show-only-markdown-files"
- >
- <Trans>Only markdown files</Trans>
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={showSkillsSection}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showSkillsSection: checked })
- }
- aria-disabled={pendingSettingsReason ? true : undefined}
- onSelect={preventPendingSettingsSelection}
- aria-describedby={
- pendingSettingsReason ? settingsLoadingReasonId : undefined
- }
- data-testid="tree-options-show-skills"
+ {sidebarState === 'expanded' ? (
+ <DropdownMenuContent
+ align="end"
+ className="min-w-52"
+ data-testid="tree-options-menu"
+ onCloseAutoFocus={(event) => {
+ if (!suppressTreeMenuFocusRestoreRef.current) return;
+ suppressTreeMenuFocusRestoreRef.current = false;
+ event.preventDefault();
+ }}
+ >
+ {showExpandAll ? (
+ <DropdownMenuItem onSelect={() => tree?.expandAll()}>
+ <UnfoldVertical aria-hidden="true" />
+ <Trans>Expand all</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {showCollapseAll ? (
+ <DropdownMenuItem onSelect={() => tree?.collapseAll()}>
+ <FoldVertical aria-hidden="true" />
+ <Trans>Collapse all</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {showTreeStateSection ? <DropdownMenuSeparator /> : null}
+ {}
+ <SettingsLoadingMenuGroupTooltip reason={pendingSettingsReason}>
+ <DropdownMenuGroup aria-label={t`Show`}>
+ <DropdownMenuLabel>
+ <Trans>Show</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuCheckboxItem
+ checked={showHiddenFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showHiddenFiles: checked })
+ }
+ aria-disabled={pendingSettingsReason ? true : undefined}
+ onSelect={preventPendingSettingsSelection}
+ aria-describedby={
+ pendingSettingsReason ? settingsLoadingReasonId : undefined
+ }
+ data-testid="tree-options-show-hidden-files"
+ >
+ <Trans>Hidden files</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showOkFolders}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOkFolders: checked })
+ }
+ aria-disabled={pendingSettingsReason ? true : undefined}
+ onSelect={preventPendingSettingsSelection}
+ aria-describedby={
+ pendingSettingsReason ? settingsLoadingReasonId : undefined
+ }
+ data-testid="tree-options-show-ok-folders"
+ >
+ <Trans>.ok folders</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showOnlyMarkdownFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOnlyMarkdownFiles: checked })
+ }
+ aria-disabled={pendingSettingsReason ? true : undefined}
+ onSelect={preventPendingSettingsSelection}
+ aria-describedby={
+ pendingSettingsReason ? settingsLoadingReasonId : undefined
+ }
+ data-testid="tree-options-show-only-markdown-files"
+ >
+ <Trans>Only markdown files</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showSkillsSection}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showSkillsSection: checked })
+ }
+ aria-disabled={pendingSettingsReason ? true : undefined}
+ onSelect={preventPendingSettingsSelection}
+ aria-describedby={
+ pendingSettingsReason ? settingsLoadingReasonId : undefined
+ }
+ data-testid="tree-options-show-skills"
+ >
+ <Trans>Skills Studio</Trans>
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ </SettingsLoadingMenuGroupTooltip>
+ {}
+ {showSkillsSection ? (
+ <>
+ <DropdownMenuSeparator />
+ <SettingsLoadingMenuGroupTooltip reason={pendingSettingsReason}>
+ <DropdownMenuGroup>
+ <DropdownMenuCheckboxItem
+ checked={showSkillGroups}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showSkillGroups: checked })
+ }
+ aria-disabled={pendingSettingsReason ? true : undefined}
+ onSelect={preventPendingSettingsSelection}
+ aria-describedby={
+ pendingSettingsReason
+ ? settingsLoadingReasonId
+ : undefined
+ }
+ data-testid="tree-options-group-skills"
+ >
+ <Trans>Group skills by source</Trans>
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ </SettingsLoadingMenuGroupTooltip>
+ </>
+ ) : null}
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ data-files-hide=""
+ onSelect={() => {
+ suppressTreeMenuFocusRestoreRef.current = true;
+ setOpen(false);
+ dismissCover();
+ }}
>
- <Trans>Skills Studio</Trans>
- </DropdownMenuCheckboxItem>
+ <PanelLeftClose aria-hidden="true" />
+ <Trans>Hide Files</Trans>
+ </DropdownMenuItem>
</DropdownMenuGroup>
- </SettingsLoadingMenuGroupTooltip>
- {}
- {showSkillsSection ? (
- <>
- <DropdownMenuSeparator />
- <SettingsLoadingMenuGroupTooltip reason={pendingSettingsReason}>
- <DropdownMenuGroup>
- <DropdownMenuCheckboxItem
- checked={showSkillGroups}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showSkillGroups: checked })
- }
- aria-disabled={pendingSettingsReason ? true : undefined}
- onSelect={preventPendingSettingsSelection}
- aria-describedby={
- pendingSettingsReason ? settingsLoadingReasonId : undefined
- }
- data-testid="tree-options-group-skills"
- >
- <Trans>Group skills by source</Trans>
- </DropdownMenuCheckboxItem>
- </DropdownMenuGroup>
- </SettingsLoadingMenuGroupTooltip>
- </>
- ) : null}
- </DropdownMenuContent>
+ </DropdownMenuContent>
+ ) : null}
</DropdownMenu>
<ToolbarButton
icon={SquarePen}
@@ -822,18 +815,8 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
{}
{showSkillsSection ? <SkillsSidebarDock filesOpen={filesOpen} /> : null}
</SidebarContent>
- <SidebarFooter className="px-0">
+ <SidebarFooter className="px-0 empty:hidden">
<OnboardingCardMount />
- <UpdateNotices />
- {}
- <FeedbackCardMount />
- {typeof window !== 'undefined' && window.okDesktop ? (
- <SidebarMenu>
- <SidebarMenuItem>
- <ProjectSwitcher bridge={window.okDesktop} />
- </SidebarMenuItem>
- </SidebarMenu>
- ) : null}
</SidebarFooter>
{}
<SidebarRail
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index feeb50b72..7b3fff83a 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -123,6 +123,7 @@ import {
applyProblemIndicators,
FILE_TREE_PROBLEM_CSS,
OK_PROBLEM_BADGE_ATTR,
+ OK_PROBLEM_ROW_ATTR,
} from '@/components/file-tree-problem-indicators';
import {
applyRenameInputAffordance,
@@ -408,8 +409,15 @@ const FILE_TREE_CREATION_CLEARED_CSS = `
}
`;
+const FILE_TREE_NAME_FOREGROUND_CSS = `
+ [data-type="item"]:not([data-item-selected="true"]):not([data-item-git-status]):not([${OK_PROBLEM_ROW_ATTR}]) > [data-item-section="content"] {
+ color: var(--file-tree-foreground, var(--trees-fg));
+ }
+`;
+
const FILE_TREE_UNSAFE_CSS = [
OK_FILE_TREE_READONLY_UNSAFE_CSS,
+ FILE_TREE_NAME_FOREGROUND_CSS,
FILE_TREE_PROBLEM_CSS,
FILE_TREE_RENAME_INPUT_CSS,
FILE_TREE_ROOT_DROP_CSS,
@@ -799,7 +807,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
reconcileLocalRemoval,
reconcileLocalRename,
} = useDocumentContext();
- const { notifySidebarFileSelected } = useSidebar();
+ const { notifySidebarFileSelected, cover: filesCover } = useSidebar();
const { resolvedTheme } = useTheme();
const { addPage, pageMeta, pages } = usePageList();
const { okignoreBinding, merged } = useConfigContext();
@@ -866,10 +874,13 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
| { kind: 'folder'; folderPath: string }
| { kind: 'asset'; assetPath: string; entries?: readonly FileEntry[] },
) {
+ let editorDocName: string | null = null;
if (target.kind === 'doc') {
if (target.registerPage) addPage(target.docName);
- openTarget(navigationTargetForDocument(target.docName, target.size), previewOpenOptions);
+ const resolved = navigationTargetForDocument(target.docName, target.size);
+ openTarget(resolved, previewOpenOptions);
pushHashWithoutNavigation(hashFromDocName(target.docName));
+ if (resolved.kind === 'doc') editorDocName = resolved.docName;
} else if (target.kind === 'folder') {
openTarget(
{ kind: 'folder', target: target.folderPath, folderPath: target.folderPath },
@@ -893,7 +904,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
);
pushHashWithoutNavigation(hashFromAssetPath(target.assetPath));
}
- notifySidebarFileSelected();
+ notifySidebarFileSelected(editorDocName);
}
function activateTreePath(
treePath: string,
@@ -3002,7 +3013,10 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
const folderPath = treeDirectoryPathToFolderPath(path);
if (wasSelected) {
if (model.getSelectedPaths().length !== 1) return;
- if (isSameHash(window.location.hash, hashFromFolderPath(folderPath))) return;
+ if (isSameHash(window.location.hash, hashFromFolderPath(folderPath))) {
+ if (filesCover) queueMicrotask(() => notifySidebarFileSelected());
+ return;
+ }
}
queueMicrotask(() => navigateWithPulse({ kind: 'folder', folderPath }));
return;
@@ -3022,7 +3036,15 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
}
const docName = treeFilePathToDocumentDocName(path, documentsRef.current);
if (model.getSelectedPaths().length !== 1) return;
- if (isSameHash(window.location.hash, hashFromDocName(docName))) return;
+ if (isSameHash(window.location.hash, hashFromDocName(docName))) {
+ if (filesCover) {
+ const resolved = navigationTargetForDocument(docName, undefined);
+ queueMicrotask(() =>
+ notifySidebarFileSelected(resolved.kind === 'doc' ? resolved.docName : null),
+ );
+ }
+ return;
+ }
queueMicrotask(() => activateTreePath(path));
}
diff --git a/packages/app/src/components/GraphPanel.tsx b/packages/app/src/components/GraphPanel.tsx
index 9e8be459a..b197bcad3 100644
--- a/packages/app/src/components/GraphPanel.tsx
+++ b/packages/app/src/components/GraphPanel.tsx
@@ -109,7 +109,8 @@ async function fetchHubs(limit: number): Promise<HubEntry[]> {
return success.data.hubs;
}
-function navigateToDoc(docName: string) {
+function navigateToDoc(docName: string, onDestinationRequested?: (docName: string) => void) {
+ onDestinationRequested?.(docName);
window.location.assign(hashFromDocName(docName));
}
@@ -136,9 +137,11 @@ function getOrphanEmptyState(mode: OrphanMode): string {
function FullscreenOrphansView({
mode,
onModeChange,
+ onDestinationRequested,
}: {
mode: OrphanMode;
onModeChange: (mode: OrphanMode) => void;
+ onDestinationRequested?: (docName: string) => void;
}) {
const { t } = useLingui();
const {
@@ -194,7 +197,7 @@ function FullscreenOrphansView({
key={entry.docName}
type="button"
className="block w-full rounded-lg border border-border bg-background/80 px-3 py-2 text-left transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- onClick={() => navigateToDoc(entry.docName)}
+ onClick={() => navigateToDoc(entry.docName, onDestinationRequested)}
>
<div className="truncate text-sm font-medium">{entry.title}</div>
<div className="truncate text-xs text-muted-foreground">{entry.docName}</div>
@@ -207,7 +210,11 @@ function FullscreenOrphansView({
);
}
-function FullscreenHubsView() {
+function FullscreenHubsView({
+ onDestinationRequested,
+}: {
+ onDestinationRequested?: (docName: string) => void;
+}) {
const { t } = useLingui();
const {
data: hubs = [],
@@ -249,7 +256,7 @@ function FullscreenHubsView() {
key={hub.docName}
type="button"
className="block w-full rounded-lg border border-border bg-background/80 px-3 py-2 text-left transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- onClick={() => navigateToDoc(hub.docName)}
+ onClick={() => navigateToDoc(hub.docName, onDestinationRequested)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
@@ -269,7 +276,17 @@ function FullscreenHubsView() {
);
}
-export function GraphPanel({ activeDocName }: { activeDocName: string }) {
+export function GraphPanel({
+ activeDocName,
+ onDestinationRequested,
+}: {
+ activeDocName: string;
+ onDestinationRequested?: (
+ docName: string,
+ allowMissing?: boolean,
+ onComplete?: () => void,
+ ) => void;
+}) {
const { t } = useLingui();
const {
folderPaths,
@@ -283,6 +300,7 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
const [fullscreenMode, setFullscreenMode] = useState<FullscreenGraphMode>('explore');
const [orphanMode, setOrphanMode] = useState<OrphanMode>('both');
const [selectedNode, setSelectedNode] = useState<GraphNodeSelection | null>(null);
+ const [pendingOpenDocName, setPendingOpenDocName] = useState<string | null>(null);
const [stats, setStats] = useState<{ nodes: number; links: number } | null>(null);
const [clusters, setClusters] = useState<string[]>([]);
const [showUrlNodesDocked, setShowUrlNodesDocked] = useState(() =>
@@ -314,6 +332,8 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
if (isOverlayLayerOpen()) return;
+ e.preventDefault();
+ e.stopPropagation();
setIsExpanded(false);
};
window.addEventListener('keydown', onKeyDown, { capture: true });
@@ -364,6 +384,23 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
const hashForSelectedNode = (
selection: Parameters<typeof getHashForGraphDocSelection>[0],
): string => selectedNodeIntent?.hash ?? getHashForGraphDocSelection(selection);
+ const openSelectedNode = (
+ docName: string,
+ selection: Parameters<typeof getHashForGraphDocSelection>[0],
+ allowMissing = false,
+ ) => {
+ const hash = hashForSelectedNode(selection);
+ if (onDestinationRequested) {
+ setPendingOpenDocName(docName);
+ onDestinationRequested(selectedNodeIntent?.hashDocName ?? docName, allowMissing, () => {
+ setPendingOpenDocName(null);
+ setIsExpanded(false);
+ });
+ } else {
+ setIsExpanded(false);
+ }
+ window.location.assign(hash);
+ };
const selectedNodeState =
selectedNode === null
? null
@@ -374,24 +411,18 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
Icon: AlertTriangle,
actionLabel: t`Create page`,
secondaryLabel: selectedNode.docName,
- onAction: () => {
- const hash = hashForSelectedNode(selectedNode);
- setIsExpanded(false);
- window.location.assign(hash);
- },
+ onAction: () => openSelectedNode(selectedNode.docName, selectedNode, true),
}
- : selectedNode.kind === 'doc' && selectedNode.docName === activeDocName
+ : selectedNode.kind === 'doc' &&
+ selectedNode.docName === activeDocName &&
+ selectedNode.docName !== pendingOpenDocName
? {
eyebrow: t`Already open`,
description: t`This document is already active in the editor. Use Open to collapse the graph.`,
Icon: CheckCircle2,
actionLabel: t`Open`,
secondaryLabel: selectedNode.docName,
- onAction: () => {
- const hash = hashForSelectedNode(selectedNode);
- setIsExpanded(false);
- window.location.assign(hash);
- },
+ onAction: () => openSelectedNode(selectedNode.docName, selectedNode),
}
: selectedNode.kind === 'doc'
? {
@@ -400,11 +431,7 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
Icon: ArrowUpRight,
actionLabel: t`Open`,
secondaryLabel: selectedNode.docName,
- onAction: () => {
- const hash = hashForSelectedNode(selectedNode);
- setIsExpanded(false);
- window.location.assign(hash);
- },
+ onAction: () => openSelectedNode(selectedNode.docName, selectedNode),
}
: {
eyebrow: t`Selected in graph`,
@@ -574,7 +601,15 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
skillVisibility={skillVisibility}
className="h-full min-h-0"
docClickBehavior={isExpanded ? 'select' : 'navigate'}
- onSelectNode={isExpanded ? setSelectedNode : undefined}
+ onSelectNode={
+ isExpanded
+ ? (node) => {
+ setPendingOpenDocName(null);
+ setSelectedNode(node);
+ }
+ : undefined
+ }
+ onDestinationRequested={onDestinationRequested}
onBackgroundClick={
isExpanded
? () => {
@@ -623,9 +658,15 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
</div>
) : null}
{isExpanded && activeMode === 'orphans' ? (
- <FullscreenOrphansView mode={orphanMode} onModeChange={setOrphanMode} />
+ <FullscreenOrphansView
+ mode={orphanMode}
+ onModeChange={setOrphanMode}
+ onDestinationRequested={onDestinationRequested}
+ />
+ ) : null}
+ {isExpanded && activeMode === 'hubs' ? (
+ <FullscreenHubsView onDestinationRequested={onDestinationRequested} />
) : null}
- {isExpanded && activeMode === 'hubs' ? <FullscreenHubsView /> : null}
</Panel>
);
}
diff --git a/packages/app/src/components/GraphView.tsx b/packages/app/src/components/GraphView.tsx
index b50c505b4..44b1df2a2 100644
--- a/packages/app/src/components/GraphView.tsx
+++ b/packages/app/src/components/GraphView.tsx
@@ -433,10 +433,12 @@ function applyGraphNodeClick({
node,
docClickBehavior,
onSelectNode,
+ onDestinationRequested,
}: {
node: GraphNode;
docClickBehavior: GraphDocClickBehavior;
onSelectNode?: (selection: GraphNodeSelection) => void;
+ onDestinationRequested?: (docName: string) => void;
}): void {
const action = resolveGraphNodeClickAction(node, docClickBehavior);
@@ -446,6 +448,7 @@ function applyGraphNodeClick({
}
if (action.kind === 'navigate') {
+ if (node.kind === 'doc') onDestinationRequested?.(node.docName);
window.location.assign(action.hash);
return;
}
@@ -458,12 +461,14 @@ function handleGraphPointerTapTarget({
docClickBehavior,
selectedNodeId,
onSelectNode,
+ onDestinationRequested,
onBackgroundClick,
}: {
target: GraphPointerTarget;
docClickBehavior: GraphDocClickBehavior;
selectedNodeId: string | null;
onSelectNode?: (selection: GraphNodeSelection) => void;
+ onDestinationRequested?: (docName: string) => void;
onBackgroundClick?: () => void;
}): void {
if (target.kind === 'background' || target.kind === 'link') {
@@ -484,6 +489,7 @@ function handleGraphPointerTapTarget({
node: target.node,
docClickBehavior,
onSelectNode,
+ onDestinationRequested,
});
}
@@ -498,6 +504,7 @@ export function GraphView({
className = '',
docClickBehavior = 'navigate',
onSelectNode,
+ onDestinationRequested,
onBackgroundClick,
onStatsChange,
onClustersChange,
@@ -512,6 +519,7 @@ export function GraphView({
className?: string;
docClickBehavior?: GraphDocClickBehavior;
onSelectNode?: (selection: GraphNodeSelection) => void;
+ onDestinationRequested?: (docName: string) => void;
onBackgroundClick?: () => void;
onStatsChange?: (nodes: number, links: number, loading: boolean) => void;
onClustersChange?: (clusters: string[]) => void;
@@ -811,6 +819,7 @@ export function GraphView({
node,
docClickBehavior,
onSelectNode,
+ onDestinationRequested,
});
return true;
},
@@ -966,6 +975,7 @@ export function GraphView({
navigationIntentByNodeId,
onBackgroundClick,
onSelectNode,
+ onDestinationRequested,
selectedNodeId,
]);
@@ -1042,6 +1052,7 @@ export function GraphView({
docClickBehavior,
selectedNodeId,
onSelectNode,
+ onDestinationRequested,
onBackgroundClick,
});
}}
@@ -1326,6 +1337,7 @@ export function GraphView({
}
if (node.docName) {
const navigationIntent = navigationIntentByNodeId.get(node.id);
+ onDestinationRequested?.(navigationIntent?.hashDocName ?? node.docName);
window.location.assign(
navigationIntent?.hash ??
hashFromDocName(
diff --git a/packages/app/src/components/HeaderOverflowActions.tsx b/packages/app/src/components/HeaderOverflowActions.tsx
new file mode 100644
index 000000000..596c1e718
--- /dev/null
+++ b/packages/app/src/components/HeaderOverflowActions.tsx
@@ -0,0 +1,86 @@
+import { useLingui } from '@lingui/react/macro';
+import { MoreHorizontalIcon } from 'lucide-react';
+import type { ReactNode, Ref } from 'react';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
+import { cn } from '@/lib/utils';
+import { displayState } from './SyncStatusBadge';
+
+export const HEADER_OVERFLOW_SLACK_PX = 8;
+
+type SyncAttention = 'conflict' | 'offline' | 'auth-error' | 'paused';
+
+function syncAttentionOf(status: GitSyncStatus | null): SyncAttention | null {
+ if (!status?.hasRemote) return null;
+ const state = displayState(status);
+ if (state === 'conflict' || state === 'offline' || state === 'auth-error') return state;
+ if (state === 'disabled' && status.pausedReason) return 'paused';
+ return null;
+}
+
+interface HeaderOverflowActionsProps {
+ syncStatus: GitSyncStatus | null;
+ children: ReactNode;
+ triggerRef?: Ref<HTMLButtonElement>;
+}
+
+export function HeaderOverflowActions({
+ syncStatus,
+ children,
+ triggerRef,
+}: HeaderOverflowActionsProps) {
+ const { t } = useLingui();
+ const syncAttention = syncAttentionOf(syncStatus);
+ const syncAttentionLabel =
+ syncAttention === 'conflict'
+ ? t`Conflict`
+ : syncAttention === 'offline'
+ ? t`Offline`
+ : syncAttention === 'auth-error'
+ ? t`Reconnect required`
+ : syncAttention === 'paused'
+ ? t`Sync paused`
+ : null;
+ const overflowActionsLabel = syncAttentionLabel
+ ? t`More actions (${syncAttentionLabel})`
+ : t`More actions`;
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ ref={triggerRef}
+ variant="ghost"
+ size="icon-sm"
+ aria-label={overflowActionsLabel}
+ data-testid="header-overflow-actions-trigger"
+ className="relative shrink-0 text-muted-foreground"
+ >
+ <MoreHorizontalIcon aria-hidden="true" />
+ {syncAttention ? (
+ <span
+ aria-hidden="true"
+ data-testid="header-overflow-actions-sync-indicator"
+ data-sync-attention={syncAttention}
+ className={cn(
+ 'absolute top-0.5 end-0.5 size-1.5 rounded-full ring-1 ring-background',
+ syncAttention === 'auth-error' && 'bg-destructive',
+ syncAttention === 'offline' && 'bg-muted-foreground',
+ (syncAttention === 'conflict' || syncAttention === 'paused') && 'bg-amber-500',
+ )}
+ />
+ ) : null}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ aria-label={t`More actions`}
+ data-header-overflow-actions=""
+ className="flex w-auto max-w-[calc(100vw-1rem)] flex-wrap items-center justify-end gap-2 p-2"
+ >
+ {children}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/app/src/components/HeaderPaneButtons.dom.test.tsx b/packages/app/src/components/HeaderPaneButtons.dom.test.tsx
new file mode 100644
index 000000000..1e461a281
--- /dev/null
+++ b/packages/app/src/components/HeaderPaneButtons.dom.test.tsx
@@ -0,0 +1,520 @@
+import { act, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { HeaderPaneButtons, useHeaderPaneButtonSet } from '@/components/HeaderPaneButtons';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { ConfigContext } from '@/lib/config-context';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibility,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
+import {
+ configContextWithTerminal,
+ type ProjectTerminalSetting,
+ TERMINAL_SETTING_UNSET,
+} from '@/test-utils/config-context';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const HIDDEN: PaneVisibility = { open: false, onScreen: false };
+const SHOWN: PaneVisibility = { open: true, onScreen: true };
+const OPEN_OFF_SCREEN: PaneVisibility = { open: true, onScreen: false };
+
+const PRESSED_LOOK = ['bg-primary/10', 'text-primary'];
+const PRESSED_HOVER_LOOK = ['hover:bg-primary/15'];
+const HIGH_CONTRAST_OUTLINE = [
+ 'forced-colors:outline-solid',
+ 'forced-colors:outline-2',
+ 'contrast-more:outline-solid',
+ 'contrast-more:outline-2',
+];
+
+const ORIGINAL_PLATFORM = globalThis.navigator.platform;
+
+function setPlatform(platform: string): void {
+ Object.defineProperty(globalThis.navigator, 'platform', {
+ value: platform,
+ configurable: true,
+ });
+}
+
+const SETTINGS_LOADING: ProjectTerminalSetting = { synced: false, enabled: null };
+const TERMINAL_OFF: ProjectTerminalSetting = { synced: true, enabled: false };
+const TERMINAL_ON: ProjectTerminalSetting = { synced: true, enabled: true };
+
+function Providers({
+ setting,
+ children,
+}: {
+ setting: ProjectTerminalSetting;
+ children: ReactNode;
+}) {
+ return (
+ <ConfigContext value={configContextWithTerminal(setting)}>
+ <TooltipProvider delayDuration={0}>{children}</TooltipProvider>
+ </ConfigContext>
+ );
+}
+
+function renderButtons(setting: ProjectTerminalSetting = TERMINAL_SETTING_UNSET) {
+ const view = render(
+ <Providers setting={setting}>
+ <HeaderPaneButtons />
+ </Providers>,
+ );
+ return {
+ ...view,
+ setTerminalSetting(next: ProjectTerminalSetting) {
+ view.rerender(
+ <Providers setting={next}>
+ <HeaderPaneButtons />
+ </Providers>,
+ );
+ },
+ };
+}
+
+function paneButtonNames(): (string | null)[] {
+ return within(screen.getByRole('group', { name: 'Panels' }))
+ .getAllByRole('button')
+ .map((button) => button.getAttribute('aria-label'));
+}
+
+function recordRequests(): PaneVisibilityRequest[] {
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ return requests;
+}
+
+function PaneSetProbe() {
+ return <output data-testid="pane-set">{useHeaderPaneButtonSet().join(',')}</output>;
+}
+
+describe('HeaderPaneButtons', () => {
+ afterEach(() => {
+ __resetPaneVisibilityStoreForTests();
+ setPlatform(ORIGINAL_PLATFORM);
+ });
+
+ test('renders Agents then Terminal inside a group named Panels, after a divider', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: SHOWN });
+ renderButtons();
+
+ const group = screen.getByRole('group', { name: 'Panels' });
+ const names = within(group)
+ .getAllByRole('button')
+ .map((button) => button.getAttribute('aria-label'));
+ expect(names).toEqual(['Agents', 'Terminal']);
+ const divider = screen.getByTestId('header-pane-divider');
+ expect(divider.getAttribute('data-orientation')).toBe('vertical');
+ expect(divider.compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(divider.contains(group)).toBe(false);
+ });
+
+ test('each button is a 28px ghost icon button with a hidden glyph and a stable test id', () => {
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ renderButtons();
+
+ const agents = screen.getByTestId('header-pane-button-agents');
+ const terminal = screen.getByTestId('header-pane-button-terminal');
+ for (const button of [agents, terminal]) {
+ expect(button.tagName).toBe('BUTTON');
+ expect(button.getAttribute('data-variant')).toBe('ghost');
+ expect(button.getAttribute('data-size')).toBe('icon-sm');
+ expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
+ }
+ expect(agents.querySelector('svg')?.classList.contains('lucide-sparkles')).toBe(true);
+ expect(terminal.querySelector('svg')?.classList.contains('lucide-square-terminal')).toBe(true);
+ });
+
+ test('pressed state follows whether each pane is on screen and flips when the store publishes', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: SHOWN });
+ renderButtons();
+
+ const agents = screen.getByRole('button', { name: 'Agents' });
+ const terminal = screen.getByRole('button', { name: 'Terminal' });
+ expect(agents.getAttribute('aria-pressed')).toBe('false');
+ expect(terminal.getAttribute('aria-pressed')).toBe('true');
+
+ act(() => {
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ });
+
+ expect(screen.getByRole('button', { name: 'Agents' })).toBe(agents);
+ expect(agents.getAttribute('aria-pressed')).toBe('true');
+ expect(terminal.getAttribute('aria-pressed')).toBe('false');
+ });
+
+ test('a pane that is open but collapsed to zero size reads off, and a click asks to show it', async () => {
+ const user = userEvent.setup();
+ const requests = recordRequests();
+ paneVisibilityStore.publish({
+ editor: null,
+ agents: OPEN_OFF_SCREEN,
+ terminal: OPEN_OFF_SCREEN,
+ });
+ renderButtons();
+
+ const agents = screen.getByRole('button', { name: 'Agents' });
+ const terminal = screen.getByRole('button', { name: 'Terminal' });
+ expect(agents.getAttribute('aria-pressed')).toBe('false');
+ expect(terminal.getAttribute('aria-pressed')).toBe('false');
+ expectVisualClassTokensAbsent(agents.className, PRESSED_LOOK);
+
+ await user.click(agents);
+ await user.click(terminal);
+
+ expect(requests).toEqual([
+ { pane: 'agents', open: true },
+ { pane: 'terminal', open: true },
+ ]);
+ });
+
+ test('renders only Agents when no terminal can exist', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: null });
+ renderButtons();
+
+ const group = screen.getByRole('group', { name: 'Panels' });
+ expect(within(group).getByRole('button', { name: 'Agents' })).toBeTruthy();
+ expect(within(group).getAllByRole('button')).toHaveLength(1);
+ expect(screen.queryByTestId('header-pane-button-terminal')).toBeNull();
+ });
+
+ test('renders nothing, divider included, when the snapshot has no panes', () => {
+ const { container } = renderButtons();
+
+ expect(container.childElementCount).toBe(0);
+ expect(screen.queryByTestId('header-pane-divider')).toBeNull();
+ expect(screen.queryByRole('group', { name: 'Panels' })).toBeNull();
+
+ act(() => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: null });
+ });
+ expect(screen.getByTestId('header-pane-divider')).toBeTruthy();
+ });
+
+ test('a click asks for the opposite of the shown state and leaves focus on the button', async () => {
+ const user = userEvent.setup();
+ const requests = recordRequests();
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: SHOWN });
+ renderButtons();
+
+ const agents = screen.getByRole('button', { name: 'Agents' });
+ const terminal = screen.getByRole('button', { name: 'Terminal' });
+ await user.click(agents);
+ expect(document.activeElement).toBe(agents);
+ await user.click(terminal);
+ expect(document.activeElement).toBe(terminal);
+
+ expect(requests).toEqual([
+ { pane: 'agents', open: true },
+ { pane: 'terminal', open: false },
+ ]);
+ });
+
+ test('hiding a pane keeps focus on the button even when the pane hands focus elsewhere as it hides', async () => {
+ const user = userEvent.setup();
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: SHOWN });
+ renderButtons();
+ const elsewhere = document.createElement('div');
+ elsewhere.tabIndex = -1;
+ document.body.append(elsewhere);
+ paneVisibilityStore.subscribeRequests(({ open }) => {
+ if (!open) elsewhere.focus();
+ });
+
+ const terminal = screen.getByRole('button', { name: 'Terminal' });
+ await user.click(terminal);
+ await act(async () => {});
+
+ expect(document.activeElement).toBe(terminal);
+ elsewhere.remove();
+ });
+
+ test('each click acts on the state shown at that moment, not a local toggle', async () => {
+ const user = userEvent.setup();
+ const requests = recordRequests();
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: null });
+ renderButtons();
+
+ const agents = screen.getByRole('button', { name: 'Agents' });
+ await user.click(agents);
+ await user.click(agents);
+ act(() => {
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: null });
+ });
+ await user.click(agents);
+
+ expect(requests.map(({ open }) => open)).toEqual([true, true, false]);
+ });
+
+ test('Enter and Space on a focused button send the same request as a click', async () => {
+ const user = userEvent.setup();
+ const requests = recordRequests();
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ renderButtons();
+
+ const agents = screen.getByRole('button', { name: 'Agents' });
+ const terminal = screen.getByRole('button', { name: 'Terminal' });
+ act(() => agents.focus());
+ await user.keyboard('{Enter}');
+ act(() => terminal.focus());
+ await user.keyboard(' ');
+
+ expect(requests).toEqual([
+ { pane: 'agents', open: false },
+ { pane: 'terminal', open: true },
+ ]);
+ expect(document.activeElement).toBe(terminal);
+ });
+
+ test.each([
+ { platform: 'MacIntel', agents: '⌘ L', terminal: '⌘ J' },
+ { platform: 'Win32', agents: 'Ctrl L', terminal: 'Ctrl J' },
+ { platform: 'Linux x86_64', agents: 'Ctrl L', terminal: 'Ctrl J' },
+ ])(
+ 'tooltips name the button and its $platform shortcut, the same in both states',
+ async ({ platform, agents, terminal }) => {
+ setPlatform(platform);
+ const user = userEvent.setup();
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ renderButtons();
+
+ await user.tab();
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Agents' }));
+ const agentsTooltip = await screen.findByRole('tooltip');
+ expect(agentsTooltip.textContent).toBe(`Agents ${agents}`);
+ expect(agentsTooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(agents);
+
+ await user.tab();
+ const terminalTooltip = await screen.findByRole('tooltip');
+ expect(terminalTooltip.textContent).toBe(`Terminal ${terminal}`);
+
+ act(() => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: SHOWN });
+ });
+ expect((await screen.findByRole('tooltip')).textContent).toBe(`Terminal ${terminal}`);
+ await user.hover(screen.getByRole('button', { name: 'Agents' }));
+ expect((await screen.findByRole('tooltip', { name: /^Agents/ })).textContent).toBe(
+ `Agents ${agents}`,
+ );
+ },
+ );
+
+ test('pressed buttons carry the tinted look, a hover tint of their own and a high-contrast outline', () => {
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ renderButtons();
+
+ const on = screen.getByRole('button', { name: 'Agents' });
+ const off = screen.getByRole('button', { name: 'Terminal' });
+ expectVisualClassTokens(on.className, [
+ ...PRESSED_LOOK,
+ ...PRESSED_HOVER_LOOK,
+ ...HIGH_CONTRAST_OUTLINE,
+ ]);
+ expectVisualClassTokensAbsent(on.className, ['hover:bg-muted', 'text-muted-foreground']);
+ expectVisualClassTokens(off.className, ['text-muted-foreground', 'hover:bg-muted']);
+ expectVisualClassTokensAbsent(off.className, [
+ ...PRESSED_LOOK,
+ ...PRESSED_HOVER_LOOK,
+ ...HIGH_CONTRAST_OUTLINE,
+ ]);
+ });
+
+ test('useHeaderPaneButtonSet lists the panes to render in header order', () => {
+ render(
+ <Providers setting={TERMINAL_SETTING_UNSET}>
+ <PaneSetProbe />
+ </Providers>,
+ );
+ const probe = screen.getByTestId('pane-set');
+ expect(probe.textContent).toBe('');
+
+ act(() => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: null });
+ });
+ expect(probe.textContent).toBe('agents');
+
+ act(() => {
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ });
+ expect(probe.textContent).toBe('agents,terminal');
+ });
+
+ test('hides the Terminal button once the project settings say the terminal is off', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: HIDDEN });
+ renderButtons(TERMINAL_OFF);
+
+ expect(paneButtonNames()).toEqual(['Agents']);
+ expect(screen.queryByTestId('header-pane-button-terminal')).toBeNull();
+ expect(screen.getByTestId('header-pane-divider')).toBeTruthy();
+ });
+
+ test.each([
+ { state: 'while the project settings are still loading', setting: SETTINGS_LOADING },
+ { state: 'when the terminal is turned on', setting: TERMINAL_ON },
+ { state: 'when the project never set the terminal', setting: TERMINAL_SETTING_UNSET },
+ ])('shows the Terminal button $state', ({ setting }) => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: HIDDEN });
+ renderButtons(setting);
+
+ expect(paneButtonNames()).toEqual(['Agents', 'Terminal']);
+ });
+
+ test('keeps the Terminal button hidden while the settings rebind, until they say otherwise', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: HIDDEN });
+ const { setTerminalSetting } = renderButtons(TERMINAL_OFF);
+ expect(paneButtonNames()).toEqual(['Agents']);
+
+ setTerminalSetting(SETTINGS_LOADING);
+ expect(paneButtonNames(), 'the button popped in while the settings rebound').toEqual([
+ 'Agents',
+ ]);
+
+ setTerminalSetting(TERMINAL_OFF);
+ expect(paneButtonNames()).toEqual(['Agents']);
+
+ setTerminalSetting(TERMINAL_ON);
+ expect(paneButtonNames()).toEqual(['Agents', 'Terminal']);
+ });
+
+ test('turning the terminal on brings the Terminal button back at once, and turning it off hides it again', () => {
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: HIDDEN });
+ const { setTerminalSetting } = renderButtons(TERMINAL_OFF);
+ const agents = screen.getByRole('button', { name: 'Agents' });
+ expect(paneButtonNames()).toEqual(['Agents']);
+
+ setTerminalSetting(TERMINAL_ON);
+ expect(paneButtonNames()).toEqual(['Agents', 'Terminal']);
+ expect(screen.getByRole('button', { name: 'Terminal' }).getAttribute('aria-pressed')).toBe(
+ 'false',
+ );
+ expect(screen.getByRole('button', { name: 'Agents' })).toBe(agents);
+
+ setTerminalSetting(TERMINAL_OFF);
+ expect(paneButtonNames()).toEqual(['Agents']);
+ });
+
+ test('keeps the Terminal button shown while the settings rebind after the terminal was turned on', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: HIDDEN });
+ const { setTerminalSetting } = renderButtons(TERMINAL_OFF);
+ setTerminalSetting(TERMINAL_ON);
+ const terminal = screen.getByRole('button', { name: 'Terminal' });
+
+ setTerminalSetting(SETTINGS_LOADING);
+ expect(screen.getByRole('button', { name: 'Terminal' })).toBe(terminal);
+ });
+
+ test('a terminal pane open on its enable notice still shows no Terminal button', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: SHOWN });
+ renderButtons(TERMINAL_OFF);
+
+ expect(paneVisibilityStore.getSnapshot().terminal?.open).toBe(true);
+ expect(paneButtonNames()).toEqual(['Agents']);
+ expect(screen.getByRole('button', { name: 'Agents' }).getAttribute('aria-pressed')).toBe(
+ 'false',
+ );
+ });
+
+ test('useHeaderPaneButtonSet drops the terminal while it is turned off, so the header re-measures', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: HIDDEN });
+ const renderProbe = (setting: ProjectTerminalSetting) => (
+ <Providers setting={setting}>
+ <PaneSetProbe />
+ </Providers>
+ );
+ const view = render(renderProbe(SETTINGS_LOADING));
+ const probe = screen.getByTestId('pane-set');
+ expect(probe.textContent).toBe('agents,terminal');
+
+ view.rerender(renderProbe(TERMINAL_OFF));
+ expect(probe.textContent).toBe('agents');
+
+ view.rerender(renderProbe(SETTINGS_LOADING));
+ expect(probe.textContent).toBe('agents');
+
+ view.rerender(renderProbe(TERMINAL_ON));
+ expect(probe.textContent).toBe('agents,terminal');
+ });
+});
+
+describe('the Editor header button', () => {
+ afterEach(() => {
+ __resetPaneVisibilityStoreForTests();
+ setPlatform(ORIGINAL_PLATFORM);
+ });
+
+ test('a project window lists Editor first, then Agents and Terminal', () => {
+ paneVisibilityStore.publish({ editor: SHOWN, agents: HIDDEN, terminal: HIDDEN });
+ renderButtons();
+
+ const names = within(screen.getByRole('group', { name: 'Panels' }))
+ .getAllByRole('button')
+ .map((button) => button.getAttribute('aria-label'));
+ expect(names).toEqual(['Editor', 'Agents', 'Terminal']);
+ const editor = screen.getByTestId('header-pane-button-editor');
+ expect(editor.getAttribute('data-size')).toBe('icon-sm');
+ expect(editor.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ test('no Editor button appears where the snapshot has no editor pane', () => {
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: HIDDEN });
+ renderButtons();
+
+ expect(screen.queryByRole('button', { name: 'Editor' })).toBeNull();
+ });
+
+ test('its pressed state follows whether the editor is shown and it keeps its name', () => {
+ paneVisibilityStore.publish({ editor: SHOWN, agents: HIDDEN, terminal: null });
+ renderButtons();
+ const editor = screen.getByRole('button', { name: 'Editor' });
+ expect(editor.getAttribute('aria-pressed')).toBe('true');
+ expectVisualClassTokens(editor.className, PRESSED_LOOK);
+
+ act(() => {
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: null });
+ });
+ expect(editor.getAttribute('aria-pressed')).toBe('false');
+ expect(editor.getAttribute('aria-label')).toBe('Editor');
+ expectVisualClassTokensAbsent(editor.className, PRESSED_LOOK);
+ });
+
+ test('a click asks to hide a shown editor and show a hidden one, leaving focus on the button', async () => {
+ const user = userEvent.setup();
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ paneVisibilityStore.publish({ editor: SHOWN, agents: HIDDEN, terminal: null });
+ renderButtons();
+ const editor = screen.getByRole('button', { name: 'Editor' });
+
+ await user.click(editor);
+ act(() => {
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: null });
+ });
+ await user.keyboard('{Enter}');
+
+ expect(requests).toEqual([
+ { pane: 'editor', open: false },
+ { pane: 'editor', open: true },
+ ]);
+ expect(document.activeElement).toBe(editor);
+ });
+
+ test('its tooltip names it with no shortcut, on hover and on keyboard focus', async () => {
+ setPlatform('MacIntel');
+ const user = userEvent.setup();
+ paneVisibilityStore.publish({ editor: SHOWN, agents: HIDDEN, terminal: null });
+ renderButtons();
+
+ await user.tab();
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Editor' }));
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toBe('Editor');
+ expect(tooltip.querySelector('[data-slot="kbd"]')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/HeaderPaneButtons.tsx b/packages/app/src/components/HeaderPaneButtons.tsx
new file mode 100644
index 000000000..9bc5da611
--- /dev/null
+++ b/packages/app/src/components/HeaderPaneButtons.tsx
@@ -0,0 +1,132 @@
+import { useLingui } from '@lingui/react/macro';
+import { useEffect, useState, useSyncExternalStore } from 'react';
+import { PANE_ICON } from '@/components/pane-icons';
+import { Button } from '@/components/ui/button';
+import { Kbd } from '@/components/ui/kbd';
+import { Separator } from '@/components/ui/separator';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useTerminalConsentState } from '@/hooks/use-terminal-enabled';
+import {
+ formatShortcut,
+ formatShortcutLabel,
+ type KeyboardShortcutId,
+} from '@/lib/keyboard-shortcuts';
+import { type PaneId, paneVisibilityStore } from '@/lib/pane-visibility-store';
+import { cn } from '@/lib/utils';
+
+type HeaderPaneButtonState = {
+ readonly pane: PaneId;
+ readonly pressed: boolean;
+};
+
+const PANE_ORDER = ['editor', 'agents', 'terminal'] as const satisfies readonly PaneId[];
+
+type _PaneOrderDrift = Exclude<PaneId, (typeof PANE_ORDER)[number]>;
+const _paneOrderDriftGuard: [_PaneOrderDrift] extends [never]
+ ? true
+ : ['PANE_ORDER is missing a PaneId', _PaneOrderDrift] = true;
+void _paneOrderDriftGuard;
+
+const PANE_SHORTCUT = {
+ editor: null,
+ agents: 'toggle-agent-panel',
+ terminal: 'toggle-terminal-panel',
+} as const satisfies Record<PaneId, KeyboardShortcutId | null>;
+
+const PRESSED_CLASSES =
+ 'bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary outline-current -outline-offset-2 forced-colors:outline-solid forced-colors:outline-2 contrast-more:outline-solid contrast-more:outline-2';
+
+function useTerminalTurnedOff(): boolean {
+ const { enabled, synced } = useTerminalConsentState();
+ const [offWhenLastSynced, setOffWhenLastSynced] = useState(false);
+ useEffect(() => {
+ if (synced) setOffWhenLastSynced(enabled === false);
+ }, [enabled, synced]);
+ return synced ? enabled === false : offWhenLastSynced;
+}
+
+function useHeaderPaneButtonStates(): readonly HeaderPaneButtonState[] {
+ const snapshot = useSyncExternalStore(
+ paneVisibilityStore.subscribe,
+ paneVisibilityStore.getSnapshot,
+ paneVisibilityStore.getSnapshot,
+ );
+ const terminalTurnedOff = useTerminalTurnedOff();
+ return PANE_ORDER.flatMap((pane) => {
+ const visibility = snapshot[pane];
+ if (visibility === null) return [];
+ if (pane === 'terminal' && terminalTurnedOff) return [];
+ return [{ pane, pressed: visibility.onScreen }];
+ });
+}
+
+export function useHeaderPaneButtonSet(): readonly PaneId[] {
+ return useHeaderPaneButtonStates().map(({ pane }) => pane);
+}
+
+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 Icon = PANE_ICON[pane];
+ const shortcutId = PANE_SHORTCUT[pane];
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={name}
+ aria-pressed={pressed}
+ data-testid={`header-pane-button-${pane}`}
+ data-header-pane-button={pane}
+ onClick={(event) => {
+ const button = event.currentTarget;
+ if (pressed && paneVisibilityStore.isExclusive()) return;
+ paneVisibilityStore.request(pane, !pressed);
+ if (pressed) queueMicrotask(() => button.focus());
+ }}
+ className={cn('text-muted-foreground', pressed && PRESSED_CLASSES)}
+ >
+ <Icon aria-hidden="true" className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>{name}</span>
+ {shortcutId === null ? null : (
+ <>
+ {' '}
+ <Kbd aria-label={formatShortcutLabel(shortcutId)}>{formatShortcut(shortcutId)}</Kbd>
+ </>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+export function HeaderPaneButtons() {
+ const { t } = useLingui();
+ const buttons = useHeaderPaneButtonStates();
+ if (buttons.length === 0) return null;
+
+ return (
+ <div className="flex shrink-0 items-center gap-1" data-testid="header-pane-buttons">
+ <Separator
+ orientation="vertical"
+ data-testid="header-pane-divider"
+ className="mx-1 h-4 data-vertical:self-center forced-colors:border-l"
+ />
+ {/* biome-ignore lint/a11y/useSemanticElements: a cluster of pane toggles is not a form-control set; <fieldset> would impose form chrome, and ButtonGroup squares the pressed tint. */}
+ <div role="group" aria-label={t`Panels`} className="flex items-center gap-0.5">
+ {buttons.map(({ pane, pressed }) => (
+ <HeaderPaneButton key={pane} pane={pane} pressed={pressed} />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/SidebarSearchBar.dom.test.tsx b/packages/app/src/components/HeaderSearchBar.dom.test.tsx
similarity index 76%
rename from packages/app/src/components/SidebarSearchBar.dom.test.tsx
rename to packages/app/src/components/HeaderSearchBar.dom.test.tsx
index 98c6707a7..ef52d45d4 100644
--- a/packages/app/src/components/SidebarSearchBar.dom.test.tsx
+++ b/packages/app/src/components/HeaderSearchBar.dom.test.tsx
@@ -9,33 +9,33 @@ vi.doMock('@lingui/react/macro', () => ({
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
-async function renderSidebarSearchBar(onClick: () => void = () => {}) {
- const { SidebarSearchBar } = await import('./SidebarSearchBar');
+async function renderHeaderSearchBar(onClick: () => void = () => {}) {
+ const { HeaderSearchBar } = await import('./HeaderSearchBar');
const { TooltipProvider } = await import('@/components/ui/tooltip');
render(
<TooltipProvider>
- <SidebarSearchBar onClick={onClick} className="extra-class" />
+ <HeaderSearchBar onClick={onClick} className="extra-class" />
</TooltipProvider>,
);
}
-describe('SidebarSearchBar runtime behavior', () => {
+describe('HeaderSearchBar runtime behavior', () => {
afterEach(() => cleanup());
test('exports the component', async () => {
- const mod = await import('./SidebarSearchBar');
- expect(typeof mod.SidebarSearchBar).toBe('function');
+ const mod = await import('./HeaderSearchBar');
+ expect(typeof mod.HeaderSearchBar).toBe('function');
});
test('renders an accessible icon-only search button with the locked visual contract', async () => {
- await renderSidebarSearchBar();
+ await renderHeaderSearchBar();
const button = screen.getByRole('button', { name: 'Search' });
expect(button.tagName).toBe('BUTTON');
expect(button.getAttribute('aria-label')).toBe('Search');
expect(button.getAttribute('data-slot')).toBe('tooltip-trigger');
expect(button.getAttribute('data-variant')).toBe('ghost');
- expect(button.getAttribute('data-telemetry-event')).toBe('ok.sidebar.search_pill.click');
+ expect(button.getAttribute('data-telemetry-event')).toBe('ok.app_header.search.click');
expect(button.classList.contains('extra-class')).toBe(true);
expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
expect(button.textContent).toBe('');
@@ -44,7 +44,7 @@ describe('SidebarSearchBar runtime behavior', () => {
test('click delegates to the supplied handler', async () => {
const clicks: string[] = [];
- await renderSidebarSearchBar(() => clicks.push('click'));
+ await renderHeaderSearchBar(() => clicks.push('click'));
await userEvent.click(screen.getByRole('button', { name: /Search/ }));
diff --git a/packages/app/src/components/SidebarSearchBar.test.ts b/packages/app/src/components/HeaderSearchBar.test.ts
similarity index 58%
rename from packages/app/src/components/SidebarSearchBar.test.ts
rename to packages/app/src/components/HeaderSearchBar.test.ts
index cbcf01fbc..62bb73943 100644
--- a/packages/app/src/components/SidebarSearchBar.test.ts
+++ b/packages/app/src/components/HeaderSearchBar.test.ts
@@ -1,15 +1,15 @@
import { getParseHealth, resetParseHealth } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import { onPillRenderError } from './SidebarSearchBar';
+import { onPillRenderError } from './HeaderSearchBar';
-describe('SidebarSearchBar module', () => {
- test('exports the SidebarSearchBar component', async () => {
- const mod = await import('./SidebarSearchBar');
- expect(typeof mod.SidebarSearchBar).toBe('function');
+describe('HeaderSearchBar module', () => {
+ test('exports the HeaderSearchBar component', async () => {
+ const mod = await import('./HeaderSearchBar');
+ expect(typeof mod.HeaderSearchBar).toBe('function');
});
test('exports onPillRenderError as a named function', async () => {
- const mod = await import('./SidebarSearchBar');
+ const mod = await import('./HeaderSearchBar');
expect(typeof mod.onPillRenderError).toBe('function');
});
});
@@ -26,31 +26,31 @@ describe('onPillRenderError — Pattern C runtime observability emission', () =>
warnSpy.mockRestore();
});
- test('emits structured jsx-render-failure event with sidebarSearchPill surface label', () => {
- onPillRenderError(new Error('boom'), { componentStack: '\n at SidebarSearchBar' });
+ test('emits structured jsx-render-failure event with headerSearchPill surface label', () => {
+ onPillRenderError(new Error('boom'), { componentStack: '\n at HeaderSearchBar' });
expect(warnSpy).toHaveBeenCalledTimes(1);
expect(warnSpy).toHaveBeenCalledWith(
JSON.stringify({
event: 'jsx-render-failure',
- component: 'sidebarSearchPill',
- rawComponentName: 'sidebarSearchPill',
+ component: 'headerSearchPill',
+ rawComponentName: 'headerSearchPill',
error: 'Error: boom',
- stack: '\n at SidebarSearchBar',
+ stack: '\n at HeaderSearchBar',
}),
);
});
- test('increments the parse-health counter for sidebarSearchPill', () => {
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBeUndefined();
- onPillRenderError(new Error('first'), { componentStack: '\n at SidebarSearchBar' });
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBe(1);
- onPillRenderError(new Error('second'), { componentStack: '\n at SidebarSearchBar' });
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBe(2);
+ test('increments the parse-health counter for headerSearchPill', () => {
+ expect(getParseHealth().jsxRenderFailure.headerSearchPill).toBeUndefined();
+ onPillRenderError(new Error('first'), { componentStack: '\n at HeaderSearchBar' });
+ expect(getParseHealth().jsxRenderFailure.headerSearchPill).toBe(1);
+ onPillRenderError(new Error('second'), { componentStack: '\n at HeaderSearchBar' });
+ expect(getParseHealth().jsxRenderFailure.headerSearchPill).toBe(2);
});
test('normalizes non-Error throws via String(err) — react-error-boundary types error as unknown', () => {
- onPillRenderError('plain string throw', { componentStack: '\n at SidebarSearchBar' });
+ onPillRenderError('plain string throw', { componentStack: '\n at HeaderSearchBar' });
expect(warnSpy).toHaveBeenCalledTimes(1);
const payload = JSON.parse(String(warnSpy.mock.calls[0][0]));
@@ -59,10 +59,10 @@ describe('onPillRenderError — Pattern C runtime observability emission', () =>
test('carries componentStack through to the stack field', () => {
onPillRenderError(new Error('x'), {
- componentStack: '\n at SidebarSearchBar\n at FileSidebar',
+ componentStack: '\n at HeaderSearchBar\n at FileSidebar',
});
const payload = JSON.parse(String(warnSpy.mock.calls[0][0]));
- expect(payload.stack).toBe('\n at SidebarSearchBar\n at FileSidebar');
+ expect(payload.stack).toBe('\n at HeaderSearchBar\n at FileSidebar');
});
});
diff --git a/packages/app/src/components/SidebarSearchBar.tsx b/packages/app/src/components/HeaderSearchBar.tsx
similarity index 81%
rename from packages/app/src/components/SidebarSearchBar.tsx
rename to packages/app/src/components/HeaderSearchBar.tsx
index 58b06c638..95ca20bf0 100644
--- a/packages/app/src/components/SidebarSearchBar.tsx
+++ b/packages/app/src/components/HeaderSearchBar.tsx
@@ -8,7 +8,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { formatShortcut } from '@/lib/keyboard-shortcuts';
import { cn } from '@/lib/utils';
-interface SidebarSearchBarProps {
+interface HeaderSearchBarProps {
onClick: () => void;
className?: string;
}
@@ -18,16 +18,16 @@ export function onPillRenderError(error: unknown, info: ErrorInfo): void {
console.warn(
JSON.stringify({
event: 'jsx-render-failure',
- component: 'sidebarSearchPill',
- rawComponentName: 'sidebarSearchPill',
+ component: 'headerSearchPill',
+ rawComponentName: 'headerSearchPill',
error: String(err),
stack: info.componentStack,
}),
);
- incrementJsxRenderFailure('sidebarSearchPill');
+ incrementJsxRenderFailure('headerSearchPill');
}
-export function SidebarSearchBar({ onClick, className }: SidebarSearchBarProps) {
+export function HeaderSearchBar({ onClick, className }: HeaderSearchBarProps) {
const { t } = useLingui();
const label = t`Search`;
return (
@@ -38,7 +38,7 @@ export function SidebarSearchBar({ onClick, className }: SidebarSearchBarProps)
size="icon-sm"
onClick={onClick}
aria-label={label}
- data-telemetry-event="ok.sidebar.search_pill.click"
+ data-telemetry-event="ok.app_header.search.click"
className={cn('shrink-0 text-muted-foreground', className)}
>
<Search aria-hidden="true" />
diff --git a/packages/app/src/components/HelpPopover.dom.test.tsx b/packages/app/src/components/HelpPopover.dom.test.tsx
index 9d564c94b..bac2f5f9b 100644
--- a/packages/app/src/components/HelpPopover.dom.test.tsx
+++ b/packages/app/src/components/HelpPopover.dom.test.tsx
@@ -78,6 +78,13 @@ describe('HelpPopover runtime behavior', () => {
expect(screen.queryByText('Settings')).toBeNull();
});
+ test('the open popover is a dialog that screen readers announce as Resources, like its trigger', async () => {
+ await renderOpenHelpPopover();
+
+ const dialog = screen.getByRole('dialog', { name: 'Resources' });
+ expect(within(dialog).getByRole('navigation', { name: 'Community' })).not.toBeNull();
+ });
+
test('omits the desktop-only Report a bug action in the web host', async () => {
await renderOpenHelpPopover();
diff --git a/packages/app/src/components/HelpPopover.tsx b/packages/app/src/components/HelpPopover.tsx
index d654184a8..6eeafeec5 100644
--- a/packages/app/src/components/HelpPopover.tsx
+++ b/packages/app/src/components/HelpPopover.tsx
@@ -203,6 +203,7 @@ export const HelpPopover: FC = () => {
</Tooltip>
<PopoverContent
align="end"
+ aria-label={t`Resources`}
className="w-56 p-3 subtle-scrollbar max-h-(--radix-popover-content-available-height) overflow-y-auto data-[state=closed]:overflow-hidden"
>
{sections.map((section, index) => (
diff --git a/packages/app/src/components/InstanceBadge.tsx b/packages/app/src/components/InstanceBadge.tsx
index f6005dea2..23bf46202 100644
--- a/packages/app/src/components/InstanceBadge.tsx
+++ b/packages/app/src/components/InstanceBadge.tsx
@@ -1,4 +1,5 @@
import { useLingui } from '@lingui/react/macro';
+import { GitBranch } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { Badge } from './ui/badge';
@@ -7,9 +8,10 @@ const UNKNOWN_APP_VERSION = '0.0.0';
interface InstanceBadgeProps {
readonly className?: string;
+ readonly compact?: boolean;
}
-export function InstanceBadge({ className }: InstanceBadgeProps) {
+export function InstanceBadge({ className, compact = false }: InstanceBadgeProps) {
const { t } = useLingui();
const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
const label = bridge?.instanceLabel ?? null;
@@ -35,7 +37,12 @@ export function InstanceBadge({ className }: InstanceBadgeProps) {
className,
)}
>
- <span aria-hidden="true" className="max-w-40 truncate">
+ {compact ? <GitBranch aria-hidden="true" /> : null}
+ <span
+ aria-hidden="true"
+ data-instance-badge-label=""
+ className={cn('max-w-40 truncate', compact && 'sr-only')}
+ >
{label}
</span>
<span className="sr-only">{accessibleName}</span>
diff --git a/packages/app/src/components/LinksPanel.tsx b/packages/app/src/components/LinksPanel.tsx
index 2e5a5068b..93f4031e7 100644
--- a/packages/app/src/components/LinksPanel.tsx
+++ b/packages/app/src/components/LinksPanel.tsx
@@ -251,7 +251,13 @@ function LinkRow({
return row;
}
-function BacklinksSection({ docName }: { docName: string }) {
+function BacklinksSection({
+ docName,
+ onDestinationRequested,
+}: {
+ docName: string;
+ onDestinationRequested?: (docName: string) => void;
+}) {
const { t } = useLingui();
const {
folderPaths,
@@ -325,6 +331,7 @@ function BacklinksSection({ docName }: { docName: string }) {
anchor={backlink.anchor}
snippet={backlink.snippet}
href={hashFromDocName(navigationIntent.hashDocName, backlink.anchor)}
+ onClick={() => onDestinationRequested?.(navigationIntent.hashDocName)}
/>
);
})}
@@ -342,7 +349,13 @@ function BacklinksSection({ docName }: { docName: string }) {
);
}
-function ForwardLinksSection({ docName }: { docName: string }) {
+function ForwardLinksSection({
+ docName,
+ onDestinationRequested,
+}: {
+ docName: string;
+ onDestinationRequested?: (docName: string) => void;
+}) {
const { t } = useLingui();
const {
addPage,
@@ -380,7 +393,10 @@ function ForwardLinksSection({ docName }: { docName: string }) {
try {
await createPageFromSeedAndUpdate(seed, {
addPage,
- onCreated: navigateToDocHash,
+ onCreated: (createdDocName) => {
+ onDestinationRequested?.(createdDocName);
+ navigateToDocHash(createdDocName);
+ },
});
setCreatingKey(null);
} catch (err) {
@@ -468,6 +484,7 @@ function ForwardLinksSection({ docName }: { docName: string }) {
anchor={link.anchor}
snippet={link.snippet}
href={navigateHref}
+ onClick={() => onDestinationRequested?.(navigateHashDocName)}
/>
);
}
@@ -482,6 +499,7 @@ function ForwardLinksSection({ docName }: { docName: string }) {
anchor={link.anchor}
snippet={link.snippet}
href={navigateHref}
+ onClick={() => onDestinationRequested?.(navigateHashDocName)}
/>
);
}
@@ -529,7 +547,13 @@ function ForwardLinksSection({ docName }: { docName: string }) {
);
}
-function LocalFilesSection({ docName }: { docName: string }) {
+function LocalFilesSection({
+ docName,
+ onDestinationComplete,
+}: {
+ docName: string;
+ onDestinationComplete?: (target?: HTMLElement) => void;
+}) {
const { t } = useLingui();
const { pages, loading: pagesLoading, error: pageListError } = usePageList();
const { data, isLoading, error } = useQuery({
@@ -558,6 +582,7 @@ function LocalFilesSection({ docName }: { docName: string }) {
line: target.line + 1,
column: target.column + 1,
source: 'links',
+ onNavigated: onDestinationComplete,
};
rememberPendingSourceNavigation(docName, { kind: 'lint', detail });
window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail }));
@@ -657,15 +682,25 @@ function LocalFilesSection({ docName }: { docName: string }) {
);
}
-export function LinksPanel({ docName, className = '' }: { docName: string; className?: string }) {
+export function LinksPanel({
+ docName,
+ className = '',
+ onDestinationRequested,
+ onDestinationComplete,
+}: {
+ docName: string;
+ className?: string;
+ onDestinationRequested?: (docName: string) => void;
+ onDestinationComplete?: (target?: HTMLElement) => void;
+}) {
return (
<Panel className={className}>
<PanelBody className="px-0 py-0">
- <ForwardLinksSection docName={docName} />
+ <ForwardLinksSection docName={docName} onDestinationRequested={onDestinationRequested} />
<Separator />
- <LocalFilesSection docName={docName} />
+ <LocalFilesSection docName={docName} onDestinationComplete={onDestinationComplete} />
<Separator />
- <BacklinksSection docName={docName} />
+ <BacklinksSection docName={docName} onDestinationRequested={onDestinationRequested} />
</PanelBody>
</Panel>
);
diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsx
index 17848e13b..bb1c6d6ca 100644
--- a/packages/app/src/components/MermaidDocEditor.tsx
+++ b/packages/app/src/components/MermaidDocEditor.tsx
@@ -219,7 +219,7 @@ export function MermaidDocEditor({
}, [isSourceMode, undoManager]);
return (
- <main
+ <section
className="flex h-full min-h-0 flex-col bg-background"
aria-label={t`Mermaid diagram`}
data-mermaid-doc-editor=""
@@ -239,6 +239,6 @@ export function MermaidDocEditor({
</div>
)}
</div>
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/MermaidFileViewer.tsx b/packages/app/src/components/MermaidFileViewer.tsx
index bd4e0b4e1..d50277baf 100644
--- a/packages/app/src/components/MermaidFileViewer.tsx
+++ b/packages/app/src/components/MermaidFileViewer.tsx
@@ -53,7 +53,7 @@ export function MermaidFileViewer({ fileName, extension, ...source }: MermaidFil
const text = fetchState.content;
return (
- <main
+ <section
className="flex h-full min-h-0 flex-col bg-background"
aria-label={fileName}
data-mermaid-file-viewer=""
@@ -115,6 +115,6 @@ export function MermaidFileViewer({ fileName, extension, ...source }: MermaidFil
<TextViewer {...source} fileName={fileName} extension={extension} />
)}
</div>
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/NavigationHistoryControls.dom.test.tsx b/packages/app/src/components/NavigationHistoryControls.dom.test.tsx
index 1b1046d97..dcad61c9d 100644
--- a/packages/app/src/components/NavigationHistoryControls.dom.test.tsx
+++ b/packages/app/src/components/NavigationHistoryControls.dom.test.tsx
@@ -66,7 +66,6 @@ describe('NavigationHistoryControls', () => {
const group = screen.getByRole('group', { name: 'Navigation history' });
const back = screen.getByRole('button', { name: 'Back' });
const forward = screen.getByRole('button', { name: 'Forward' });
- expect(group.getAttribute('data-slot')).toBe('button-group');
expect(group.contains(back)).toBe(true);
expect(group.contains(forward)).toBe(true);
expect(back.getAttribute('data-variant')).toBe('ghost');
diff --git a/packages/app/src/components/NothingOpen.dom.test.tsx b/packages/app/src/components/NothingOpen.dom.test.tsx
new file mode 100644
index 000000000..2a1253414
--- /dev/null
+++ b/packages/app/src/components/NothingOpen.dom.test.tsx
@@ -0,0 +1,90 @@
+import { act, cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
+import { NothingOpen } from '@/components/NothingOpen';
+import { ConfigContext } from '@/lib/config-context';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibility,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
+import {
+ configContextWithTerminal,
+ type ProjectTerminalSetting,
+ TERMINAL_SETTING_UNSET,
+} from '@/test-utils/config-context';
+
+const HIDDEN: PaneVisibility = { open: false, onScreen: false };
+const TERMINAL_OFF: ProjectTerminalSetting = { synced: true, enabled: false };
+
+function renderNothingOpen(setting: ProjectTerminalSetting = TERMINAL_SETTING_UNSET) {
+ return render(
+ <ConfigContext value={configContextWithTerminal(setting)}>
+ <NothingOpen />
+ </ConfigContext>,
+ );
+}
+
+function openButtonNames(): string[] {
+ return screen.getAllByRole('button').map((button) => button.textContent ?? '');
+}
+
+afterEach(() => {
+ cleanup();
+ __resetPaneVisibilityStoreForTests();
+});
+
+describe('Nothing open', () => {
+ test('names itself with no hint line and offers every pane the header offers', () => {
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: HIDDEN });
+ renderNothingOpen();
+
+ expect(screen.getByRole('region', { name: 'Nothing open' })).toBeTruthy();
+ expect(screen.queryByText(/Turn panels on/)).toBeNull();
+ expect(openButtonNames()).toEqual(['Open editor', 'Open agents', 'Open terminal']);
+ });
+
+ test('offers no terminal where no terminal can exist', () => {
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: null });
+ renderNothingOpen();
+
+ expect(openButtonNames()).toEqual(['Open editor', 'Open agents']);
+ });
+
+ test('offers no terminal while the project has it turned off', () => {
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: HIDDEN });
+ renderNothingOpen(TERMINAL_OFF);
+
+ expect(openButtonNames()).toEqual(['Open editor', 'Open agents']);
+ });
+
+ test('each button asks for its pane to be shown', async () => {
+ const user = userEvent.setup();
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: HIDDEN });
+ renderNothingOpen();
+
+ await user.click(screen.getByRole('button', { name: 'Open editor' }));
+ await user.click(screen.getByRole('button', { name: 'Open agents' }));
+ await user.click(screen.getByRole('button', { name: 'Open terminal' }));
+
+ expect(requests).toEqual([
+ { pane: 'editor', open: true },
+ { pane: 'agents', open: true },
+ { pane: 'terminal', open: true },
+ ]);
+ });
+
+ test('shows no Ask AI box and can take focus itself', () => {
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: HIDDEN, terminal: null });
+ renderNothingOpen();
+ const region = screen.getByRole('region', { name: 'Nothing open' });
+
+ act(() => region.focus());
+
+ expect(document.activeElement).toBe(region);
+ expect(screen.queryByRole('textbox')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/NothingOpen.tsx b/packages/app/src/components/NothingOpen.tsx
new file mode 100644
index 000000000..78142c561
--- /dev/null
+++ b/packages/app/src/components/NothingOpen.tsx
@@ -0,0 +1,44 @@
+import { useLingui } from '@lingui/react/macro';
+import { useId } from 'react';
+import { useHeaderPaneButtonSet } from '@/components/HeaderPaneButtons';
+import { PaneLayoutIcon } from '@/components/icons/editor-pane';
+import { Button } from '@/components/ui/button';
+import { type PaneId, paneVisibilityStore } from '@/lib/pane-visibility-store';
+
+export function NothingOpen() {
+ const { t } = useLingui();
+ const titleId = useId();
+ const panes = useHeaderPaneButtonSet();
+ const openLabels: Record<PaneId, string> = {
+ editor: t`Open editor`,
+ agents: t`Open agents`,
+ terminal: t`Open terminal`,
+ };
+
+ return (
+ <section
+ data-nothing-open=""
+ tabIndex={-1}
+ aria-labelledby={titleId}
+ className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 p-6 text-center outline-none"
+ >
+ <PaneLayoutIcon className="mb-1 size-8 text-muted-foreground/60" />
+ <h2 id={titleId} className="font-medium text-base text-sidebar-hover-muted-foreground">
+ {t`Nothing open`}
+ </h2>
+ <div className="mt-2 flex flex-wrap justify-center gap-2">
+ {panes.map((pane) => (
+ <Button
+ key={pane}
+ variant="outline"
+ size="sm"
+ data-testid={`nothing-open-${pane}`}
+ onClick={() => paneVisibilityStore.request(pane, true)}
+ >
+ {openLabels[pane]}
+ </Button>
+ ))}
+ </div>
+ </section>
+ );
+}
diff --git a/packages/app/src/components/OutlinePanel.tsx b/packages/app/src/components/OutlinePanel.tsx
index 70b43a6ba..a2520b387 100644
--- a/packages/app/src/components/OutlinePanel.tsx
+++ b/packages/app/src/components/OutlinePanel.tsx
@@ -74,6 +74,7 @@ export interface OutlineNavDetail {
index: number;
slug: string;
mode: 'wysiwyg' | 'source';
+ onNavigated?: (target: HTMLElement) => void;
}
export const OUTLINE_NAV_EVENT = 'open-knowledge:outline-nav';
@@ -88,6 +89,7 @@ export function OutlinePanel(props: {
docName: string;
isSourceMode: boolean;
className?: string;
+ onNavigated?: (target: HTMLElement) => void;
}) {
return (
<ProfilerBoundary name="outline-panel">
@@ -100,10 +102,12 @@ function OutlinePanelInner({
docName,
isSourceMode,
className = '',
+ onNavigated,
}: {
docName: string;
isSourceMode: boolean;
className?: string;
+ onNavigated?: (target: HTMLElement) => void;
}) {
const { t } = useLingui();
const { pages, loading, error: pageListError } = usePageList();
@@ -162,6 +166,7 @@ function OutlinePanelInner({
index,
slug,
mode: isSourceMode ? 'source' : 'wysiwyg',
+ onNavigated,
};
if (detail.mode === 'source') {
rememberPendingSourceNavigation(docName, { kind: 'outline', detail });
@@ -229,7 +234,7 @@ function OutlinePanelInner({
className={cn(
'w-full cursor-pointer truncate py-1.5 pe-2 text-left text-sm transition-colors',
isActive
- ? 'font-medium text-primary'
+ ? 'font-medium text-[var(--secondary-panel-accent,var(--primary))]'
: 'text-muted-foreground hover:text-foreground',
)}
style={{ paddingLeft: `${(heading.level - 1) * LEVEL_W + 20}px` }}
diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsx
index 92bbf1f95..a5637004b 100644
--- a/packages/app/src/components/ProblemsPanel.tsx
+++ b/packages/app/src/components/ProblemsPanel.tsx
@@ -86,6 +86,7 @@ export interface LintNavDetail {
column: number;
source?: string;
frontmatterScope?: FrontmatterScope;
+ onNavigated?: (target: HTMLElement) => void;
}
export const LINT_NAV_EVENT = 'open-knowledge:lint-nav';
@@ -462,6 +463,8 @@ export function ProblemsPanel({
onAutoFix,
onAskAi,
onFixWithAi,
+ onDestinationComplete,
+ onDestinationRequested,
}: {
docName: string;
diagnostics: DiagnosticLike[];
@@ -471,6 +474,13 @@ export function ProblemsPanel({
onAutoFix?: () => void;
onAskAi?: (diagnostic: DiagnosticLike) => void;
onFixWithAi?: (scope: PanelScope) => void;
+ onDestinationComplete?: (target: HTMLElement) => void;
+ onDestinationRequested?: (
+ docName: string,
+ allowMissing?: boolean,
+ onReady?: () => void,
+ completion?: 'synced' | 'navigated',
+ ) => void;
}) {
const { t } = useLingui();
const panelRef = useRef<HTMLElement>(null);
@@ -606,7 +616,7 @@ export function ProblemsPanel({
useEffect(() => subscribeToProjectFixSweepSettled(() => onSweepSettledRef.current()), []);
function handleNav(diagnostic: DiagnosticLike) {
- const detail = lintNavDetailOf(docName, diagnostic);
+ const detail = { ...lintNavDetailOf(docName, diagnostic), onNavigated: onDestinationComplete };
rememberPendingSourceNavigation(docName, { kind: 'lint', detail });
window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail }));
}
@@ -617,10 +627,22 @@ export function ProblemsPanel({
handleNav(diagnostic);
return;
}
+ const detail = {
+ ...lintNavDetailOf(targetDocName, diagnostic),
+ onNavigated: onDestinationComplete,
+ };
rememberPendingSourceNavigation(targetDocName, {
kind: 'lint',
- detail: lintNavDetailOf(targetDocName, diagnostic),
+ detail,
});
+ onDestinationRequested?.(
+ targetDocName,
+ false,
+ () => {
+ window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail }));
+ },
+ 'navigated',
+ );
window.location.hash = hashFromDocName(targetDocName);
}
diff --git a/packages/app/src/components/ProjectSwitcher.dom.test.tsx b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
index 043ea2856..2494656ba 100644
--- a/packages/app/src/components/ProjectSwitcher.dom.test.tsx
+++ b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
@@ -108,14 +108,6 @@ vi.doMock('@/components/ui/input-group', () => ({
InputGroupInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
}));
-vi.doMock('@/components/ui/sidebar', () => ({
- SidebarMenuButton: ({ children, ...props }: ItemProps) => (
- <button type="button" {...props}>
- {children}
- </button>
- ),
-}));
-
vi.doMock('./CreateProjectDialog', () => ({
CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
createDialogProps.push(props);
@@ -251,8 +243,7 @@ describe('ProjectSwitcher dropdown behavior', () => {
const bridge = createBridge();
render(<ProjectSwitcher bridge={bridge as never} />);
- expect(screen.getByTestId('project-switcher-trigger').textContent).toContain('current');
- expect(screen.getByTestId('project-switcher-trigger').textContent).toContain('main');
+ expect(screen.getByTestId('project-switcher-name').textContent).toBe('current');
await openMenu();
@@ -306,14 +297,15 @@ describe('ProjectSwitcher dropdown behavior', () => {
expect(createDialogProps.at(-1)?.bridge).toBe(bridge);
});
- test('keeps a nested project name visible alongside its repository and branch', () => {
+ test('names the repository for a nested project and leaves its folder and branch to the editor footer', () => {
const bridge = createBridge();
bridge.config.projectName = 'docs';
render(<ProjectSwitcher bridge={bridge as never} />);
+ expect(screen.getByTestId('project-switcher-name').textContent).toBe('current');
const trigger = screen.getByTestId('project-switcher-trigger');
- expect(trigger.textContent).toContain('current');
- expect(trigger.textContent).toContain('docs');
- expect(trigger.textContent).toContain('main');
+ expect(trigger.textContent).not.toContain('docs');
+ expect(trigger.textContent).not.toContain('main');
+ expect(trigger.getAttribute('title')).toBe('/projects/current');
});
test('the per-row × removes a recent from the list without opening it', async () => {
diff --git a/packages/app/src/components/ProjectSwitcher.tsx b/packages/app/src/components/ProjectSwitcher.tsx
index 760519c5a..5e6b23420 100644
--- a/packages/app/src/components/ProjectSwitcher.tsx
+++ b/packages/app/src/components/ProjectSwitcher.tsx
@@ -1,7 +1,8 @@
import { Trans, useLingui } from '@lingui/react/macro';
import {
- ChevronsUpDown,
+ ChevronDown,
FileText,
+ Folder,
FolderOpen,
GitBranch,
LayoutGrid,
@@ -9,6 +10,7 @@ import {
Search,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
+import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
@@ -18,16 +20,14 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
-import { SidebarMenuButton } from '@/components/ui/sidebar';
import { useCurrentBranch } from '@/hooks/use-current-branch';
import { useWorktrees } from '@/hooks/use-worktrees';
import type { OkDesktopBridge, RecentProjectEntry } from '@/lib/desktop-bridge-types';
import { runWithToast as runWithToastBase } from '@/lib/error-state';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
-import { cn } from '@/lib/utils';
import { CreateProjectDialog } from './CreateProjectDialog';
+import { checkoutIdentity } from './checkout-identity';
import { NewWorktreeDialog } from './NewWorktreeDialog';
-import { basenameOf } from './project-switcher-recents';
import { RecentProjectsMenu } from './RecentProjectsMenu';
export const runWithToast = (
@@ -146,30 +146,22 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
const loadedRecents = recents ?? [];
const menuRecents = loadedRecents;
const menuWorktreeModel = worktreeModel;
- const triggerName =
- worktreeModel !== null ? basenameOf(worktreeModel.mainRoot) : bridge.config.projectName;
- const currentCheckout = worktreeModel?.entries.find((entry) => entry.isCurrent) ?? null;
- const checkoutName =
- branch ??
- (currentCheckout?.worktreePath !== null && currentCheckout?.worktreePath !== undefined
- ? basenameOf(currentCheckout.worktreePath)
- : null);
- const projectScopeName =
- bridge.config.projectName === triggerName ? null : bridge.config.projectName;
- const triggerCheckout = [projectScopeName, checkoutName]
- .filter((value) => value !== null)
- .join(' · ');
+ const { repositoryName } = checkoutIdentity({
+ projectName: bridge.config.projectName,
+ branch,
+ worktreeModel,
+ });
+ const triggerName = repositoryName ?? bridge.config.projectName;
return (
<>
{}
<DropdownMenu open={open} onOpenChange={handleOpenChange} modal={false}>
<DropdownMenuTrigger asChild>
- <SidebarMenuButton
- className={cn(
- 'justify-between text-sidebar-foreground/70 hover:text-sidebar-foreground! data-open:hover:text-sidebar-foreground!',
- triggerCheckout.length > 0 && 'h-auto py-1.5',
- )}
+ <Button
+ variant="ghost"
+ size="sm"
+ className="max-w-[min(100%,15rem)] min-w-0"
data-testid="project-switcher-trigger"
aria-label={t`Open project menu`}
title={bridge.config.projectPath}
@@ -192,24 +184,20 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
: undefined
}
>
- <span className="flex min-w-0 flex-col gap-0.5">
- <span className="truncate">{triggerName}</span>
- {triggerCheckout.length > 0 ? (
- <span
- className="flex min-w-0 items-center gap-1 text-xs text-sidebar-foreground/50 group-hover/menu-button:text-sidebar-foreground"
- data-testid="project-switcher-branch"
- >
- <GitBranch aria-hidden="true" className="size-3! shrink-0" />
- <span className="truncate">{triggerCheckout}</span>
- </span>
- ) : null}
+ <Folder aria-hidden="true" className="size-4" />
+ <span
+ className="min-w-0 truncate"
+ data-app-header-center-label=""
+ data-testid="project-switcher-name"
+ >
+ {triggerName}
</span>
- <ChevronsUpDown aria-hidden="true" className="opacity-60" />
- </SidebarMenuButton>
+ <ChevronDown aria-hidden="true" className="size-4 opacity-60" />
+ </Button>
</DropdownMenuTrigger>
<DropdownMenuContent
- align="start"
- side="top"
+ align="center"
+ side="bottom"
className="min-w-[260px]"
data-testid="project-switcher-menu"
>
diff --git a/packages/app/src/components/ReportBugDialogBody.tsx b/packages/app/src/components/ReportBugDialogBody.tsx
index fd4d8f50f..32dbf5991 100644
--- a/packages/app/src/components/ReportBugDialogBody.tsx
+++ b/packages/app/src/components/ReportBugDialogBody.tsx
@@ -326,7 +326,10 @@ function ReportBugDialog({
</DialogHeader>
<DialogBody className="flex flex-auto flex-col gap-2 pb-2 [&>*]:shrink-0">
{crashInvite !== undefined && (
- <div className="flex items-start gap-2.5 rounded-md border border-chart-3/35 bg-chart-3/10 px-3 py-2.5 text-sm">
+ <div
+ data-testid="report-bug-crash-invite"
+ className="flex items-start gap-2.5 rounded-md border border-chart-3/35 bg-chart-3/10 px-3 py-2.5 text-sm"
+ >
<TriangleAlertIcon
className="mt-0.5 size-4 shrink-0 text-chart-3"
aria-hidden="true"
diff --git a/packages/app/src/components/SessionsHost.agents.dom.test.tsx b/packages/app/src/components/SessionsHost.agents.dom.test.tsx
index f16f9229a..a398181af 100644
--- a/packages/app/src/components/SessionsHost.agents.dom.test.tsx
+++ b/packages/app/src/components/SessionsHost.agents.dom.test.tsx
@@ -1,7 +1,7 @@
import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { useEffect, useState, useSyncExternalStore } from 'react';
+import { StrictMode, useEffect, useState, useSyncExternalStore } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { requestSendToOpenChat, subscribeSendInThread } from '@/comments/open-chat-send';
import { TooltipProvider } from '@/components/ui/tooltip';
@@ -18,6 +18,7 @@ import {
} from '@/lib/acp/thread-draft-staging';
import type { ThreadRenderModel } from '@/lib/acp/thread-event-model';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { IN_APP_THREAD_ID, saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';
import type { ThreadLaunchIntent } from './EditorPane';
import { requestPreferredSession } from './handoff/preferred-session-events';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
@@ -136,6 +137,7 @@ vi.doMock('@/lib/acp/thread-client', () => ({
),
useAgentThreadUnread: (threadId: string) => unreadThreadIds.has(threadId),
getAgentThreadClient: () => ({
+ getConnectionGeneration: () => 0,
closeThread,
renameThread,
openArchivedThread,
@@ -212,6 +214,9 @@ vi.doMock('@/lib/acp/launch-agent-thread', () => ({
launchAgentThread,
hasInflightThreadLaunch: () => mockInflightLaunch,
}));
+vi.doMock('./TerminalGate', () => ({
+ TerminalGate: () => <span data-testid="preferred-terminal-session" />,
+}));
let catalogData: unknown;
let catalogLoading = false;
@@ -301,21 +306,31 @@ function makeControl(): { current: HarnessControl | null } {
function Harness({
bridge: initialBridge = null,
initialVisible = true,
+ hostKey,
+ placementProbe = false,
+ externalPlacement,
onVisibleChange,
threadLaunch: initialThreadLaunch = null,
control,
initiallyRestoreSettled = true,
initialShowing,
onRequestEditorFocus,
+ onPreferredSessionHostReady,
+ installedClis = {},
}: {
bridge?: OkDesktopBridge | null;
initialVisible?: boolean;
+ hostKey?: string;
+ placementProbe?: boolean;
+ externalPlacement?: HTMLDivElement;
onVisibleChange?: (v: boolean) => void;
threadLaunch?: ThreadLaunchIntent | null;
control?: { current: HarnessControl | null };
initiallyRestoreSettled?: boolean;
initialShowing?: boolean;
onRequestEditorFocus?: () => void;
+ onPreferredSessionHostReady?: () => void;
+ installedClis?: { claude?: boolean };
}) {
const [container, setContainer] = useState<HTMLDivElement | null>(null);
const [visible, setVisible] = useState(initialVisible);
@@ -340,8 +355,12 @@ function Harness({
}, [control]);
return (
<TooltipProvider>
- <div ref={setContainer} data-testid="dock-container" />
+ <div ref={setContainer} data-testid="dock-container">
+ {placementProbe ? <span data-testid="consumer-owned-placement-content" /> : null}
+ </div>
<SessionsHost
+ {...(onPreferredSessionHostReady ? { onPreferredSessionHostReady } : {})}
+ key={hostKey}
surface="agents-panel"
bridge={bridge}
terminalCapable={bridge != null}
@@ -352,8 +371,8 @@ function Harness({
onVisibleChange?.(v);
setVisible(v);
}}
- installedClis={{}}
- container={container}
+ installedClis={installedClis}
+ container={externalPlacement ?? container}
isShowing={showing && container != null}
onRequestEditorFocus={onRequestEditorFocus ?? (() => {})}
/>
@@ -361,6 +380,27 @@ function Harness({
);
}
+function DualDesktopPreferredHosts({ bridge }: { bridge: OkDesktopBridge }) {
+ const [terminalContainer, setTerminalContainer] = useState<HTMLDivElement | null>(null);
+ return (
+ <TooltipProvider>
+ <Harness bridge={bridge} initialVisible={false} installedClis={{ claude: true }} />
+ <div ref={setTerminalContainer} data-testid="terminal-host-container" />
+ <SessionsHost
+ surface="terminal-dock"
+ bridge={bridge}
+ terminalCapable
+ visible={false}
+ onVisibleChange={() => {}}
+ installedClis={{ claude: true }}
+ container={terminalContainer}
+ isShowing={false}
+ onRequestEditorFocus={() => {}}
+ />
+ </TooltipProvider>
+ );
+}
+
describe('SessionsHost — agents desktop order-restore gate', () => {
beforeEach(() => {
openThreads = [];
@@ -957,6 +997,97 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
vi.restoreAllMocks();
});
+ test('a replaced host removes its attachment from the persistent placement', async () => {
+ setOpenThreads([makeThread({ threadId: 'gap-probe', title: 'Gap probe' })]);
+ const view = render(<Harness hostKey="first" placementProbe />);
+ const placement = screen.getByTestId('dock-container');
+ const consumerContent = screen.getByTestId('consumer-owned-placement-content');
+ const firstTab = await screen.findByRole('tab', { name: /Gap probe/ });
+ const firstAttachment = Array.from(placement.children).find((child) =>
+ child.contains(firstTab),
+ );
+ expect(firstAttachment).toBeDefined();
+
+ view.rerender(<Harness hostKey="second" placementProbe />);
+
+ const nextTab = await screen.findByRole('tab', { name: /Gap probe/ });
+ expect(placement.contains(nextTab)).toBe(true);
+ expect(firstAttachment?.isConnected).toBe(false);
+ expect(placement.contains(firstAttachment ?? null)).toBe(false);
+ expect(screen.getByTestId('consumer-owned-placement-content')).toBe(consumerContent);
+ expect(placement.contains(consumerContent)).toBe(true);
+ });
+
+ test('owner lifetime removes its attachment on final unmount and keeps consumer content', async () => {
+ setOpenThreads([makeThread({ threadId: 'owner-final', title: 'Owner final' })]);
+ const placement = document.createElement('div');
+ const consumerContent = document.createElement('span');
+ placement.append(consumerContent);
+ document.body.append(placement);
+
+ try {
+ const view = render(<Harness externalPlacement={placement} />);
+ const tab = await screen.findByRole('tab', { name: /Owner final/ });
+ const attachment = Array.from(placement.children).find((child) => child.contains(tab));
+ expect(attachment).toBeDefined();
+ expect(attachment?.isConnected).toBe(true);
+
+ view.unmount();
+
+ expect(attachment?.isConnected).toBe(false);
+ expect(placement.contains(attachment ?? null)).toBe(false);
+ expect(consumerContent.isConnected).toBe(true);
+ expect(placement.contains(consumerContent)).toBe(true);
+ } finally {
+ placement.remove();
+ }
+ });
+
+ test('owner lifetime keeps one attachment through StrictMode rehearsal and retires replacements', async () => {
+ setOpenThreads([makeThread({ threadId: 'owner-strict', title: 'Owner strict' })]);
+ const placement = document.createElement('div');
+ const consumerContent = document.createElement('span');
+ placement.append(consumerContent);
+ document.body.append(placement);
+
+ try {
+ const view = render(
+ <StrictMode>
+ <Harness hostKey="first" externalPlacement={placement} />
+ </StrictMode>,
+ );
+ const firstTab = await screen.findByRole('tab', { name: /Owner strict/ });
+ const firstAttachment = Array.from(placement.children).find((child) =>
+ child.contains(firstTab),
+ );
+ expect(firstAttachment).toBeDefined();
+ expect(placement.children).toHaveLength(2);
+
+ view.rerender(
+ <StrictMode>
+ <Harness hostKey="second" externalPlacement={placement} />
+ </StrictMode>,
+ );
+
+ const nextTab = await screen.findByRole('tab', { name: /Owner strict/ });
+ const nextAttachment = Array.from(placement.children).find((child) =>
+ child.contains(nextTab),
+ );
+ expect(nextAttachment).toBeDefined();
+ expect(nextAttachment).not.toBe(firstAttachment);
+ expect(firstAttachment?.isConnected).toBe(false);
+ expect(placement.children).toHaveLength(2);
+ expect(placement.contains(consumerContent)).toBe(true);
+
+ view.unmount();
+
+ expect(nextAttachment?.isConnected).toBe(false);
+ expect(consumerContent.isConnected).toBe(true);
+ } finally {
+ placement.remove();
+ }
+ });
+
test('a thread-launch intent carrying an image attachment forwards it to launchAgentThread', async () => {
render(
<Harness
@@ -1203,6 +1334,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
const panelLayout = screen.getByTestId('agent-panel-layout');
expect(sessionSurface.hasAttribute('inert')).toBe(true);
expect(screen.getByTestId('agent-thread-history-surface').parentElement).toBe(panelLayout);
+ expect(
+ screen.getByTestId('agent-thread-history-surface').className.split(/\s+/),
+ 'the cover sits over the draggable chat top bar, so it opts out of the window-drag region',
+ ).toContain('[-webkit-app-region:no-drag]');
expect(screen.getByRole('tab', { name: /Live conversation/ })).toBeDefined();
await user.keyboard('{Escape}');
@@ -1400,6 +1535,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
null,
null,
undefined,
+ undefined,
);
expect(screen.queryByTestId('agent-thread-history-panel')).toBeNull();
});
@@ -1618,6 +1754,24 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
await waitFor(() => expect(onVisibleChange).toHaveBeenCalledWith(true));
});
+ test('a thread seeded by a visible Chat does not reopen Chat after the user switches away', async () => {
+ setInitialRosterIds(new Set());
+ mockRegisteredAgent = FIRST_AGENT;
+ const control = makeControl();
+ const onVisibleChange = vi.fn((_v: boolean) => {});
+ render(<Harness initialVisible={false} onVisibleChange={onVisibleChange} control={control} />);
+
+ act(() => control.current?.setVisible(true));
+ await waitFor(() => expect(launchAgentThread).toHaveBeenCalledTimes(1));
+ act(() => control.current?.setVisible(false));
+ act(() =>
+ setOpenThreads([makeThread({ threadId: 'seeded', title: 'Seeded', agent: FIRST_AGENT })]),
+ );
+
+ expect(onVisibleChange).not.toHaveBeenCalledWith(true);
+ expect(await screen.findByRole('tab', { name: /Seeded/ })).toBeDefined();
+ });
+
test('an archived-only backlog does NOT auto-reveal the dock', async () => {
const onVisibleChange = vi.fn((_v: boolean) => {});
render(<Harness initialVisible={false} onVisibleChange={onVisibleChange} />);
@@ -2091,19 +2245,19 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
},
);
- test('collapsing the dock hands focus back to the editor', async () => {
- const user = userEvent.setup();
- const onVisibleChange = vi.fn((_v: boolean) => {});
+ test('hiding the dock while focus is inside it hands focus back to the editor', async () => {
const onRequestEditorFocus = vi.fn(() => {});
+ const control = makeControl();
setOpenThreads([makeThread({ threadId: 't1', title: 'Pre-existing' })]);
- render(
- <Harness onVisibleChange={onVisibleChange} onRequestEditorFocus={onRequestEditorFocus} />,
- );
+ render(<Harness control={control} onRequestEditorFocus={onRequestEditorFocus} />);
await screen.findByTestId('thread-view');
+ act(() => {
+ screen.getByRole('tab', { name: /Pre-existing/ }).focus();
+ });
+ onRequestEditorFocus.mockClear();
- await user.click(screen.getByRole('button', { name: 'Collapse agent panel' }));
+ act(() => control.current?.setVisible(false));
- expect(onVisibleChange).toHaveBeenCalledWith(false);
expect(onRequestEditorFocus).toHaveBeenCalled();
});
@@ -2440,6 +2594,64 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
});
describe('Ask AI honors the preferred AI', () => {
+ test.each([
+ { label: 'agent', sticky: IN_APP_THREAD_ID, expectedAgent: 1, expectedTerminal: 0 },
+ {
+ label: 'CLI',
+ sticky: terminalCliId('claude'),
+ expectedAgent: 0,
+ expectedTerminal: 1,
+ },
+ ])(
+ 'two desktop hosts claim exactly one $label preferred route',
+ async ({ sticky, expectedAgent, expectedTerminal }) => {
+ setInitialRosterIds(new Set());
+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
+ saveStickyAgent(sticky);
+ const bridge = makeTerminalBridge();
+ render(<DualDesktopPreferredHosts bridge={bridge} />);
+ await act(async () => {});
+
+ let claimed: unknown;
+ act(() => {
+ claimed = requestPreferredSession();
+ });
+
+ expect(launchAgentThread).toHaveBeenCalledTimes(expectedAgent);
+ expect(screen.queryAllByTestId('preferred-terminal-session')).toHaveLength(
+ expectedTerminal,
+ );
+ expect(claimed).toBe(true);
+ },
+ );
+
+ test('no available session kind handles the request by revealing Chat settings', async () => {
+ setInitialRosterIds(new Set());
+ const visibleChanges: boolean[] = [];
+ render(
+ <Harness
+ initialVisible={false}
+ onVisibleChange={(visible) => visibleChanges.push(visible)}
+ />,
+ );
+ await act(async () => {});
+
+ const originalUrl = window.location.href;
+ try {
+ let claimed: unknown;
+ act(() => {
+ claimed = requestPreferredSession();
+ });
+
+ expect(visibleChanges).toContain(true);
+ expect(window.location.hash).toBe('#settings/agent-connections');
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ expect(claimed).toBe(true);
+ } finally {
+ window.history.replaceState(null, '', originalUrl);
+ }
+ });
+
test('an Ask AI instruction RUNS on a new thread (never a CLI)', async () => {
mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
const launches: unknown[] = [];
@@ -2548,6 +2760,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
null,
null,
undefined,
+ undefined,
]);
});
@@ -2651,6 +2864,76 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
expect(launchAgentThread).not.toHaveBeenCalled();
});
+ test('the agent host signals readiness but declines a terminal-kind preferred request', async () => {
+ const ready = vi.fn();
+ render(<Harness bridge={makeTerminalBridge()} onPreferredSessionHostReady={ready} />);
+ await screen.findByTestId('terminal-new-chat');
+
+ let claimed: unknown;
+ act(() => {
+ claimed = requestPreferredSession();
+ });
+
+ expect(claimed).toBe(false);
+ expect(ready).toHaveBeenCalledTimes(1);
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ });
+
+ test('an explicit preferred request opens one agent conversation from a settled empty roster', async () => {
+ setInitialRosterIds(new Set());
+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
+ const ready = vi.fn();
+ const visibleChanges: boolean[] = [];
+ render(
+ <Harness
+ initialVisible={false}
+ onPreferredSessionHostReady={ready}
+ onVisibleChange={(visible) => visibleChanges.push(visible)}
+ />,
+ );
+ await act(async () => {});
+ expect(launchAgentThread).not.toHaveBeenCalled();
+
+ let claimed: unknown;
+ act(() => {
+ claimed = requestPreferredSession();
+ });
+
+ expect(claimed).toBe(true);
+ expect(ready).toHaveBeenCalledTimes(1);
+ expect(visibleChanges).toContain(true);
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ });
+
+ test('an explicit preferred request opens a new conversation without replacing a restored tab', async () => {
+ setInitialRosterIds(new Set(['existing']));
+ act(() => setOpenThreads([makeThread({ threadId: 'existing', title: 'Existing' })]));
+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
+ const ready = vi.fn();
+ const visibleChanges: boolean[] = [];
+ render(
+ <Harness
+ initialVisible={false}
+ onPreferredSessionHostReady={ready}
+ onVisibleChange={(visible) => visibleChanges.push(visible)}
+ />,
+ );
+ await act(async () => {});
+ expect(screen.getByRole('tab', { name: /Existing/ })).toBeDefined();
+ expect(launchAgentThread).not.toHaveBeenCalled();
+
+ let claimed: unknown;
+ act(() => {
+ claimed = requestPreferredSession();
+ });
+
+ expect(claimed).toBe(true);
+ expect(ready).toHaveBeenCalledTimes(1);
+ expect(visibleChanges).toContain(true);
+ expect(screen.getByRole('tab', { name: /Existing/ })).toBeDefined();
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ });
+
test.each([
{ submit: true, label: 'an Ask AI instruction' },
{ submit: false, label: 'a selection send' },
@@ -2713,6 +2996,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
null,
null,
undefined,
+ undefined,
]);
expect(window.location.hash).toBe('');
expect(registerAgent).not.toHaveBeenCalled();
@@ -2818,6 +3102,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
'Notes',
null,
undefined,
+ undefined,
]);
});
});
@@ -2868,8 +3153,102 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
});
describe('seed on reveal', () => {
+ test('revealing after an empty roster settles starts one conversation', () => {
+ setInitialRosterIds(new Set());
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ const control = makeControl();
+ render(<Harness initialVisible={false} control={control} />);
+
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ act(() => control.current?.setVisible(true));
+
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ expect(launchAgentThread.mock.calls[0][0]).toEqual({ source: 'registry', id: 'claude-acp' });
+ act(() => control.current?.rerender());
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ });
+
+ test('a restored open tab prevents a default conversation while session tabs catch up', () => {
+ setInitialRosterIds(new Set(['existing']));
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ const control = makeControl();
+ render(<Harness initialVisible={false} control={control} />);
+
+ act(() => {
+ setOpenThreads([makeThread({ threadId: 'existing', title: 'Existing' })]);
+ control.current?.setVisible(true);
+ });
+
+ expect(screen.getByRole('tab', { name: /Existing/ })).toBeDefined();
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ });
+
+ test('a reveal waits for an unknown roster and starts once it arrives empty', () => {
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ const control = makeControl();
+ render(<Harness initialVisible={false} control={control} />);
+
+ act(() => control.current?.setVisible(true));
+ expect(launchAgentThread).not.toHaveBeenCalled();
+
+ act(() => setInitialRosterIds(new Set()));
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ act(() => control.current?.rerender());
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ });
+
+ test('hiding before the roster settles cancels an automatic conversation', () => {
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ const control = makeControl();
+ render(<Harness initialVisible={false} control={control} />);
+
+ act(() => control.current?.setVisible(true));
+ act(() => control.current?.setVisible(false));
+ act(() => setInitialRosterIds(new Set()));
+
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ });
+
+ test('a later reveal starts a conversation after the restored tab closes', () => {
+ setInitialRosterIds(new Set(['restored']));
+ setOpenThreads([makeThread({ threadId: 'restored', title: 'Restored' })]);
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ const control = makeControl();
+ render(<Harness initialVisible={false} control={control} />);
+
+ expect(screen.getByRole('tab', { name: /Restored/ })).toBeDefined();
+ act(() => control.current?.setVisible(true));
+ expect(launchAgentThread).not.toHaveBeenCalled();
+
+ act(() => setOpenThreads([]));
+ expect(launchAgentThread).not.toHaveBeenCalled();
+
+ act(() => control.current?.setVisible(false));
+ act(() => control.current?.setVisible(true));
+
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ expect(launchAgentThread.mock.calls[0][0]).toEqual({ source: 'registry', id: 'claude-acp' });
+ });
+
+ test('an independently opened tab cancels an automatic seed owed while agents load', () => {
+ setInitialRosterIds(new Set());
+ const control = makeControl();
+ render(<Harness initialVisible control={control} />);
+ expect(launchAgentThread).not.toHaveBeenCalled();
+
+ act(() => {
+ setOpenThreads([makeThread({ threadId: 'independent', title: 'Independent' })]);
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ control.current?.rerender();
+ });
+
+ expect(screen.getByRole('tab', { name: /Independent/ })).toBeDefined();
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ });
+
test('revealing an empty panel starts one conversation when an agent resolves', () => {
window.location.hash = '';
+ setInitialRosterIds(new Set());
mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
const control = makeControl();
render(<Harness initialVisible={false} control={control} />);
@@ -2885,12 +3264,30 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
null,
null,
undefined,
+ expect.any(Function),
]);
expect(registerAgent).not.toHaveBeenCalled();
});
+ test('a roster refresh after an empty Chat reveal does not start a second conversation', () => {
+ window.location.hash = '';
+ setInitialRosterIds(new Set());
+ mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
+ const control = makeControl();
+ render(<Harness initialVisible={false} control={control} />);
+
+ act(() => control.current?.setVisible(true));
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+
+ mockInflightLaunch = false;
+ act(() => setInitialRosterIds(new Set()));
+
+ expect(launchAgentThread).toHaveBeenCalledTimes(1);
+ });
+
test('a reveal before the registry lands still gets its conversation once it does', () => {
window.location.hash = '';
+ setInitialRosterIds(new Set());
mockRegisteredAgent = null;
const control = makeControl();
render(<Harness initialVisible={false} control={control} />);
@@ -2908,6 +3305,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
test('re-subscribing the agents order restore keeps a reveal seed another effect owes', async () => {
window.location.hash = '';
+ setInitialRosterIds(new Set());
mockRegisteredAgent = null;
const control = makeControl();
const makeDockBridge = () =>
@@ -3148,6 +3546,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
test('a launch that fails to land re-enables reveal-seed once it is no longer in flight', () => {
window.location.hash = '';
+ setInitialRosterIds(new Set());
mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
const control = makeControl();
render(<Harness initialVisible={false} control={control} />);
@@ -3176,6 +3575,7 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
test('a conversation created on one reveal is not duplicated on the next reveal', async () => {
window.location.hash = '';
+ setInitialRosterIds(new Set());
mockRegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude Agent' };
const control = makeControl();
render(<Harness initialVisible={false} control={control} />);
@@ -3275,6 +3675,7 @@ describe('switching the agent of an unsent chat', () => {
null,
{ doc: DRAFT_DOC, attachments: [DRAFT_IMAGE] },
undefined,
+ undefined,
]);
await waitFor(() => expect(closeThread).toHaveBeenCalledWith('t1'));
});
@@ -3335,6 +3736,7 @@ describe('switching the agent of an unsent chat', () => {
null,
null,
undefined,
+ undefined,
]);
});
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 97c51b389..69d237fbb 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
@@ -3,6 +3,7 @@ import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol
import { act, cleanup, render, screen, within } from '@testing-library/react';
import { type ReactNode, useEffect, useRef, useState } from 'react';
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 type { SessionPlacements } from './EditorArea';
@@ -372,29 +373,31 @@ function CompositionHarness({ bridge }: { bridge: OkDesktopBridge }) {
}, [placements]);
return (
<TooltipProvider>
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={bridge}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={() => {}}
- onSessionPlacements={setPlacements}
- />
- <SessionsHost
- surface="terminal-dock"
- terminalPlacement="right"
- bridge={bridge}
- terminalCapable
- visible
- onVisibleChange={() => {}}
- installedClis={{}}
- container={placements.terminal.container}
- isShowing={placements.terminal.isShowing}
- onRequestEditorFocus={() => {}}
- />
+ <SidebarProvider>
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ terminalBridge={bridge}
+ terminalVisible
+ terminalPlacement="right"
+ onTerminalVisibleChange={() => {}}
+ onSessionPlacements={setPlacements}
+ />
+ <SessionsHost
+ surface="terminal-dock"
+ terminalPlacement="right"
+ bridge={bridge}
+ terminalCapable
+ visible
+ onVisibleChange={() => {}}
+ installedClis={{}}
+ container={placements.terminal.container}
+ isShowing={placements.terminal.isShowing}
+ onRequestEditorFocus={() => {}}
+ />
+ </SidebarProvider>
</TooltipProvider>
);
}
@@ -438,28 +441,33 @@ describe('terminal dock restore vs portal-host attachment', () => {
expect(gatesMountedIntoADetachedHost()).toEqual([]);
});
- test('mounts no terminal gate during the cold-start window that nulls the real container', async () => {
+ test('restores the terminal into its live mount while the cold-load skeleton shows, never into a detached host', async () => {
window.location.hash = '#/some-doc';
const bridge = makeRestartBridge();
const view = render(<CompositionHarness bridge={bridge} />);
await settle(500);
expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
- expect(document.querySelector('[data-terminal-panel-mount]')).toBeNull();
- expect(publishedTerminalContainers).toContain(null);
+ const coldLoadMount = document.querySelector('[data-terminal-panel-mount]');
+ expect(coldLoadMount).not.toBeNull();
+ expect(publishedTerminalContainers.at(-1)).toBe(coldLoadMount);
expect(gatesMountedIntoADetachedHost()).toEqual([]);
+ const coldLoadGates = screen.getAllByTestId('terminal-gate');
+ expect(coldLoadGates).toHaveLength(2);
+ expect(coldLoadGates.filter((gate) => !coldLoadMount?.contains(gate))).toEqual([]);
await act(async () => {
docCtx = LIVE_DOC_CTX;
});
view.rerender(<CompositionHarness bridge={bridge} />);
await settle(500);
- expect(document.querySelector('[data-terminal-panel-mount]')).not.toBeNull();
- expect(publishedTerminalContainers).toContain(
- document.querySelector('[data-terminal-panel-mount]'),
- );
- expect(screen.getAllByTestId('terminal-gate')).toHaveLength(2);
+ expect(screen.queryByTestId('editor-skeleton')).toBeNull();
+ const liveMount = document.querySelector('[data-terminal-panel-mount]');
+ expect(publishedTerminalContainers.at(-1)).toBe(liveMount);
expect(gatesMountedIntoADetachedHost()).toEqual([]);
+ const liveGates = screen.getAllByTestId('terminal-gate');
+ expect(liveGates).toHaveLength(2);
+ expect(liveGates.filter((gate) => !liveMount?.contains(gate))).toEqual([]);
});
test('keeps every restored terminal gate mounted when the dock container is withdrawn and replaced', async () => {
@@ -471,6 +479,9 @@ describe('terminal dock restore vs portal-host attachment', () => {
expect(gatesMountedIntoADetachedHost()).toEqual([]);
const mountsAfterRestore = [...gateLifecycle.mounts];
expect(mountsAfterRestore).toHaveLength(2);
+ const firstAttachment = screen.getByTestId('terminal-mount').firstElementChild;
+ const gatesAfterRestore = screen.getAllByTestId('terminal-gate');
+ expect(firstAttachment).not.toBeNull();
view.rerender(<ChurnHarness slot="none" />);
await settle(500);
@@ -486,6 +497,9 @@ describe('terminal dock restore vs portal-host attachment', () => {
const gatesAfterSwap = screen.getAllByTestId('terminal-gate');
expect(gatesAfterSwap).toHaveLength(2);
expect(gatesAfterSwap.filter((gate) => !replacementContainer.contains(gate))).toEqual([]);
+ expect(replacementContainer.firstElementChild).toBe(firstAttachment);
+ expect(gatesAfterSwap[0]).toBe(gatesAfterRestore[0]);
+ expect(gatesAfterSwap[1]).toBe(gatesAfterRestore[1]);
expect(tabTitles()).toEqual(['process second', 'process first']);
expect(gatesMountedIntoADetachedHost()).toEqual([]);
});
diff --git a/packages/app/src/components/SessionsHost.tsx b/packages/app/src/components/SessionsHost.tsx
index 5902fae06..d09055ac6 100644
--- a/packages/app/src/components/SessionsHost.tsx
+++ b/packages/app/src/components/SessionsHost.tsx
@@ -44,6 +44,7 @@ import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
import { hasInflightThreadLaunch, launchAgentThread } from '@/lib/acp/launch-agent-thread';
import {
enabledTerminalClis,
+ LAUNCHER_KIND_PANE,
type LauncherSelection,
resolveLauncherSelection,
} from '@/lib/acp/launcher-selection';
@@ -71,6 +72,7 @@ import {
type ThreadDraftContent,
} from '@/lib/acp/thread-draft-staging';
import { threadHasUserMessage } from '@/lib/acp/thread-event-model';
+import { usePreferredSessionSelection } from '@/lib/acp/use-preferred-session-selection';
import type { OkDesktopBridge, OkTerminalRestartSnapshot } from '@/lib/desktop-bridge-types';
import { emitDiagnosticBreadcrumb } from '@/lib/diagnostic-breadcrumb';
import {
@@ -85,6 +87,7 @@ import { matchesPrimaryModifier, type ShortcutPlatform } from '@/lib/keyboard-sh
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import type { NewSessionChoice } from '@/lib/new-session-choice';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
+import { paneVisibilityStore } from '@/lib/pane-visibility-store';
import { RESTORE_SETTLE_TIMEOUT_MS } from '@/lib/restore-settle-timeout';
import { usePreferBareTerminal, writePreferBareTerminal } from '@/lib/terminal-new-tab-store';
import {
@@ -219,6 +222,16 @@ function focusInsideHost(hostEl: HTMLElement | null): boolean {
return hostEl?.contains(document.activeElement) ?? false;
}
+function focusRemainsUsable(element: Element | null): boolean {
+ return (
+ element instanceof HTMLElement &&
+ element !== document.body &&
+ element.isConnected &&
+ element.closest('[inert]') == null &&
+ element.getClientRects().length > 0
+ );
+}
+
function focusAvailableButton(candidate: HTMLButtonElement | null): HTMLButtonElement | null {
if (
candidate == null ||
@@ -409,16 +422,18 @@ interface SessionsHostSharedProps {
readonly terminalCapable?: boolean;
readonly terminalPlacement?: TerminalPlacement;
readonly onTerminalPlacementChange?: (placement: TerminalPlacement) => void;
- readonly reserveRightRevealTabGutter?: boolean;
readonly terminalRestoreRevealNonce?: number;
readonly visible: boolean;
- readonly onVisibleChange: (visible: boolean) => void;
+ readonly wideVisible?: boolean;
+ readonly onVisibleChange: (visible: boolean, reason?: 'session-close') => void;
+ readonly onPreferredSessionHostReady?: () => void;
readonly launch?: TerminalLaunchIntent | null;
readonly commandLaunch?: { readonly id: TerminalCommandId; readonly nonce: number } | null;
readonly threadLaunch?: ThreadLaunchIntent | null;
readonly installedClis?: Partial<Record<TerminalCli, boolean>>;
readonly container: HTMLElement | null;
readonly isShowing: boolean;
+ readonly revealFocusHold?: boolean;
readonly onRequestEditorFocus: () => void;
}
@@ -436,12 +451,6 @@ type SessionsHostProps = SessionsHostSharedProps &
const REVEAL_FOCUS_LANDING_TIMEOUT_MS = 5_000;
-const TERMINAL_DOCK_KINDS: Record<Exclude<LauncherSelection['kind'], 'thread' | 'none'>, true> = {
- cli: true,
- terminal: true,
- desktop: true,
-};
-
function closeHistory(
setOpen: (open: boolean) => void,
focus: 'always' | 'if-panel-focused' | 'never',
@@ -464,10 +473,11 @@ export function SessionsHost({
surface,
terminalPlacement = 'bottom',
onTerminalPlacementChange,
- reserveRightRevealTabGutter,
terminalRestoreRevealNonce = 0,
visible,
+ wideVisible = visible,
onVisibleChange,
+ onPreferredSessionHostReady,
agentsVisibilityRestoreSettled,
launch = null,
commandLaunch = null,
@@ -475,6 +485,7 @@ export function SessionsHost({
installedClis,
container,
isShowing,
+ revealFocusHold = false,
onRequestEditorFocus,
}: SessionsHostProps) {
const { t } = useLingui();
@@ -485,7 +496,7 @@ export function SessionsHost({
const terminalAvailable = hostTerminals && terminalCapable && bridge?.terminal != null;
const edge: SessionPanelEdge = hostThreads ? 'right' : terminalPlacement;
const persistSurface: DockSurface = hostThreads ? 'agents' : 'terminal';
- const persistedPanelLevel = hostThreads && visible;
+ const persistedPanelLevel = hostThreads && wideVisible;
const persistsOrder = !isWindow;
const shortcutPlatform: ShortcutPlatform | undefined =
bridge?.platform === 'darwin'
@@ -504,6 +515,11 @@ export function SessionsHost({
const [attachedHostEl, setAttachedHostEl] = useState<HTMLDivElement | null>(null);
const hostStateReportsRef = useRef(0);
+ useLayoutEffect(() => {
+ if (hostEl == null) return;
+ return () => hostEl.remove();
+ }, [hostEl]);
+
useLayoutEffect(() => {
if (hostEl == null || container == null) return;
if (hostEl.parentElement !== container) container.appendChild(hostEl);
@@ -572,6 +588,11 @@ export function SessionsHost({
const lastHandledThreadNonceRef = useRef<number | null>(null);
const settingsShownForNonceRef = useRef<number | null>(null);
const seedOwedRef = useRef(false);
+ const seededThreadLaunchRef = useRef<{
+ agentKey: string;
+ connectionGeneration: number;
+ } | null>(null);
+ const seededThreadIdRef = useRef<string | null>(null);
const initialVisibleSeedAttemptedRef = useRef(false);
const [emptyAgentLaunchState, setEmptyAgentLaunchState] = useState<EmptyAgentLaunchState>('idle');
const pendingAgentLaunchRequestRef = useRef<AgentPaneLaunchRequest | null>(null);
@@ -592,6 +613,11 @@ export function SessionsHost({
const ptyIdBySessionRef = useRef(new Map<string, string>());
const stripLaunchNonceRef = useRef(0);
+ const revealFocusHoldRef = useRef(revealFocusHold);
+ useLayoutEffect(() => {
+ revealFocusHoldRef.current = revealFocusHold;
+ }, [revealFocusHold]);
+
useLayoutEffect(() => {
const revealing = isShowing && !revealFocusWasShowingRef.current;
revealFocusWasShowingRef.current = isShowing;
@@ -710,7 +736,7 @@ export function SessionsHost({
const snapshot = buildTerminalRestartSnapshot(sessionsRef.current, activeSessionIdRef.current);
if (hostThreads) {
writeDockSessionOrder(bridge, 'agents', { order, activeKey }, snapshot);
- writeAgentsPanelLevel(bridge, visible);
+ writeAgentsPanelLevel(bridge, wideVisible);
} else {
writeDockSessionOrder(bridge, 'terminal', { order, activeKey }, snapshot);
}
@@ -791,7 +817,10 @@ export function SessionsHost({
openSession({ prompt: null, cli, nonce: stripLaunchNonceRef.current }, null, provenance);
}
- function launchAgentForPane(request: AgentPaneLaunchRequest) {
+ function launchAgentForPane(
+ request: AgentPaneLaunchRequest,
+ onCreated?: (info: ThreadInfo) => void,
+ ) {
const {
agent,
prompt = null,
@@ -813,6 +842,7 @@ export function SessionsHost({
titleHint,
stageDraft,
attachments,
+ onCreated,
).then((outcome) => {
if (outcome === 'deduped') {
toast.error(t`Already starting a chat with this agent — try again in a moment.`);
@@ -870,7 +900,21 @@ export function SessionsHost({
function seedOnReveal(): boolean {
if (hostThreads) {
if (newSessionChoice.kind !== 'agent' || newSessionChoice.agent == null) return false;
- void launchAgentForPane({ agent: newSessionChoice.agent });
+ const agent = newSessionChoice.agent;
+ const seededLaunch = {
+ agentKey: `${agent.source}:${agent.id}`,
+ connectionGeneration: getAgentThreadClient().getConnectionGeneration(),
+ };
+ seededThreadIdRef.current = null;
+ seededThreadLaunchRef.current = seededLaunch;
+ void launchAgentForPane({ agent }, (info) => {
+ if (seededThreadLaunchRef.current !== seededLaunch) return;
+ seededThreadIdRef.current = info.threadId;
+ seededThreadLaunchRef.current = null;
+ }).then((outcome) => {
+ if (outcome !== 'started' && seededThreadLaunchRef.current === seededLaunch)
+ seededThreadLaunchRef.current = null;
+ });
return true;
}
if (newSessionChoice.kind === 'terminal') openSession(null, null, 'restore-seed');
@@ -905,23 +949,15 @@ export function SessionsHost({
bareTerminalFallback: false,
});
- const preferredSessionSelection = resolveLauncherSelection({
- sticky: stickyAgentId,
- effectiveThreadAgent: effectiveDefaultAgent,
- enabledClis: enabledTerminalClis(enabledOverrides, installedClis ?? {}),
- enabledDesktopTargets: [],
+ const preferredSessionSelection = usePreferredSessionSelection({
installedClis: installedClis ?? {},
terminalAvailable: terminalCapable,
threadsAvailable: !isWindow,
- desktopSelectable: false,
- preferBareTerminal,
- bareTerminalFallback: true,
});
function claimsSessionKind(kind: LauncherSelection['kind']): boolean {
if (isWindow) return true;
- const agentsPanelKind = kind === 'thread' || kind === 'none';
- return hostThreads ? agentsPanelKind : kind in TERMINAL_DOCK_KINDS;
+ return LAUNCHER_KIND_PANE[kind] === (hostThreads ? 'agents' : 'terminal');
}
function publishReusableSessionFrom(sessionList: readonly SessionDescriptor[], activeId: string) {
@@ -960,9 +996,14 @@ export function SessionsHost({
publishReusableSessionFrom(sessions, activeSessionId);
}, [activeSessionId, sessions, openThreadTabs]);
+ function requestHostPaneReveal() {
+ if (!visible) onVisibleChange(true);
+ else if (hostThreads) paneVisibilityStore.request('agents', true);
+ }
+
function revealForReuse() {
dismissCoveringHistory();
- if (!visible) onVisibleChange(true);
+ requestHostPaneReveal();
}
function dispatchAskAi({ text, newTab, submit, target }: ActiveTerminalInputDetail) {
@@ -970,14 +1011,13 @@ export function SessionsHost({
if (target === 'agents') {
if (!hostThreads) return;
} else if (!claimsSessionKind(selection.kind)) return;
- if (!visible) onVisibleChange(true);
+ requestHostPaneReveal();
dismissCoveringHistory();
const activeId = activeSessionIdRef.current;
const active = sessionsRef.current.find((s) => s.id === activeId);
if (!newTab && active != null) {
if (active.kind === 'thread') {
stageThreadDraft(active.threadId, text);
- revealForReuse();
queueMicrotask(() => focusSession(active));
return;
}
@@ -1142,7 +1182,7 @@ export function SessionsHost({
}
function launchPreferredSession() {
if (!claimsSessionKind(preferredSessionSelection.kind)) return;
- if (!visible) onVisibleChange(true);
+ requestHostPaneReveal();
launchSelectedNewTab();
}
@@ -1154,6 +1194,7 @@ export function SessionsHost({
const dispatchAskAiRef = useRef(dispatchAskAi);
const revealForReuseRef = useRef(revealForReuse);
const launchPreferredSessionRef = useRef(launchPreferredSession);
+ const preferredSessionKindRef = useRef(preferredSessionSelection.kind);
function closeSession(id: string) {
const current = sessionsRef.current;
@@ -1176,7 +1217,7 @@ export function SessionsHost({
setSessions(current.filter((s) => s.id !== id));
}
if (isLast) {
- onVisibleChange(false);
+ onVisibleChange(false, 'session-close');
onRequestEditorFocus();
}
}
@@ -1199,6 +1240,7 @@ export function SessionsHost({
dispatchAskAiRef.current = dispatchAskAi;
revealForReuseRef.current = revealForReuse;
launchPreferredSessionRef.current = launchPreferredSession;
+ preferredSessionKindRef.current = preferredSessionSelection.kind;
noteUserArrangementRef.current = noteUserArrangement;
moveActiveSessionRef.current = moveActiveSession;
activeSessionIdRef.current = activeSessionId;
@@ -1333,11 +1375,36 @@ export function SessionsHost({
const previous = prevLiveThreadIdsRef.current;
prevLiveThreadIdsRef.current = liveThreadIds;
const added = liveThreadIds.filter((id) => !previous.includes(id));
- if (added.length === 0 || visible) return;
- const absorbsReloadSnapshot = added.every((id) => initialRosterThreadIds?.has(id) === true);
+ if (added.length === 0) return;
+ const seededLaunch = seededThreadLaunchRef.current;
+ const seededThreadId = added.find((id) => {
+ if (id === seededThreadIdRef.current) return true;
+ if (
+ seededLaunch === null ||
+ seededLaunch.connectionGeneration !== getAgentThreadClient().getConnectionGeneration()
+ )
+ return false;
+ const info = openThreadTabs.find((thread) => thread.threadId === id);
+ return (
+ initialRosterThreadIds?.has(id) !== true &&
+ info !== undefined &&
+ `${info.agent.source}:${info.agent.id}` === seededLaunch.agentKey
+ );
+ });
+ if (seededThreadId !== undefined) {
+ seededThreadIdRef.current = seededThreadId;
+ seededThreadLaunchRef.current = null;
+ }
+ if (visible) return;
+ const newArrival = added.filter((id) => id !== seededThreadId);
+ if (newArrival.length === 0) return;
+ const absorbsReloadSnapshot = newArrival.every(
+ (id) => initialRosterThreadIds?.has(id) === true,
+ );
if (!absorbsReloadSnapshot) onVisibleChange(true);
}, [
liveThreadIds,
+ openThreadTabs,
hostThreads,
agentsVisibilityRestoreSettled,
visible,
@@ -1395,6 +1462,14 @@ export function SessionsHost({
!(hostThreads && hasInflightThreadLaunch())
) {
if (restoredVisibility && !restoreAbandonedRef.current) return;
+ if (hostThreads) {
+ if (initialRosterThreadIds === null) return;
+ initialVisibleSeedAttemptedRef.current = true;
+ if (openThreadTabs.length > 0) {
+ seedOwedRef.current = false;
+ return;
+ }
+ }
seedOwedRef.current = !seedOnRevealRef.current();
return;
}
@@ -1417,7 +1492,12 @@ export function SessionsHost({
return;
}
if (!seedOwedRef.current) return;
- if (!visible || sessions.length > 0 || threadLaunchPending) {
+ if (
+ !visible ||
+ sessions.length > 0 ||
+ threadLaunchPending ||
+ (hostThreads && openThreadTabs.length > 0)
+ ) {
seedOwedRef.current = false;
return;
}
@@ -1675,8 +1755,20 @@ export function SessionsHost({
}, [hostThreads]);
useEffect(() => {
- return subscribeToPreferredSessionRequests(() => launchPreferredSessionRef.current());
- }, []);
+ const unsubscribe = subscribeToPreferredSessionRequests(
+ () => launchPreferredSessionRef.current(),
+ window,
+ () => {
+ if (isWindow) return true;
+ return (
+ LAUNCHER_KIND_PANE[preferredSessionKindRef.current] ===
+ (hostThreads ? 'agents' : 'terminal')
+ );
+ },
+ );
+ onPreferredSessionHostReady?.();
+ return unsubscribe;
+ }, [hostThreads, isWindow, onPreferredSessionHostReady]);
useEffect(() => {
if (!hostTerminals) return;
@@ -1770,6 +1862,10 @@ export function SessionsHost({
useEffect(() => {
if (!isShowing || attachedHostEl == null) return;
const focusOrigin = document.activeElement;
+ if (revealFocusHoldRef.current && focusRemainsUsable(focusOrigin)) {
+ revealFocusRef.current = null;
+ return;
+ }
const initialTargetId = revealFocusRef.current?.pendingThreadId ?? activeSessionIdRef.current;
const initialActive = sessionsRef.current.find((s) => s.id === initialTargetId);
let initialFallbackLanding = false;
@@ -2091,15 +2187,6 @@ export function SessionsHost({
}}
edge={edge}
onPlacementChange={surface === 'terminal-dock' ? onTerminalPlacementChange : undefined}
- reserveRightRevealTabGutter={reserveRightRevealTabGutter}
- onCollapse={
- isWindow
- ? undefined
- : () => {
- onVisibleChange(false);
- onRequestEditorFocus();
- }
- }
draggable={isWindow}
className="h-full"
>
@@ -2128,9 +2215,9 @@ export function SessionsHost({
{historyOpen ? (
<div
className={cn(
- 'z-20 h-full max-w-full bg-background',
+ 'z-20 h-full max-w-full bg-sidebar',
historyMode === 'cover'
- ? 'absolute inset-0 w-full shadow-xl'
+ ? 'absolute inset-0 w-full shadow-xl [-webkit-app-region:no-drag]'
: 'w-(--history-panel-width) shrink-0 border-s',
)}
style={
diff --git a/packages/app/src/components/ShareButton.dom.test.tsx b/packages/app/src/components/ShareButton.dom.test.tsx
index 86b76b650..6b4e71149 100644
--- a/packages/app/src/components/ShareButton.dom.test.tsx
+++ b/packages/app/src/components/ShareButton.dom.test.tsx
@@ -110,6 +110,9 @@ describe('ShareButton', () => {
const input = screen.getByLabelText('Share URL') as HTMLInputElement;
expect(input.value).toBe('https://openknowledge.ai/d/Share123');
expect(screen.getByRole('button', { name: 'Copied!' })).not.toBeNull();
+ expect(screen.getByRole('dialog', { name: 'Share' })).toBe(
+ screen.getByTestId('share-button-popover'),
+ );
});
test('swallows only the clipboard toast when the popover already carries the link', async () => {
diff --git a/packages/app/src/components/ShareButton.tsx b/packages/app/src/components/ShareButton.tsx
index b8cb4e96a..64df9cf79 100644
--- a/packages/app/src/components/ShareButton.tsx
+++ b/packages/app/src/components/ShareButton.tsx
@@ -3,7 +3,7 @@
import type { ShareFreshness } from '@inkeep/open-knowledge-core/schemas/api';
import { Trans, useLingui } from '@lingui/react/macro';
import { CircleHelp, Share2 } from 'lucide-react';
-import { type Ref, useEffect, useRef, useState } from 'react';
+import { type Ref, useEffect, useId, useRef, useState } from 'react';
import { toast } from 'sonner';
import { CopyButton } from '@/components/CopyButton';
import { Button } from '@/components/ui/button';
@@ -29,6 +29,7 @@ export interface ShareButtonProps {
export function ShareButton({ input, onClickWhenNoRemote, triggerRef }: ShareButtonProps) {
const { t } = useLingui();
+ const headingId = useId();
const { status } = useGitSyncStatusDetailed();
const [busy, setBusy] = useState(false);
const [sharePopover, setSharePopover] = useState<{
@@ -110,17 +111,21 @@ export function ShareButton({ input, onClickWhenNoRemote, triggerRef }: ShareBut
className="gap-1.5 text-muted-foreground px-1.5"
data-testid="share-button"
>
- <Share2 className="size-3.5" aria-hidden />
+ <Share2 className="size-4" aria-hidden />
<Trans>Share</Trans>
</Button>
</PopoverAnchor>
<PopoverContent
align="end"
+ aria-labelledby={headingId}
className={cn('flex flex-col gap-2', showFreshnessRow ? 'w-96' : 'w-80')}
data-testid="share-button-popover"
>
{}
- <p className="font-mono tracking-wide uppercase text-muted-foreground text-xs">
+ <p
+ id={headingId}
+ className="font-mono tracking-wide uppercase text-muted-foreground text-xs"
+ >
<Trans>Share</Trans>
</p>
{sharePopover?.autoCopyFailed ? (
diff --git a/packages/app/src/components/SkillBundlePreview.tsx b/packages/app/src/components/SkillBundlePreview.tsx
index 15d6c5660..6dbf56eae 100644
--- a/packages/app/src/components/SkillBundlePreview.tsx
+++ b/packages/app/src/components/SkillBundlePreview.tsx
@@ -38,7 +38,6 @@ interface Props {
headerActions: ReactNode;
headerLine: ReactNode;
noPreviewFallback?: ReactNode;
- reserveRightGutter?: boolean;
selectedPath?: string;
scope?: SkillScope;
onPreviewMeta?: (preview: SkillPreviewData) => void;
@@ -55,7 +54,6 @@ export function SkillBundlePreview({
headerLine,
noPreviewFallback,
banner,
- reserveRightGutter = false,
selectedPath: selectedPathProp,
scope,
onBundlePathClick,
@@ -120,11 +118,7 @@ export function SkillBundlePreview({
<ProseFindBar containerRef={scrollRef} onClose={() => setFindOpen(false)} />
) : null}
{}
- <SkillModeBanner
- icon={<Eye className="size-4" aria-hidden />}
- actions={headerActions}
- reserveRightGutter={reserveRightGutter}
- >
+ <SkillModeBanner icon={<Eye className="size-4" aria-hidden />} actions={headerActions}>
{headerLine}
</SkillModeBanner>
diff --git a/packages/app/src/components/SkillMarkdownViewer.tsx b/packages/app/src/components/SkillMarkdownViewer.tsx
index 9200ecae2..7f3af2f1c 100644
--- a/packages/app/src/components/SkillMarkdownViewer.tsx
+++ b/packages/app/src/components/SkillMarkdownViewer.tsx
@@ -83,7 +83,7 @@ export function SkillMarkdownViewer({
{grid}
</article>
) : (
- <main
+ <section
className="flex h-full min-h-0 flex-col bg-background"
aria-label={fileName}
data-skill-markdown-viewer=""
@@ -94,7 +94,7 @@ export function SkillMarkdownViewer({
<ReadonlyPropertyPanel text={text} />
{grid}
</div>
- </main>
+ </section>
)}
{createPortal(
// oxlint-disable-next-line ok/no-unportaled-editor-content -- portaled site — view.dom parent is the exclusively-owned portalTarget per the H6 contract (PRECEDENTS.md #44)
diff --git a/packages/app/src/components/SkillModeBanner.tsx b/packages/app/src/components/SkillModeBanner.tsx
index 027d00c97..4bf61bef7 100644
--- a/packages/app/src/components/SkillModeBanner.tsx
+++ b/packages/app/src/components/SkillModeBanner.tsx
@@ -1,26 +1,16 @@
-// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility
-
import type { ReactNode } from 'react';
-import { cn } from '@/lib/utils';
export function SkillModeBanner({
icon,
children,
actions,
- reserveRightGutter,
}: {
icon: ReactNode;
children: ReactNode;
actions?: ReactNode;
- reserveRightGutter?: boolean;
}) {
return (
- <div
- className={cn(
- 'flex shrink-0 items-center justify-between gap-3 border-b border-border bg-muted/35 px-3 py-2',
- reserveRightGutter && 'pr-10',
- )}
- >
+ <div className="flex shrink-0 items-center justify-between gap-3 border-b border-border bg-muted/35 px-3 py-2">
<div className="flex min-w-0 items-start gap-1.5 text-muted-foreground text-sm">
<span className="mt-0.5 shrink-0">{icon}</span>
{}
diff --git a/packages/app/src/components/SkillPreviewTab.tsx b/packages/app/src/components/SkillPreviewTab.tsx
index 5ac8f02d1..3dcd69ed2 100644
--- a/packages/app/src/components/SkillPreviewTab.tsx
+++ b/packages/app/src/components/SkillPreviewTab.tsx
@@ -42,7 +42,6 @@ interface Props {
name: string;
subtitle: string;
level?: SkillScope;
- reserveRightGutter?: boolean;
path?: string;
}
@@ -75,15 +74,7 @@ export function BuiltinHeaderActions({ scope, name }: { scope: SkillScope; name:
);
}
-export function SkillPreviewTab({
- flavor,
- source,
- name,
- subtitle,
- level,
- reserveRightGutter,
- path,
-}: Props) {
+export function SkillPreviewTab({ flavor, source, name, subtitle, level, path }: Props) {
const selectedPath = path ?? SKILL_MD;
const scopeLabels = useSkillScopeLabels();
const openSkill = useOpenSkill();
@@ -384,7 +375,6 @@ export function SkillPreviewTab({
onBundlePathClick={onBundlePathClick}
headerActions={headerActions}
headerLine={headerLine}
- reserveRightGutter={reserveRightGutter}
selectedPath={selectedPath}
onPreviewMeta={(preview) => {
const next = detected ? (preview.plugin ?? null) : null;
diff --git a/packages/app/src/components/SkillsSidebarDock.tsx b/packages/app/src/components/SkillsSidebarDock.tsx
index a48a55732..45c30888b 100644
--- a/packages/app/src/components/SkillsSidebarDock.tsx
+++ b/packages/app/src/components/SkillsSidebarDock.tsx
@@ -106,7 +106,7 @@ export function SkillsSidebarDock({ filesOpen = true }: { filesOpen?: boolean }
}}
className={cn(
'group/skills-dock flex min-h-0 flex-col',
- expanded && !filesOpen ? 'flex-1' : 'shrink-0',
+ !expanded ? 'shrink-0' : filesOpen ? 'shrink' : 'flex-1',
)}
data-testid="skills-dock"
>
diff --git a/packages/app/src/components/SubscribeCard.dom.test.tsx b/packages/app/src/components/SubscribeCard.dom.test.tsx
index e10bd292c..40e755375 100644
--- a/packages/app/src/components/SubscribeCard.dom.test.tsx
+++ b/packages/app/src/components/SubscribeCard.dom.test.tsx
@@ -121,6 +121,7 @@ describe('SubscribeCard (combined release-notes + subscribe)', () => {
await userEvent.click(screen.getByTestId('subscribe-submit'));
await waitFor(() => expect(submitSubscribe).toHaveBeenCalled());
+ expect(submitSubscribe).toHaveBeenCalledWith('[email protected]', 'post_update_card');
expect(store.getSnapshot().subscribed).toBe(true);
expect(screen.queryByText('Follow us on')).toBeNull();
expect(screen.getByText(/Updated to Version/)).toBeTruthy();
diff --git a/packages/app/src/components/SubscribeCard.tsx b/packages/app/src/components/SubscribeCard.tsx
index 5ed3ffbbf..cd1b9118b 100644
--- a/packages/app/src/components/SubscribeCard.tsx
+++ b/packages/app/src/components/SubscribeCard.tsx
@@ -56,7 +56,7 @@ export function SubscribeCard({
}, [succeeded, onClose, autoDismissMs]);
return (
- <Card asChild size="sm" className="mx-1 mb-1">
+ <Card asChild size="sm" className="floating-card-surface rounded-lg ring-0 ring-transparent">
<section aria-label={t`Stay in the loop`}>
<CardContent>
<SubscribeForm
diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
index 394be5503..3891d8851 100644
--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx
+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
@@ -5,6 +5,11 @@ import { type ReactNode, useEffect, useReducer } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
vi.doMock('@lingui/core/macro', () => ({
@@ -1443,6 +1448,61 @@ describe('SyncStatusBadge working-tree listing', () => {
worktreeLastReadAt = null;
triggered.length = 0;
triggerRejection = null;
+ __resetPaneVisibilityStoreForTests();
+ });
+
+ function hideEditorBesideOneChangedDoc(): Array<
+ PaneVisibilityRequest & { hashWhenAsked: string }
+ > {
+ const reveals: Array<PaneVisibilityRequest & { hashWhenAsked: string }> = [];
+ paneVisibilityStore.subscribeRequests((request) => {
+ reveals.push({ ...request, hashWhenAsked: window.location.hash });
+ });
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = {
+ ...emptyWorktree,
+ notStaged: [
+ {
+ path: 'notes/cadence.md',
+ code: 'M',
+ syncScoped: true,
+ open: { kind: 'doc', docName: 'notes/cadence' },
+ },
+ ],
+ };
+ return reveals;
+ }
+
+ test('opening a row shows a hidden editor before navigating to it', async () => {
+ const reveals = hideEditorBesideOneChangedDoc();
+ window.location.hash = '#/elsewhere';
+ await renderBadge();
+ await openPopover();
+ await expandWorktreeListing();
+
+ await userEvent.click(screen.getByRole('button', { name: 'notes/cadence.md' }));
+
+ expect(reveals).toEqual([{ pane: 'editor', open: true, hashWhenAsked: '#/elsewhere' }]);
+ expect(window.location.hash).toBe('#/notes/cadence');
+ });
+
+ test('opening a row for the document already open still shows a hidden editor', async () => {
+ const reveals = hideEditorBesideOneChangedDoc();
+ window.location.hash = '#/notes/cadence';
+ await renderBadge();
+ await openPopover();
+ await expandWorktreeListing();
+
+ await userEvent.click(screen.getByRole('button', { name: 'notes/cadence.md' }));
+
+ expect(reveals).toEqual([{ pane: 'editor', open: true, hashWhenAsked: '#/notes/cadence' }]);
+ expect(window.location.hash).toBe('#/notes/cadence');
});
test("groups by what Push will do, not by git's index state", async () => {
diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsx
index ac93f98d4..6da136c3e 100644
--- a/packages/app/src/components/SyncStatusBadge.tsx
+++ b/packages/app/src/components/SyncStatusBadge.tsx
@@ -38,6 +38,7 @@ import { useGitWorktreeStatus } from '@/hooks/use-git-worktree-status';
import { useConfigContext } from '@/lib/config-provider';
import { hashFromAssetPath, hashFromDocName, isSameHash } from '@/lib/doc-hash';
import { engineSyncMode } from '@/lib/engine-sync-mode';
+import { revealEditor } from '@/lib/reveal-editor';
import { triggerSync } from '@/lib/trigger-sync';
import { openAccountSettings, openSyncSettings } from '@/lib/use-settings-route';
import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';
@@ -68,6 +69,7 @@ function triggerSyncFromBadge(op: ManualSyncOp = 'sync', onFailure?: () => void)
function navigateToHash(nextHash: string): void {
if (typeof window === 'undefined') return;
+ revealEditor();
if (!isSameHash(window.location.hash, nextHash)) {
window.location.hash = nextHash;
}
@@ -140,10 +142,11 @@ export function displayState(status: GitSyncStatus): GitSyncStatus['state'] {
interface BadgeIconProps {
status: GitSyncStatus;
+ size?: 'size-3.5' | 'size-4';
}
-function BadgeIcon({ status }: BadgeIconProps) {
- const cls = 'size-3.5';
+function BadgeIcon({ status, size = 'size-3.5' }: BadgeIconProps) {
+ const cls = size;
switch (displayState(status)) {
case 'dormant':
return <Cloud className={`${cls} text-muted-foreground`} />;
@@ -1488,7 +1491,7 @@ export function SyncStatusBadge({ onSignIn, onSetIdentity }: SyncStatusBadgeProp
: t`Sync status: ${syncStateLabel}`
}
>
- <BadgeIcon status={status} />
+ <BadgeIcon status={status} size="size-4" />
{label && (
<span className="absolute -top-0.5 -right-0.5 text-[9px] leading-none font-medium bg-background border rounded-full px-0.5">
{label}
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
index 20066f929..4828f6630 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.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 userEvent from '@testing-library/user-event';
-import { useEffect, useRef, useState } from 'react';
+import { type PointerEventHandler, 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,6 +11,10 @@ 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';
@@ -60,9 +64,22 @@ vi.doMock('@/components/ui/resizable', () => ({
</div>
);
},
- // biome-ignore lint/suspicious/noExplicitAny: test stub
- ResizableHandle: ({ onPointerDown, disabled, withHandle }: any) => (
- <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'}
@@ -184,7 +201,9 @@ function DockHarness({
p = 'bottom',
targetAvailable = true,
onVisibleChange,
+ onPreferredSessionHostReady,
bridge,
+ children,
// biome-ignore lint/suspicious/noExplicitAny: test harness props
}: any) {
const [bottomContainer, setBottomContainer] = useState<HTMLDivElement | null>(null);
@@ -195,16 +214,20 @@ function DockHarness({
<TerminalDock
placement={p}
visible={v}
+ available
+ variant="card"
onVisibleChange={onVisibleChange}
onBottomContainer={setBottomContainer}
- onEditorRegion={setEditorRegionEl}
>
- <div data-testid="editor-child" />
+ <div ref={setEditorRegionEl} tabIndex={-1} data-testid="editor-region">
+ {children ?? <div data-testid="editor-child" />}
+ </div>
</TerminalDock>
{p === 'right' && targetAvailable ? (
<div ref={setRightContainer} data-testid="terminal-right-mount" />
) : null}
<SessionsHost
+ {...(onPreferredSessionHostReady ? { onPreferredSessionHostReady } : {})}
surface="terminal-dock"
terminalPlacement={p}
bridge={bridge}
@@ -225,6 +248,7 @@ function renderDock(
launch?: TestLaunch | null,
placement = 'bottom',
platform: OkDesktopBridge['platform'] = 'darwin',
+ onPreferredSessionHostReady?: () => void,
) {
const onVisibleChange = vi.fn((_v: boolean) => {});
const { bridge, create, kill, input, viewMenuPushes, dispatchMenuAction } = makeBridge(platform);
@@ -235,6 +259,7 @@ function renderDock(
p={p}
targetAvailable={targetAvailable}
onVisibleChange={onVisibleChange}
+ onPreferredSessionHostReady={onPreferredSessionHostReady}
bridge={bridge}
/>
);
@@ -371,9 +396,76 @@ describe('TerminalDock multi-session', () => {
).toHaveLength(2);
});
- test('tab strip exposes the collapse button without obsolete dock or drag controls', () => {
+ 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.getByRole('button', { name: 'Collapse Terminal' })).not.toBeNull();
+ expect(screen.queryByRole('button', { name: /^Collapse/ })).toBeNull();
expect(screen.queryByRole('button', { name: /Dock sessions/ })).toBeNull();
expect(screen.queryByRole('button', { name: 'Drag to dock the terminal' })).toBeNull();
});
@@ -438,6 +530,24 @@ describe('TerminalDock multi-session', () => {
expect(sessions[1].getAttribute('data-cli')).toBe('cursor');
});
+ test('a ready terminal host claims a preferred terminal request once', () => {
+ writePreferBareTerminal(false);
+ saveStickyAgent(terminalCliId('cursor'));
+ const ready = vi.fn();
+ renderDock(true, null, 'bottom', 'darwin', ready);
+
+ expect(ready).toHaveBeenCalledTimes(1);
+ let claimed: unknown;
+ act(() => {
+ claimed = requestPreferredSession();
+ });
+
+ expect(claimed).toBe(true);
+ const sessions = screen.getAllByTestId('terminal-session');
+ expect(sessions).toHaveLength(2);
+ expect(sessions[1].getAttribute('data-cli')).toBe('cursor');
+ });
+
test('a preferred-session shortcut honors a bare-shell pick', () => {
writePreferBareTerminal(true);
renderDock(true);
@@ -840,7 +950,7 @@ describe('TerminalDock multi-session', () => {
await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
+ expect(view.onVisibleChange).toHaveBeenCalledWith(false, 'session-close');
expect(document.activeElement).toBe(editorRegion());
});
@@ -1263,13 +1373,27 @@ describe('TerminalDock multi-session', () => {
expect(document.activeElement).toBe(session);
});
- test('renders no edge reveal tab, hidden or visible', () => {
- const view = renderDock(false);
- expect(screen.queryByRole('button', { name: 'Open terminal' })).toBeNull();
- expect(editorRegion().querySelector('[data-terminal-reveal]')).toBeNull();
+ 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));
- expect(screen.queryByRole('button', { name: 'Open terminal' })).toBeNull();
+ expectVisualClassTokensAbsent(card().className, ['shadow-none']);
});
test('disables the resize handle while hidden so there is no drag-to-open', () => {
@@ -1303,7 +1427,7 @@ describe('TerminalDock extraction pins', () => {
await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
+ expect(view.onVisibleChange).toHaveBeenCalledWith(false, 'session-close');
expect(document.activeElement).toBe(editorRegion());
});
diff --git a/packages/app/src/components/TerminalDock.editor-hidden.dom.test.tsx b/packages/app/src/components/TerminalDock.editor-hidden.dom.test.tsx
new file mode 100644
index 000000000..66ca811f7
--- /dev/null
+++ b/packages/app/src/components/TerminalDock.editor-hidden.dom.test.tsx
@@ -0,0 +1,182 @@
+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.reload-survival.dom.test.tsx b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
index be477d815..aeffd9a82 100644
--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
@@ -74,9 +74,10 @@ function ReloadHarness({
<TooltipProvider>
<TerminalDock
visible={visible}
+ available
+ variant="card"
onVisibleChange={() => {}}
onBottomContainer={setBottomContainer}
- onEditorRegion={() => {}}
>
<div data-testid="editor-child" />
</TerminalDock>
diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsx
index 17ffca92a..bf84ebec6 100644
--- a/packages/app/src/components/TerminalDock.tsx
+++ b/packages/app/src/components/TerminalDock.tsx
@@ -1,7 +1,23 @@
import type { TerminalPlacement } from '@inkeep/open-knowledge-core/terminal-layout';
+import { useLingui } from '@lingui/react/macro';
import { useTheme } from 'next-themes';
-import { type ReactNode, useEffect, useRef, useState } from 'react';
+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,
@@ -9,32 +25,51 @@ import {
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;
- readonly onEditorRegion: (el: HTMLDivElement | null) => void;
}
export function TerminalDock({
+ ref,
+ editorVisible = true,
+ onBottomCollapsedChange,
children,
placement = 'bottom',
visible,
+ available,
+ variant,
onVisibleChange,
onBottomContainer,
- onEditorRegion,
}: TerminalDockProps) {
+ const { t } = useLingui();
const { resolvedTheme } = useTheme();
const panelRef = usePanelRef();
- const bottomVisible = placement === 'bottom' && visible;
+ 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());
@@ -78,7 +113,11 @@ export function TerminalDock({
[],
);
- useEffect(() => {
+ function bottomTargetSize(): string {
+ return fillsColumn ? FULL_COLUMN : `${heightPxRef.current}px`;
+ }
+
+ useLayoutEffect(() => {
const panel = panelRef.current;
if (panel == null) return;
try {
@@ -90,44 +129,83 @@ export function TerminalDock({
} 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) return;
+ if (!bottomVisible || fillsColumn) return;
try {
panelRef.current?.resize(`${next}px`);
} catch {}
};
window.addEventListener('resize', reclampToViewport);
return () => window.removeEventListener('resize', reclampToViewport);
- }, [bottomVisible, panelRef]);
+ }, [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="5%" className="flex min-h-0 flex-col">
- {}
- <div
- ref={onEditorRegion}
- tabIndex={-1}
- className="relative flex h-full min-h-0 flex-col outline-none"
- >
- {children}
- </div>
+ <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>
{}
- {placement === 'bottom' ? (
+ {bottomPresent ? (
<>
<ResizableHandle
- withHandle={bottomVisible}
- disabled={!bottomVisible}
+ 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 (!bottomVisible) return;
+ if (!bottomHandleShown) return;
endDragRef.current?.();
setIsDragging(true);
isDraggingRef.current = true;
@@ -150,16 +228,17 @@ export function TerminalDock({
/>
<ResizablePanel
id={TERMINAL_PANEL_ID}
- style={{ backgroundColor: xtermBackground }}
+ style={{ overflow: 'visible' }}
panelRef={panelRef}
defaultSize={bottomVisible ? `${initialHeightPx}px` : 0}
minSize="120px"
- maxSize="95%"
+ 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 {
@@ -183,8 +262,22 @@ export function TerminalDock({
'transition-[flex-grow] duration-150 ease-out motion-reduce:transition-none motion-reduce:duration-0',
)}
>
- {}
- <div ref={onBottomContainer} className="flex min-h-0 flex-1 flex-col overflow-hidden" />
+ <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}
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index 6e92da6de..9d5d447f4 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -12,6 +12,11 @@ import type {
OkPtyExit,
OkPtyNotice,
} from '@/lib/desktop-bridge-types';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import { terminalAgentSnapshot } from './terminal-agent-connections.test-helper';
import {
applyModelledScroll,
@@ -357,6 +362,7 @@ describe('TerminalPanel', () => {
});
afterEach(() => {
cleanup();
+ __resetPaneVisibilityStoreForTests();
});
test('mounts an accessible region, configures xterm for a11y, and creates a PTY sized to the fitted terminal', async () => {
@@ -2885,6 +2891,42 @@ describe('TerminalPanel', () => {
expect(window.location.hash).toBe('#/packages/app/');
});
+ test.each([
+ { kind: 'markdown path', line: 'edited notes/a.md', text: 'notes/a.md', hash: '#/notes/a' },
+ {
+ kind: 'trailing-slash folder',
+ line: 'cd packages/app/',
+ text: 'packages/app',
+ hash: '#/packages/app/',
+ },
+ ])(
+ 'clicking a $kind shows a hidden editor before navigating to it',
+ async ({ line, text, hash }) => {
+ const reveals: Array<PaneVisibilityRequest & { hashWhenAsked: string }> = [];
+ paneVisibilityStore.subscribeRequests((request) => {
+ reveals.push({ ...request, hashWhenAsked: window.location.hash });
+ });
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.lineText = line;
+
+ const [link] = await provide(term);
+ expect(link?.text).toBe(text);
+ window.location.hash = '';
+ link?.activate({} as MouseEvent, link.text);
+
+ expect(reveals).toEqual([{ pane: 'editor', open: true, hashWhenAsked: '' }]);
+ expect(window.location.hash).toBe(hash);
+ },
+ );
+
test('a non-blocked openAsset failure surfaces silently — no reveal fallback', async () => {
const { bridge, openAsset, revealAsset } = makeBridge({ ok: true, ptyId: 'pty-1' });
render(<TerminalPanel bridge={bridge} />);
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 4075371a9..d1dfa84b6 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -28,6 +28,7 @@ import { useTheme } from 'next-themes';
import { use, useEffect, useRef, useState } from 'react';
import { ConfigContext } from '@/lib/config-context';
import type { OkDesktopBridge, OkPtyNotice } from '@/lib/desktop-bridge-types';
+import { revealEditor } from '@/lib/reveal-editor';
import { cn } from '@/lib/utils';
import { getPageListCache } from '../editor/page-list-cache';
import { filePathToDocName, hashFromDocName, hashFromFolderPath } from '../lib/doc-hash';
@@ -286,9 +287,11 @@ function TerminalSession({
const activateFileLink = (target: TerminalLinkTarget) => {
switch (target.kind) {
case 'doc':
+ revealEditor();
window.location.hash = hashFromDocName(filePathToDocName(target.relPath));
return;
case 'folder':
+ revealEditor();
window.location.hash = hashFromFolderPath(target.relPath);
return;
case 'external':
@@ -395,7 +398,17 @@ function TerminalSession({
if (cancelled || sessionEnded || terminalInputEnabledRef.current) return;
terminalInputEnabledRef.current = true;
setStatus('running');
- term.focus();
+ const active = document.activeElement;
+ const sessionHost = term.element?.closest('[data-session-id]') ?? term.element;
+ const focusUnclaimed =
+ active === null || active === document.body || sessionHost?.contains(active) === true;
+ const hostRect = sessionHost?.getBoundingClientRect();
+ const hostOnScreen =
+ sessionHost?.closest('[inert]') == null &&
+ hostRect !== undefined &&
+ hostRect.width > 0 &&
+ hostRect.height > 0;
+ if (focusUnclaimed || hostOnScreen) term.focus();
};
term.attachCustomKeyEventHandler((event) => {
diff --git a/packages/app/src/components/TerminalRevealTab.dom.test.tsx b/packages/app/src/components/TerminalRevealTab.dom.test.tsx
deleted file mode 100644
index 05e70473b..000000000
--- a/packages/app/src/components/TerminalRevealTab.dom.test.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
-import { cleanup, render, screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { afterEach, describe, expect, test, vi } from 'vitest';
-import { TooltipProvider } from '@/components/ui/tooltip';
-
-let openThreads: ThreadInfo[] = [];
-
-vi.doMock('@/lib/acp/thread-client', () => ({
- useOpenAgentThreadTabs: () => openThreads,
-}));
-
-const { TerminalRevealTab } = await import('./TerminalRevealTab');
-
-const LABEL = { bottom: 'Open terminal', right: 'Open agents panel' } as const;
-
-function makeThread(overrides: Partial<ThreadInfo> & { threadId: string }): ThreadInfo {
- return {
- agent: { id: 'a', name: 'Agent', source: 'registry' },
- title: overrides.threadId,
- status: 'ready',
- createdAt: 1,
- lastActivityAt: 1,
- lastSeq: 0,
- archived: false,
- ...overrides,
- };
-}
-
-function renderTab(edge: 'bottom' | 'right') {
- const onReveal = vi.fn(() => {});
- render(
- <TooltipProvider>
- <TerminalRevealTab edge={edge} onReveal={onReveal} />
- </TooltipProvider>,
- );
- return { onReveal };
-}
-
-describe('TerminalRevealTab', () => {
- afterEach(() => {
- cleanup();
- openThreads = [];
- });
-
- test('names the panel it reopens and fires onReveal on click', async () => {
- const user = userEvent.setup();
- const { onReveal } = renderTab('right');
-
- await user.click(screen.getByRole('button', { name: LABEL.right }));
-
- expect(onReveal).toHaveBeenCalledTimes(1);
- });
-
- test('labels each edge for its own panel, so the two are never confusable', () => {
- renderTab('right');
- expect(screen.getByRole('button', { name: LABEL.right })).toBeTruthy();
- expect(screen.queryByRole('button', { name: LABEL.bottom })).toBeNull();
- cleanup();
-
- renderTab('bottom');
- expect(screen.getByRole('button', { name: LABEL.bottom })).toBeTruthy();
- expect(screen.queryByRole('button', { name: LABEL.right })).toBeNull();
- });
-
- test('marks which edge it hugs so it sits where the collapse control was', () => {
- renderTab('right');
- expect(
- screen.getByRole('button', { name: LABEL.right }).getAttribute('data-terminal-reveal'),
- ).toBe('right');
- cleanup();
-
- renderTab('bottom');
- expect(
- screen.getByRole('button', { name: LABEL.bottom }).getAttribute('data-terminal-reveal'),
- ).toBe('bottom');
- });
-
- test('surfaces its label in a tooltip on hover', async () => {
- const user = userEvent.setup();
- renderTab('bottom');
-
- await user.hover(screen.getByRole('button', { name: LABEL.bottom }));
-
- const tooltip = await screen.findByRole('tooltip');
- expect(tooltip.textContent).toContain(LABEL.bottom);
- });
-
- test('a live thread surfaces a presence dot on the agents edge while the panel is closed', () => {
- openThreads = [
- makeThread({ threadId: 't1', title: 'Working' }),
- makeThread({ threadId: 't2', title: 'Also working', createdAt: 2, lastActivityAt: 2 }),
- makeThread({ threadId: 't3', title: 'Third', createdAt: 3, lastActivityAt: 3 }),
- ];
-
- renderTab('right');
-
- expect(screen.getByTestId('agents-reveal-live-dot')).toBeTruthy();
- expect(screen.getByTestId('agents-reveal-live-dot').getAttribute('aria-hidden')).toBe('true');
- expect(
- screen.getByRole('button', { name: 'Open agents panel — 3 live agent threads' }),
- ).toBeTruthy();
- });
-
- test('one live thread names the panel with the singular live count', () => {
- openThreads = [makeThread({ threadId: 't1', title: 'Working' })];
-
- renderTab('right');
-
- expect(
- screen.getByRole('button', { name: 'Open agents panel — 1 live agent thread' }),
- ).toBeTruthy();
- });
-
- test('no presence dot without live threads, on the terminal edge, or for archived-only threads', () => {
- renderTab('right');
- expect(screen.queryByTestId('agents-reveal-live-dot')).toBeNull();
- cleanup();
-
- openThreads = [makeThread({ threadId: 't1', title: 'Working' })];
- renderTab('bottom');
- expect(screen.queryByTestId('agents-reveal-live-dot')).toBeNull();
- cleanup();
-
- openThreads = [makeThread({ threadId: 't1', title: 'History', archived: true })];
- renderTab('right');
- expect(screen.queryByTestId('agents-reveal-live-dot')).toBeNull();
- });
-});
diff --git a/packages/app/src/components/TerminalRevealTab.tsx b/packages/app/src/components/TerminalRevealTab.tsx
deleted file mode 100644
index 2e323b455..000000000
--- a/packages/app/src/components/TerminalRevealTab.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { plural } from '@lingui/core/macro';
-import { useLingui } from '@lingui/react/macro';
-import { ChevronLeftIcon, ChevronUpIcon } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { useOpenAgentThreadTabs } from '@/lib/acp/thread-client';
-import { cn } from '@/lib/utils';
-import type { SessionPanelEdge } from './TerminalTabStrip';
-
-interface TerminalRevealTabProps {
- readonly edge: SessionPanelEdge;
- readonly onReveal: () => void;
- readonly className?: string;
-}
-
-export function TerminalRevealTab({ edge, onReveal, className }: TerminalRevealTabProps) {
- const { t } = useLingui();
- const rightEdge = edge === 'right';
- const openThreadTabs = useOpenAgentThreadTabs();
- const liveThreadCount = openThreadTabs.filter((info) => info.archived !== true).length;
- const label = rightEdge
- ? liveThreadCount > 0
- ? t`Open agents panel — ${plural(liveThreadCount, {
- one: '# live agent thread',
- other: '# live agent threads',
- })}`
- : t`Open agents panel`
- : t`Open terminal`;
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="outline"
- size="icon-sm"
- aria-label={label}
- data-terminal-reveal={edge}
- onClick={onReveal}
- className={cn(
- 'absolute z-20 shrink-0 bg-background text-muted-foreground shadow-sm hover:text-foreground',
- rightEdge ? 'rounded-r-none border-r-0' : 'rounded-b-none border-b-0',
- className,
- )}
- >
- {rightEdge ? (
- <ChevronLeftIcon aria-hidden="true" />
- ) : (
- <ChevronUpIcon aria-hidden="true" />
- )}
- {rightEdge && liveThreadCount > 0 ? (
- <span
- aria-hidden="true"
- data-testid="agents-reveal-live-dot"
- className="absolute top-1 end-1 size-1.5 rounded-full bg-emerald-600 ring-1 ring-background"
- />
- ) : null}
- </Button>
- </TooltipTrigger>
- <TooltipContent side={rightEdge ? 'left' : 'top'} sideOffset={8}>
- {label}
- </TooltipContent>
- </Tooltip>
- );
-}
diff --git a/packages/app/src/components/TerminalTabStrip.dom.test.tsx b/packages/app/src/components/TerminalTabStrip.dom.test.tsx
index 6c59858ef..c8b9006ef 100644
--- a/packages/app/src/components/TerminalTabStrip.dom.test.tsx
+++ b/packages/app/src/components/TerminalTabStrip.dom.test.tsx
@@ -31,14 +31,12 @@ function renderStrip(props?: {
draggable?: boolean;
renameDisabled?: boolean;
withTrailing?: boolean;
- reserveRightRevealTabGutter?: boolean;
}) {
const onSelect = vi.fn((_id: string) => {});
const onTabActivate = vi.fn((_id: string) => {});
const onNewButtonClick = vi.fn(() => {});
const onClose = vi.fn((_id: string) => {});
const onRename = vi.fn((_id: string, _label: string) => {});
- const onCollapse = vi.fn(() => {});
const onPlacementChange = vi.fn((_placement: 'bottom' | 'right') => {});
const view = render(
<TooltipProvider>
@@ -60,8 +58,6 @@ function renderStrip(props?: {
sessionKind={props?.sessionKind ?? (props?.edge === 'right' ? 'agent' : 'terminal')}
edge={props?.draggable ? undefined : (props?.edge ?? 'bottom')}
onPlacementChange={props?.draggable ? undefined : onPlacementChange}
- reserveRightRevealTabGutter={props?.reserveRightRevealTabGutter}
- onCollapse={props?.draggable ? undefined : onCollapse}
draggable={props?.draggable}
/>
</TooltipProvider>,
@@ -72,7 +68,6 @@ function renderStrip(props?: {
onNewButtonClick,
onClose,
onRename,
- onCollapse,
onPlacementChange,
rerender: view.rerender,
};
@@ -322,28 +317,38 @@ describe('TerminalTabStrip', () => {
expect(onSelect).not.toHaveBeenCalled();
});
- test('the New button hugs the last tab, preceding the trailing collapse control', () => {
+ test('the New button hugs the last tab, preceding the trailing placement control', () => {
renderStrip();
const newButton = screen.getByRole('button', { name: 'New session' });
- const collapse = screen.getByRole('button', { name: 'Collapse Terminal' });
+ const placement = screen.getByRole('button', { name: 'Move Terminal to right' });
expect(
- newButton.compareDocumentPosition(collapse) & Node.DOCUMENT_POSITION_FOLLOWING,
+ newButton.compareDocumentPosition(placement) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});
- test('trailing controls render at the far right, immediately left of the collapse control', () => {
+ test('trailing controls render at the far right, immediately left of the placement control', () => {
renderStrip({ withTrailing: true });
const trailing = screen.getByRole('button', { name: 'Reopen a past chat' });
const newButton = screen.getByRole('button', { name: 'New session' });
- const collapse = screen.getByRole('button', { name: 'Collapse Terminal' });
+ const placement = screen.getByRole('button', { name: 'Move Terminal to right' });
expect(
newButton.compareDocumentPosition(trailing) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(
- trailing.compareDocumentPosition(collapse) & Node.DOCUMENT_POSITION_FOLLOWING,
+ trailing.compareDocumentPosition(placement) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});
+ test('neither strip offers an in-pane collapse control; the header buttons and shortcuts hide the panes', () => {
+ renderStrip({ edge: 'bottom', sessionKind: 'terminal', withTrailing: true });
+ expect(screen.queryByRole('button', { name: /^Collapse/ })).toBeNull();
+ cleanup();
+ renderStrip({ edge: 'right', sessionKind: 'agent', withTrailing: true });
+ expect(screen.queryByRole('button', { name: /^Collapse/ })).toBeNull();
+ const buttons = screen.getAllByRole('button');
+ expect(buttons.at(-1)).toBe(screen.getByRole('button', { name: 'Reopen a past chat' }));
+ });
+
test('a tab close control reports onClose with that session id only', async () => {
const user = userEvent.setup();
const { onClose, onSelect, onNewButtonClick } = renderStrip({ activeSessionId: 's1' });
@@ -436,38 +441,16 @@ describe('TerminalTabStrip', () => {
expect(onPlacementChange).toHaveBeenCalledWith('right');
});
- test('the right Terminal header clears the collapsed agents reveal control', () => {
- renderStrip({
- edge: 'right',
- sessionKind: 'terminal',
- reserveRightRevealTabGutter: true,
- });
-
- expect(document.querySelector('[data-terminal-tab-row]')?.className).toContain('pr-9');
- });
-
test('the agent strip keeps independent names and controls without Terminal placement actions', () => {
renderStrip({ edge: 'right', sessionKind: 'agent' });
expect(screen.getByRole('tablist', { name: 'Agent chats' })).toBeDefined();
- expect(screen.getByRole('button', { name: 'Collapse agent panel' })).toBeDefined();
expect(screen.queryByRole('button', { name: /Move Terminal/ })).toBeNull();
fireEvent.contextMenu(screen.getByRole('tablist', { name: 'Agent chats' }));
expect(screen.queryByRole('menu')).toBeNull();
});
- test('the collapse control reports onCollapse and never onClose / new-button', async () => {
- const user = userEvent.setup();
- const { onCollapse, onClose, onNewButtonClick } = renderStrip();
-
- await user.click(screen.getByRole('button', { name: 'Collapse Terminal' }));
-
- expect(onCollapse).toHaveBeenCalledTimes(1);
- expect(onClose).not.toHaveBeenCalled();
- expect(onNewButtonClick).not.toHaveBeenCalled();
- });
-
test('no drag-to-dock grip is rendered (dragging was removed)', () => {
renderStrip();
expect(screen.queryByRole('button', { name: 'Drag to dock the terminal' })).toBeNull();
@@ -475,7 +458,7 @@ describe('TerminalTabStrip', () => {
test('every strip-owned icon-only control exposes an accessible name', () => {
renderStrip();
- expect(screen.getByRole('button', { name: 'Collapse Terminal' })).toBeDefined();
+ expect(screen.getByRole('button', { name: 'Move Terminal to right' })).toBeDefined();
for (const label of ['Terminal 1', 'Terminal 2', 'Terminal 3']) {
expect(screen.getByRole('button', { name: `Close ${label}` })).toBeDefined();
}
@@ -484,7 +467,6 @@ describe('TerminalTabStrip', () => {
test('window mode marks the bar as the draggable macOS title region; dock mode does not', () => {
renderStrip({ draggable: true });
expect(document.querySelector('[data-electron-drag]')).not.toBeNull();
- expect(screen.queryByRole('button', { name: 'Collapse Terminal' })).toBeNull();
expect(screen.getByRole('button', { name: 'New session' })).toBeDefined();
cleanup();
renderStrip();
@@ -635,7 +617,6 @@ describe('TerminalTabStrip', () => {
onClose={() => {}}
onRename={() => {}}
edge="bottom"
- onCollapse={() => {}}
/>
</TooltipProvider>,
);
@@ -661,3 +642,50 @@ describe('TerminalTabStrip', () => {
expect(within(tablist).queryAllByRole('button', { name: /^Terminal/ })).toHaveLength(0);
});
});
+
+describe('TerminalTabStrip as a card top bar', () => {
+ afterEach(() => {
+ cleanup();
+ Reflect.deleteProperty(window, 'okDesktop');
+ });
+
+ test('a docked strip is a 44px top bar with no hairline, matching the tab row', () => {
+ renderStrip({ edge: 'right', sessionKind: 'agent' });
+ const row = document.querySelector('[data-terminal-tab-row]');
+ expect(row?.className).toContain('h-11');
+ expect(row?.className).not.toContain('shadow-[inset_0_-1px_0_var(--border)]');
+ expect(row?.className).not.toContain('h-[62px]');
+ expect(row?.className).not.toContain('[-webkit-app-region:drag]');
+ expect(row?.hasAttribute('data-electron-drag')).toBe(false);
+ });
+
+ test('the detached terminal window keeps its 62px title strip', () => {
+ renderStrip({ edge: 'bottom', sessionKind: 'terminal', draggable: true });
+ const row = document.querySelector('[data-terminal-tab-row]');
+ expect(row?.className).toContain('h-[62px]');
+ expect(row?.className).not.toContain('h-11');
+ expect(row?.className).toContain('[-webkit-app-region:drag]');
+ });
+
+ test('on desktop the docked strip drags the window from its empty space while every control opts out', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'editor' } },
+ });
+ renderStrip({ edge: 'bottom', sessionKind: 'terminal', withTrailing: true });
+ const row = document.querySelector('[data-terminal-tab-row]');
+ expect(row?.getAttribute('data-electron-drag')).toBe('');
+ expect(row?.className).toContain('[-webkit-app-region:drag]');
+ expect(row?.className).toContain('h-11');
+ for (const control of [
+ screen.getByRole('button', { name: 'Move Terminal to right' }),
+ screen.getByRole('button', { name: 'Reopen a past chat' }),
+ screen.getByRole('tab', { name: 'Terminal 1' }),
+ ]) {
+ expect(
+ control.closest('.\\[-webkit-app-region\\:no-drag\\]'),
+ `${control.getAttribute('aria-label') ?? control.textContent} opts out of the drag band`,
+ ).not.toBeNull();
+ }
+ });
+});
diff --git a/packages/app/src/components/TerminalTabStrip.tsx b/packages/app/src/components/TerminalTabStrip.tsx
index f51647c02..2efeb7880 100644
--- a/packages/app/src/components/TerminalTabStrip.tsx
+++ b/packages/app/src/components/TerminalTabStrip.tsx
@@ -8,13 +8,7 @@ import {
useSortable,
} from '@dnd-kit/sortable';
import { Trans, useLingui } from '@lingui/react/macro';
-import {
- ChevronDownIcon,
- ChevronRightIcon,
- PanelBottomIcon,
- PanelRightIcon,
- XIcon,
-} from 'lucide-react';
+import { PanelBottomIcon, PanelRightIcon, XIcon } from 'lucide-react';
import { type ReactElement, type ReactNode, useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
@@ -25,6 +19,7 @@ import {
ContextMenuTrigger,
} from '@/components/ui/context-menu';
import { InputGroup, InputGroupInput } from '@/components/ui/input-group';
+import { PANE_CARD_TOP_BAR_CLASS } from '@/components/ui/pane-card';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
@@ -149,8 +144,6 @@ interface TerminalTabStripProps {
readonly onDragActiveChange?: (active: boolean) => void;
readonly edge?: SessionPanelEdge;
readonly onPlacementChange?: (placement: SessionPanelEdge) => void;
- readonly reserveRightRevealTabGutter?: boolean;
- readonly onCollapse?: () => void;
readonly children?: ReactNode;
readonly className?: string;
readonly draggable?: boolean;
@@ -170,14 +163,14 @@ export function TerminalTabStrip({
onDragActiveChange,
edge,
onPlacementChange,
- reserveRightRevealTabGutter,
- onCollapse,
children,
className,
draggable,
}: TerminalTabStripProps) {
const { t } = useLingui();
const rightEdge = edge === 'right';
+ const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
+ const windowDragRegion = draggable || isElectronHost;
const placementTarget: SessionPanelEdge = rightEdge ? 'bottom' : 'right';
const placementLabel = rightEdge ? t`Move Terminal to bottom` : t`Move Terminal to right`;
const onMoveRight =
@@ -279,12 +272,13 @@ export function TerminalTabStrip({
<div
ref={rowRef}
data-terminal-tab-row=""
- data-electron-drag={draggable ? '' : undefined}
+ data-electron-drag={windowDragRegion ? '' : undefined}
className={cn(
'flex shrink-0 flex-row items-center gap-1 px-1.5 py-1',
- rightEdge && reserveRightRevealTabGutter && 'pr-9',
+ !draggable && PANE_CARD_TOP_BAR_CLASS,
+ windowDragRegion && '[-webkit-app-region:drag]',
draggable &&
- 'h-[62px] [-webkit-app-region:drag] pr-[22px] pl-[calc(var(--ok-titlebar-reserve-left,1rem)+0.75rem)]',
+ 'h-[62px] pr-[22px] pl-[calc(var(--ok-titlebar-reserve-left,1rem)+0.75rem)]',
)}
>
<DndContext
@@ -308,7 +302,7 @@ export function TerminalTabStrip({
onWheel={scrollTabStripOnWheel}
className={cn(
'grid h-auto w-fit max-w-full min-w-0 grid-flow-col items-center justify-start gap-0.5 overflow-x-auto overflow-y-hidden [grid-auto-columns:minmax(8rem,9rem)] [scrollbar-width:none] scroll-fade-mask-x',
- draggable && '[-webkit-app-region:no-drag]',
+ windowDragRegion && '[-webkit-app-region:no-drag]',
)}
>
<TabsList
@@ -364,7 +358,7 @@ export function TerminalTabStrip({
? TAB_SELECTED_SURFACE_IMPORTANT_CLASS
: isHovered && TAB_HOVER_SURFACE_IMPORTANT_CLASS,
isRenaming && 'w-full opacity-0',
- draggable && '[-webkit-app-region:no-drag]',
+ windowDragRegion && '[-webkit-app-region:no-drag]',
)}
>
{session.icon}
@@ -405,7 +399,7 @@ export function TerminalTabStrip({
style={{ gridColumn: index + 1, gridRow: 1 }}
className={cn(
'z-20 h-7 w-full rounded-md border-0 bg-transparent dark:bg-transparent',
- draggable && '[-webkit-app-region:no-drag]',
+ windowDragRegion && '[-webkit-app-region:no-drag]',
)}
>
<InputGroupInput
@@ -444,7 +438,7 @@ export function TerminalTabStrip({
'z-20 mr-0.5 justify-self-end opacity-0 transition-opacity focus-visible:opacity-100',
(isActive || hoveredId === session.id) && 'opacity-100',
tabReorderBounds != null && 'pointer-events-none opacity-0',
- draggable && '[-webkit-app-region:no-drag]',
+ windowDragRegion && '[-webkit-app-region:no-drag]',
)}
onMouseEnter={() => setHoveredId(session.id)}
onMouseLeave={() => setHoveredId(null)}
@@ -463,7 +457,7 @@ export function TerminalTabStrip({
</DndContext>
{}
{newButton != null ? (
- <div className={cn('shrink-0', draggable && '[-webkit-app-region:no-drag]')}>
+ <div className={cn('shrink-0', windowDragRegion && '[-webkit-app-region:no-drag]')}>
{newButton}
</div>
) : null}
@@ -471,7 +465,7 @@ export function TerminalTabStrip({
<div className="flex-1" />
{}
{trailingControls != null ? (
- <div className={cn('shrink-0', draggable && '[-webkit-app-region:no-drag]')}>
+ <div className={cn('shrink-0', windowDragRegion && '[-webkit-app-region:no-drag]')}>
{trailingControls}
</div>
) : null}
@@ -483,7 +477,10 @@ export function TerminalTabStrip({
variant="ghost"
size="icon-xs"
aria-label={placementLabel}
- className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"
+ className={cn(
+ 'shrink-0 cursor-pointer text-muted-foreground hover:text-foreground',
+ windowDragRegion && '[-webkit-app-region:no-drag]',
+ )}
onClick={() => onPlacementChange(placementTarget)}
>
{rightEdge ? (
@@ -498,36 +495,6 @@ export function TerminalTabStrip({
</TooltipContent>
</Tooltip>
) : null}
- {onCollapse != null ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon-xs"
- aria-label={
- sessionKind === 'terminal' ? t`Collapse Terminal` : t`Collapse agent panel`
- }
- className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"
- onClick={onCollapse}
- >
- {}
- {rightEdge ? (
- <ChevronRightIcon aria-hidden="true" />
- ) : (
- <ChevronDownIcon aria-hidden="true" />
- )}
- </Button>
- </TooltipTrigger>
- <TooltipContent side="bottom" sideOffset={8}>
- {sessionKind === 'terminal' ? (
- <Trans>Collapse Terminal</Trans>
- ) : (
- <Trans>Collapse agent panel</Trans>
- )}
- </TooltipContent>
- </Tooltip>
- ) : null}
</div>
</BottomTerminalPlacementMenu>
{children}
diff --git a/packages/app/src/components/TextDocEditor.tsx b/packages/app/src/components/TextDocEditor.tsx
index 4d5d7d006..59ec8dc32 100644
--- a/packages/app/src/components/TextDocEditor.tsx
+++ b/packages/app/src/components/TextDocEditor.tsx
@@ -92,12 +92,12 @@ export function TextDocEditor({
}, [ytext, provider, resolvedTheme, docName, undoManager]);
return (
- <main
+ <section
className="flex h-full min-h-0 flex-col bg-background"
aria-label={t`${basename} — text editor`}
data-text-doc-editor=""
>
<div ref={containerRef} className="min-h-0 flex-1 overflow-auto" />
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/TextViewer.tsx b/packages/app/src/components/TextViewer.tsx
index 41a6f3860..5195f4ab9 100644
--- a/packages/app/src/components/TextViewer.tsx
+++ b/packages/app/src/components/TextViewer.tsx
@@ -92,7 +92,7 @@ export function TextViewer({ fileName, extension, ...source }: TextViewerProps)
}
return (
- <main
+ <section
className="flex h-full min-h-0 flex-col bg-background"
aria-label={fileName}
data-text-viewer=""
@@ -100,6 +100,6 @@ export function TextViewer({ fileName, extension, ...source }: TextViewerProps)
data-text-viewer-extension={extension}
>
<div ref={containerRef} className="min-h-0 flex-1 overflow-auto" />
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/TimelineDiffPane.destination.dom.test.tsx b/packages/app/src/components/TimelineDiffPane.destination.dom.test.tsx
new file mode 100644
index 000000000..3a0554837
--- /dev/null
+++ b/packages/app/src/components/TimelineDiffPane.destination.dom.test.tsx
@@ -0,0 +1,80 @@
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+vi.mock('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+vi.mock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ activeProvider: null, activeDocName: 'notes' }),
+}));
+
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { TimelineDiffView } from '@/lib/timeline-diff-store';
+
+const { TimelineDiffPane } = await import('./TimelineDiffPane');
+
+const MISSING_SHA = 'a'.repeat(40);
+const PRESENT_SHA = 'b'.repeat(40);
+
+function viewFor(sha: string): TimelineDiffView {
+ return {
+ docName: 'notes',
+ sha,
+ parentSha: null,
+ laterEdits: 0,
+ authorName: 'Alice',
+ relativeTime: '2 hours ago',
+ absoluteTime: '2026-04-17 00:00',
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('TimelineDiffPane destination settlement', () => {
+ test('a failed selection does not settle the next selection as failed', async () => {
+ let releasePresent: (() => void) | undefined;
+ globalThis.fetch = vi.fn((input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input.toString();
+ if (url.includes(`/api/history/${PRESENT_SHA}`)) {
+ return new Promise<Response>((resolve) => {
+ releasePresent = () =>
+ resolve(
+ new Response(JSON.stringify({ content: 'present\n' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+ });
+ }
+ return Promise.resolve(new Response(null, { status: 404 }));
+ }) as never;
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onDestinationComplete = vi.fn();
+ const onDestinationFailed = vi.fn();
+ const pane = (sha: string) => (
+ <TooltipProvider>
+ <TimelineDiffPane
+ view={viewFor(sha)}
+ isPanelCollapsed={false}
+ onTogglePanel={() => {}}
+ onDestinationComplete={onDestinationComplete}
+ onDestinationFailed={onDestinationFailed}
+ />
+ </TooltipProvider>
+ );
+
+ const { rerender } = render(pane(MISSING_SHA));
+ await waitFor(() => expect(onDestinationFailed).toHaveBeenCalledTimes(1));
+
+ rerender(pane(PRESENT_SHA));
+ await waitFor(() => expect(releasePresent).toBeDefined());
+ expect(onDestinationFailed).toHaveBeenCalledTimes(1);
+ releasePresent?.();
+
+ await waitFor(() => expect(onDestinationComplete).toHaveBeenCalledTimes(1));
+ expect(onDestinationFailed).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/components/TimelineDiffPane.tsx b/packages/app/src/components/TimelineDiffPane.tsx
index c908e2863..50c0d5899 100644
--- a/packages/app/src/components/TimelineDiffPane.tsx
+++ b/packages/app/src/components/TimelineDiffPane.tsx
@@ -3,7 +3,7 @@
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core/schemas/api';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { ChevronDown, ChevronUp, PanelRightClose, PanelRightOpen, Undo2, X } from 'lucide-react';
-import { lazy, Suspense, useEffect, useRef, useState } from 'react';
+import { lazy, Suspense, useEffect, useEffectEvent, useRef, useState } from 'react';
import { toast } from 'sonner';
import { MAX_RENDERED_CHANGES, PropertyDiffBlock } from '@/components/PropertyDiffBlock';
import { computeRenderedDiff, RenderedDiffView } from '@/components/RenderedDiffView';
@@ -33,6 +33,7 @@ import {
import { closeTimelineDiff, type TimelineDiffView } from '@/lib/timeline-diff-store';
import {
HISTORICAL_CONTENT_CACHE_LIMIT,
+ timelineEntryCacheKey,
useTimelineEntryDiff,
} from '@/lib/use-timeline-entry-diff';
@@ -45,9 +46,17 @@ interface TimelineDiffPaneProps {
view: TimelineDiffView;
isPanelCollapsed: boolean;
onTogglePanel: () => void;
+ onDestinationComplete?: (target?: HTMLElement) => void;
+ onDestinationFailed?: () => void;
}
-export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: TimelineDiffPaneProps) {
+export function TimelineDiffPane({
+ view,
+ isPanelCollapsed,
+ onTogglePanel,
+ onDestinationComplete,
+ onDestinationFailed,
+}: TimelineDiffPaneProps) {
const { t } = useLingui();
const { docName, sha, parentSha, laterEdits, authorName, relativeTime } = view;
const [cache] = useState(() => new LruStringCache(HISTORICAL_CONTENT_CACHE_LIMIT));
@@ -55,12 +64,30 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Time
const [dialogOpen, setDialogOpen] = useState(false);
const [restoring, setRestoring] = useState(false);
const abortRef = useRef<AbortController | null>(null);
+ const closeButtonRef = useRef<HTMLButtonElement>(null);
const diffBodyRef = useRef<HTMLDivElement>(null);
const [currentChange, setCurrentChange] = useState(0);
const [pierreChangeCount, setPierreChangeCount] = useState(0);
const [pierreSettled, setPierreSettled] = useState(false);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const result = useTimelineEntryDiff(sha, docName, cache, 'vs-parent', parentSha);
+ const completeDestination = useEffectEvent(() => {
+ onDestinationComplete?.(closeButtonRef.current ?? undefined);
+ });
+ const failDestination = useEffectEvent(() => onDestinationFailed?.());
+ const settledRequestRef = useRef<TimelineDiffView | null>(null);
+ useEffect(() => {
+ if (settledRequestRef.current === view) return;
+ if (result.status !== 'ready' && result.status !== 'error') return;
+ if (result.key !== timelineEntryCacheKey(docName, sha)) return;
+ if (result.status === 'ready') {
+ settledRequestRef.current = view;
+ completeDestination();
+ } else {
+ settledRequestRef.current = view;
+ failDestination();
+ }
+ }, [result, docName, sha, view]);
const rendered =
result.status === 'ready' ? computeRenderedDiff(result.before, result.after) : null;
@@ -246,6 +273,7 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Time
<Tooltip>
<TooltipTrigger asChild>
<Button
+ ref={closeButtonRef}
variant="ghost"
size="icon"
className="size-7 shrink-0"
diff --git a/packages/app/src/components/UpdateNotices.tsx b/packages/app/src/components/UpdateNotices.tsx
index a3c9d3e10..1da6d27bc 100644
--- a/packages/app/src/components/UpdateNotices.tsx
+++ b/packages/app/src/components/UpdateNotices.tsx
@@ -1,9 +1,7 @@
// oxlint-disable ok/no-raw-html-interactive-element -- pre-rule backlog — file uses raw <button>/<input>/<textarea> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-raw-html-interactive-element
-// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility
-
import { useLingui } from '@lingui/react/macro';
-import { X } from 'lucide-react';
+import { TriangleAlertIcon, X } from 'lucide-react';
import type { ReactNode } from 'react';
import { useSyncExternalStore } from 'react';
import { Button } from '@/components/ui/button';
@@ -38,25 +36,37 @@ export function NoticeCard({ notice, onDismiss }: { notice: UpdateNotice; onDism
const { t } = useLingui();
const tone =
notice.variant === 'error'
- ? 'border-destructive/60 bg-sidebar-accent/30 text-muted-foreground'
+ ? 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300'
: notice.variant === 'success'
- ? 'border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
- : 'border-sidebar-border bg-sidebar-accent/30 text-muted-foreground';
+ ? 'border-emerald-500/40 text-emerald-700 dark:text-emerald-400'
+ : 'text-muted-foreground';
+ const dismissTone =
+ notice.variant === 'error'
+ ? 'text-amber-700 hover:bg-amber-100 hover:text-amber-800 dark:text-amber-300 dark:hover:bg-amber-900 dark:hover:text-amber-200'
+ : 'text-muted-foreground hover:text-sidebar-foreground';
const dismissButton =
notice.dismissible === false ? null : (
<Button
variant="ghost"
size="icon"
- className="size-5 shrink-0 text-muted-foreground hover:text-sidebar-foreground"
+ className={`size-5 shrink-0 ${dismissTone}`}
aria-label={t`Dismiss notice`}
onClick={onDismiss}
>
<X aria-hidden="true" className="size-3" />
</Button>
);
- const actionDecoration =
- notice.variant === 'success' ? 'decoration-emerald-500/40' : 'decoration-muted-foreground/40';
- const actionButtonClass = `shrink-0 text-xs font-medium underline underline-offset-2 ${actionDecoration} hover:text-sidebar-foreground hover:decoration-sidebar-foreground`;
+ const warningIcon =
+ notice.variant === 'error' ? (
+ <TriangleAlertIcon aria-hidden="true" className="mt-px size-3.5 shrink-0" />
+ ) : null;
+ const actionTone =
+ notice.variant === 'error'
+ ? 'decoration-amber-700/40 hover:text-amber-800 hover:decoration-amber-800 dark:decoration-amber-300/40 dark:hover:text-amber-200 dark:hover:decoration-amber-200'
+ : notice.variant === 'success'
+ ? 'decoration-emerald-500/40 hover:text-sidebar-foreground hover:decoration-sidebar-foreground'
+ : 'decoration-muted-foreground/40 hover:text-sidebar-foreground hover:decoration-sidebar-foreground';
+ const actionButtonClass = `shrink-0 text-xs font-medium underline underline-offset-2 ${actionTone}`;
if (notice.secondaryAction) {
return (
@@ -64,13 +74,14 @@ export function NoticeCard({ notice, onDismiss }: { notice: UpdateNotice; onDism
role="status"
aria-live="polite"
data-testid={`update-notice-${notice.id}`}
- className={`flex flex-col gap-2 rounded-md border px-2 py-2 text-xs ${tone}`}
+ className={`floating-card-surface relative flex w-fit max-w-full flex-col gap-2 py-2 ps-3 ${dismissButton ? 'pe-9' : 'pe-3'} text-xs ${tone}`}
>
<div className="flex items-start gap-2">
- <span className="flex-1 leading-snug">{notice.body}</span>
- {dismissButton}
+ {warningIcon}
+ <span className="min-w-0 flex-1 leading-snug wrap-anywhere">{notice.body}</span>
</div>
- <div className="flex gap-3 pl-1">
+ {dismissButton ? <div className="absolute end-1.5 top-1.5">{dismissButton}</div> : null}
+ <div className={`flex gap-3 ${warningIcon ? 'ps-5.5' : 'ps-1'}`}>
{notice.action ? (
<button
type="button"
@@ -101,9 +112,10 @@ export function NoticeCard({ notice, onDismiss }: { notice: UpdateNotice; onDism
role="status"
aria-live="polite"
data-testid={`update-notice-${notice.id}`}
- className={`flex items-center gap-2 rounded-md border px-2 py-1.5 text-xs ${tone}`}
+ className={`floating-card-surface relative flex w-fit max-w-full items-center gap-3 py-2 ps-3 ${dismissButton ? 'pe-9' : 'pe-3'} text-xs ${tone}`}
>
- <span className="flex-1 leading-snug">{notice.body}</span>
+ {warningIcon}
+ <span className="min-w-0 flex-1 leading-snug wrap-anywhere">{notice.body}</span>
{notice.action ? (
<button
type="button"
@@ -115,7 +127,7 @@ export function NoticeCard({ notice, onDismiss }: { notice: UpdateNotice; onDism
{notice.action.label}
</button>
) : null}
- {dismissButton}
+ {dismissButton ? <div className="absolute end-1.5 top-1.5">{dismissButton}</div> : null}
</div>
);
}
@@ -137,7 +149,7 @@ export function UpdateNotices(): ReactNode {
if (!active) return null;
if (active.combinedSubscribe && active.whatsNew) {
return (
- <div data-testid="update-notices-list">
+ <div data-testid="update-notices-list" className="shrink-0">
<SubscribeCard
version={active.whatsNew.version}
onOpenReleaseNotes={() => active.action?.onClick()}
@@ -147,7 +159,7 @@ export function UpdateNotices(): ReactNode {
);
}
return (
- <div data-testid="update-notices-list">
+ <div data-testid="update-notices-list" className="shrink-0">
<NoticeCard
notice={active}
onDismiss={() => {
diff --git a/packages/app/src/components/ViewerStatusPane.tsx b/packages/app/src/components/ViewerStatusPane.tsx
index 59d30c1e4..9739ff15a 100644
--- a/packages/app/src/components/ViewerStatusPane.tsx
+++ b/packages/app/src/components/ViewerStatusPane.tsx
@@ -11,7 +11,7 @@ interface ViewerStatusPaneBaseProps {
export function ViewerLoadingPane({ fileName, dataAttr, extraAttrs }: ViewerStatusPaneBaseProps) {
return (
- <main
+ <section
className="flex h-full min-h-0 flex-col items-center justify-center bg-background text-muted-foreground text-sm"
aria-label={fileName}
{...{ [dataAttr]: '', [`${dataAttr}-state`]: 'loading' }}
@@ -20,7 +20,7 @@ export function ViewerLoadingPane({ fileName, dataAttr, extraAttrs }: ViewerStat
<span>
<Trans>Loading {fileName}</Trans>
</span>
- </main>
+ </section>
);
}
@@ -35,7 +35,7 @@ export function ViewerErrorPane({
openFile?: ViewerOpenFileTarget;
}) {
return (
- <main
+ <section
className="flex h-full min-h-0 flex-col items-center justify-center gap-2 bg-background p-4 text-center"
aria-label={fileName}
{...{ [dataAttr]: '', [`${dataAttr}-state`]: 'error' }}
@@ -64,6 +64,6 @@ export function ViewerErrorPane({
<Trans>Open file</Trans>
</Button>
) : null}
- </main>
+ </section>
);
}
diff --git a/packages/app/src/components/WebProjectName.dom.test.tsx b/packages/app/src/components/WebProjectName.dom.test.tsx
new file mode 100644
index 000000000..1ff7c921b
--- /dev/null
+++ b/packages/app/src/components/WebProjectName.dom.test.tsx
@@ -0,0 +1,78 @@
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+
+let workspace: { contentDir: string; pathSeparator: '/' | '\\' } | null = null;
+
+vi.mock('@/lib/use-workspace', () => ({ useWorkspace: () => workspace }));
+
+vi.mock('@lingui/react/macro', () => ({
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+const { WebProjectName } = await import('./WebProjectName');
+
+afterEach(() => {
+ cleanup();
+ workspace = null;
+});
+
+describe('WebProjectName', () => {
+ test.each([
+ { shape: 'a posix path', contentDir: '/Users/sarah/notes/field-notes', name: 'field-notes' },
+ {
+ shape: 'a windows path',
+ contentDir: 'C:\\Users\\ok\\Documents\\header-check',
+ name: 'header-check',
+ },
+ {
+ shape: 'a trailing separator',
+ contentDir: '/Users/sarah/notes/field-notes/',
+ name: 'field-notes',
+ },
+ ])('names the project from $shape', ({ contentDir, name }) => {
+ workspace = { contentDir, pathSeparator: '/' };
+ render(<WebProjectName />, { wrapper: TooltipProvider });
+
+ expect(screen.getByTestId('web-project-name-label').textContent).toBe(name);
+ });
+
+ test('says what the name is for', () => {
+ workspace = { contentDir: '/Users/sarah/notes/field-notes', pathSeparator: '/' };
+ render(<WebProjectName />, { wrapper: TooltipProvider });
+
+ expect(screen.getByTestId('web-project-name').textContent).toContain('Project');
+ });
+
+ test('a keyboard user can reach the full content directory a truncated name otherwise loses', async () => {
+ workspace = { contentDir: '/Users/sarah/notes/field-notes', pathSeparator: '/' };
+ render(<WebProjectName />, { wrapper: TooltipProvider });
+
+ const label = screen.getByTestId('web-project-name');
+ expect(label.getAttribute('tabindex')).toBe('0');
+
+ await userEvent.tab();
+ expect(document.activeElement).toBe(label);
+ await waitFor(() =>
+ expect(screen.getAllByText('/Users/sarah/notes/field-notes').length).toBeGreaterThan(0),
+ );
+ });
+
+ test('renders nothing until the workspace is known', () => {
+ workspace = null;
+ render(<WebProjectName />, { wrapper: TooltipProvider });
+
+ expect(screen.queryByTestId('web-project-name')).toBeNull();
+ });
+
+ test('renders nothing for a filesystem root, which yields no name', () => {
+ workspace = { contentDir: '/', pathSeparator: '/' };
+ render(<WebProjectName />, { wrapper: TooltipProvider });
+
+ expect(screen.queryByTestId('web-project-name')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/WebProjectName.tsx b/packages/app/src/components/WebProjectName.tsx
new file mode 100644
index 000000000..1831a0ecd
--- /dev/null
+++ b/packages/app/src/components/WebProjectName.tsx
@@ -0,0 +1,37 @@
+import { useLingui } from '@lingui/react/macro';
+import { Folder } from 'lucide-react';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { extractFolderBasename } from '@/lib/path-utils';
+import { useWorkspace } from '@/lib/use-workspace';
+
+const CENTRE_LABEL_CLASS = 'flex min-w-0 items-center gap-1.5 px-2 text-foreground text-sm';
+
+export function WebProjectName() {
+ const { t } = useLingui();
+ const workspace = useWorkspace();
+ if (workspace === null) return null;
+ const name = extractFolderBasename(workspace.contentDir) || null;
+ if (name === null) return null;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* biome-ignore lint/a11y/noNoninteractiveTabindex: tooltip-on-static-text pattern — focusable span lets keyboard users surface the full project path that mouse users see on hover. */}
+ <span tabIndex={0} data-testid="web-project-name" className={CENTRE_LABEL_CLASS}>
+ <Folder aria-hidden="true" className="size-4 shrink-0" />
+ <span className="sr-only">{t`Project`}</span>
+ <span
+ className="min-w-0 truncate"
+ data-app-header-center-label=""
+ data-testid="web-project-name-label"
+ >
+ {name}
+ </span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="max-w-xs break-all">
+ {workspace.contentDir}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/app/src/components/acp/ThreadHistoryPanel.tsx b/packages/app/src/components/acp/ThreadHistoryPanel.tsx
index f9a55415b..b3d6360da 100644
--- a/packages/app/src/components/acp/ThreadHistoryPanel.tsx
+++ b/packages/app/src/components/acp/ThreadHistoryPanel.tsx
@@ -24,6 +24,7 @@ import {
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group';
+import { SECONDARY_PANEL_SURFACE_CLASS } from '@/components/ui/pane-card';
import {
SidebarContent,
SidebarFooter,
@@ -367,7 +368,10 @@ export function ThreadHistoryPanel({
<aside
id={panelId}
aria-label={t`Chat history`}
- className="flex h-full min-h-0 w-full flex-col bg-muted/20 text-sidebar-foreground [--sidebar-accent-foreground:var(--foreground)]"
+ className={cn(
+ 'flex h-full min-h-0 w-full flex-col text-sidebar-foreground [--sidebar-accent-foreground:var(--foreground)]',
+ SECONDARY_PANEL_SURFACE_CLASS,
+ )}
data-testid="agent-thread-history-panel"
data-history-mode={mode}
onKeyDown={(event) => {
diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsx
index 7846b3366..eedeb24ea 100644
--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx
+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx
@@ -30,6 +30,7 @@ import type {
ThreadRenderModel,
} from '@/lib/acp/thread-event-model';
import { installPointerPositionTracker } from '@/lib/pointer-position';
+import { consumeWorkspaceHashWrite } from '@/lib/workspace-hash-writes';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
@@ -1324,6 +1325,32 @@ describe('ThreadView permissions', () => {
expect(window.location.hash).toBe('#/notes/today');
});
+ test('follow-the-agent navigation is a hash change the workspace did not write, which the navigation handler treats as a deliberate open', async () => {
+ model = makeModel();
+ window.location.hash = '#/notes/yesterday';
+ const hashChanges: string[] = [];
+ const onHashChange = (event: HashChangeEvent) => hashChanges.push(event.newURL);
+ window.addEventListener('hashchange', onHashChange);
+ const view = () => <ThreadView info={makeInfo({ status: 'awaiting_permission' })} />;
+ const { rerender } = render(view());
+
+ model = makeModel({
+ items: [
+ toolCall({ toolKind: 'edit', rawInput: { docName: 'notes/today' } }),
+ permission({ toolCallId: 'c1' }),
+ ],
+ });
+ threadState = { info: undefined, events: [], lastSeq: 6, replayThroughSeq: 6 };
+ rerender(view());
+ threadState = { info: undefined, events: [], lastSeq: 7, replayThroughSeq: 7 };
+ rerender(view());
+
+ expect(window.location.hash).toBe('#/notes/today');
+ await waitFor(() => expect(hashChanges.at(-1)).toMatch(/#\/notes\/today$/));
+ window.removeEventListener('hashchange', onHashChange);
+ expect(consumeWorkspaceHashWrite(window.location.hash)).toBe(false);
+ });
+
test('stacks three-plus options top-to-bottom with the primary grant emphasized', () => {
model = makeModel({
items: [
@@ -4220,10 +4247,13 @@ describe('ThreadView auth-required dead ends', () => {
await userEvent.click(offerButton());
expect(resumeThread).not.toHaveBeenCalled();
- expect(createThread).toHaveBeenCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: undefined,
- });
+ expect(createThread).toHaveBeenCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: undefined,
+ },
+ undefined,
+ );
});
test('a new chat that lost the race to another launch says so rather than going quiet', async () => {
@@ -4315,10 +4345,13 @@ describe('ThreadView auth-required dead ends', () => {
fireEvent.change(composer, { target: { value: 'draft I have not sent yet' } });
await userEvent.click(offerButton());
- expect(createThread).toHaveBeenCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: undefined,
- });
+ expect(createThread).toHaveBeenCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: undefined,
+ },
+ undefined,
+ );
await waitFor(() => expect(staged.text).toBe('draft I have not sent yet'));
expect(composer.value).toBe('draft I have not sent yet');
});
@@ -4338,10 +4371,13 @@ describe('ThreadView auth-required dead ends', () => {
fireEvent.change(composer, { target: { value: 'half-finished instruction' } });
await userEvent.click(screen.getByTestId('agent-thread-resume-fallback-new'));
- expect(createThread).toHaveBeenCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: undefined,
- });
+ expect(createThread).toHaveBeenCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: undefined,
+ },
+ undefined,
+ );
await waitFor(() => expect(staged.text).toBe('half-finished instruction'));
expect(composer.value).toBe('half-finished instruction');
});
@@ -4362,10 +4398,13 @@ describe('ThreadView auth-required dead ends', () => {
await userEvent.click(screen.getByTestId('agent-thread-resume-fallback-new'));
await waitFor(() => expect(createThread).toHaveBeenCalledTimes(1));
- expect(createThread).toHaveBeenLastCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: 'finish the migration',
- });
+ expect(createThread).toHaveBeenLastCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: 'finish the migration',
+ },
+ undefined,
+ );
expect(staged.text).toBeNull();
});
@@ -4379,10 +4418,13 @@ describe('ThreadView auth-required dead ends', () => {
await userEvent.click(offerButton());
await waitFor(() => expect(createThread).toHaveBeenCalledTimes(1));
- expect(createThread).toHaveBeenLastCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: undefined,
- });
+ expect(createThread).toHaveBeenLastCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: undefined,
+ },
+ undefined,
+ );
await waitFor(() => expect(staged.text).toBe('finish the migration'));
});
@@ -4550,10 +4592,13 @@ describe('ThreadView auth-required dead ends', () => {
await userEvent.click(screen.getByTestId('agent-thread-resume-fallback-new'));
await waitFor(() => expect(createThread).toHaveBeenCalledTimes(1));
- expect(createThread).toHaveBeenCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: undefined,
- });
+ expect(createThread).toHaveBeenCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: undefined,
+ },
+ undefined,
+ );
});
test('a thread the server says it cannot resume leaves no control that still says resume', async () => {
@@ -4565,10 +4610,13 @@ describe('ThreadView auth-required dead ends', () => {
expect(screen.queryByRole('button', { name: 'Resume chat' })).toBeNull();
await userEvent.click(offerButton());
expect(resumeThread).not.toHaveBeenCalled();
- expect(createThread).toHaveBeenCalledWith({
- agent: { source: 'registry', id: 'claude' },
- prompt: undefined,
- });
+ expect(createThread).toHaveBeenCalledWith(
+ {
+ agent: { source: 'registry', id: 'claude' },
+ prompt: undefined,
+ },
+ undefined,
+ );
});
test('one rejection does not retire a resume the server still says is available', async () => {
@@ -6238,6 +6286,7 @@ describe('ThreadView context window', () => {
await waitFor(() =>
expect(createThread).toHaveBeenCalledWith(
expect.objectContaining({ agent: { source: 'registry', id: 'codex-acp' } }),
+ undefined,
),
);
});
diff --git a/packages/app/src/components/checkout-identity.test.ts b/packages/app/src/components/checkout-identity.test.ts
new file mode 100644
index 000000000..956d9e71e
--- /dev/null
+++ b/packages/app/src/components/checkout-identity.test.ts
@@ -0,0 +1,100 @@
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { checkoutIdentity } from './checkout-identity';
+
+function model(currentWorktreePath: string | null): WorktreeSelectorModel {
+ return {
+ mainRoot: '/work/acme-notes',
+ currentBranch: null,
+ remoteBranches: [],
+ entries: [
+ {
+ branch: 'main',
+ worktreePath: '/work/acme-notes',
+ isCurrent: currentWorktreePath === '/work/acme-notes',
+ isMain: true,
+ locked: false,
+ },
+ {
+ branch: 'feat/new-layout',
+ worktreePath: '/work/acme-notes-feature',
+ isCurrent: currentWorktreePath === '/work/acme-notes-feature',
+ isMain: false,
+ locked: false,
+ },
+ {
+ branch: null,
+ worktreePath: '/work/acme-notes-review',
+ isCurrent: currentWorktreePath === '/work/acme-notes-review',
+ isMain: false,
+ locked: false,
+ },
+ ],
+ };
+}
+
+describe('checkoutIdentity', () => {
+ test('a nested project in a worktree on a branch names the repository, then the project folder and branch', () => {
+ expect(
+ checkoutIdentity({
+ projectName: 'docs',
+ branch: 'feat/new-layout',
+ worktreeModel: model('/work/acme-notes-feature'),
+ }),
+ ).toEqual({ repositoryName: 'acme-notes', checkoutDetail: 'docs · feat/new-layout' });
+ });
+
+ test('a nested project in a worktree with no branch falls back to the worktree folder name', () => {
+ expect(
+ checkoutIdentity({
+ projectName: 'docs',
+ branch: null,
+ worktreeModel: model('/work/acme-notes-review'),
+ }),
+ ).toEqual({ repositoryName: 'acme-notes', checkoutDetail: 'docs · acme-notes-review' });
+ });
+
+ test('a project at the root of the original clone leaves the matching project folder name out', () => {
+ expect(
+ checkoutIdentity({
+ projectName: 'acme-notes',
+ branch: 'main',
+ worktreeModel: model('/work/acme-notes'),
+ }),
+ ).toEqual({ repositoryName: 'acme-notes', checkoutDetail: 'main' });
+ });
+
+ test('a project at the root of a worktree names the worktree folder as the project folder', () => {
+ expect(
+ checkoutIdentity({
+ projectName: 'acme-notes-feature',
+ branch: 'feat/new-layout',
+ worktreeModel: model('/work/acme-notes-feature'),
+ }),
+ ).toEqual({
+ repositoryName: 'acme-notes',
+ checkoutDetail: 'acme-notes-feature · feat/new-layout',
+ });
+ });
+
+ test('before the worktree inventory loads, the project name stands in for the repository name', () => {
+ expect(checkoutIdentity({ projectName: 'docs', branch: 'main', worktreeModel: null })).toEqual({
+ repositoryName: 'docs',
+ checkoutDetail: 'main',
+ });
+ });
+
+ test('with no desktop project and no worktree inventory, only the branch remains', () => {
+ expect(checkoutIdentity({ projectName: null, branch: 'main', worktreeModel: null })).toEqual({
+ repositoryName: null,
+ checkoutDetail: 'main',
+ });
+ });
+
+ test('with nothing to report, the detail is null rather than an empty string', () => {
+ expect(checkoutIdentity({ projectName: null, branch: null, worktreeModel: null })).toEqual({
+ repositoryName: null,
+ checkoutDetail: null,
+ });
+ });
+});
diff --git a/packages/app/src/components/checkout-identity.ts b/packages/app/src/components/checkout-identity.ts
new file mode 100644
index 000000000..a149e4221
--- /dev/null
+++ b/packages/app/src/components/checkout-identity.ts
@@ -0,0 +1,30 @@
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core/git/worktree-selector-model';
+import { basenameOf } from './project-switcher-recents';
+
+export interface CheckoutIdentity {
+ readonly repositoryName: string | null;
+ readonly checkoutDetail: string | null;
+}
+
+export interface CheckoutIdentityInput {
+ readonly projectName: string | null;
+ readonly branch: string | null;
+ readonly worktreeModel: WorktreeSelectorModel | null;
+}
+
+export function checkoutIdentity({
+ projectName,
+ branch,
+ worktreeModel,
+}: CheckoutIdentityInput): CheckoutIdentity {
+ const repositoryName = worktreeModel !== null ? basenameOf(worktreeModel.mainRoot) : projectName;
+ const currentCheckout = worktreeModel?.entries.find((entry) => entry.isCurrent) ?? null;
+ const worktreeName =
+ currentCheckout?.worktreePath !== null && currentCheckout?.worktreePath !== undefined
+ ? basenameOf(currentCheckout.worktreePath)
+ : null;
+ const checkoutName = branch ?? worktreeName;
+ const projectScopeName = projectName === repositoryName ? null : projectName;
+ const parts = [projectScopeName, checkoutName].filter((part): part is string => part !== null);
+ return { repositoryName, checkoutDetail: parts.length > 0 ? parts.join(' · ') : null };
+}
diff --git a/packages/app/src/components/command-palette-commands.ts b/packages/app/src/components/command-palette-commands.ts
index 73d812860..da7897bc5 100644
--- a/packages/app/src/components/command-palette-commands.ts
+++ b/packages/app/src/components/command-palette-commands.ts
@@ -53,6 +53,7 @@ import { requestDocPanelTab } from '@/components/doc-panel-events';
import { DiscordIcon } from '@/components/icons/discord';
import { GithubIcon } from '@/components/icons/github';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
+import { PANE_ICON } from '@/components/pane-icons';
import { requestSkillsDockExpanded } from '@/components/skills-dock-expanded-store';
import type { OkDesktopBridge, OkMenuAction } from '@/lib/desktop-bridge-types';
import { i18n } from '@/lib/i18n';
@@ -155,6 +156,8 @@ const PALETTE_COMMAND_LABELS = {
sidebarHide: msg`Hide sidebar`,
docPanelShow: msg`Show document panel`,
docPanelHide: msg`Hide document panel`,
+ editorShow: msg`Show Editor`,
+ editorHide: msg`Hide Editor`,
terminalShow: msg`Show Terminal`,
terminalHide: msg`Hide Terminal`,
terminalMoveRight: msg`Move Terminal to right`,
@@ -240,9 +243,10 @@ const COMMAND_ICONS: Record<string, ComponentType<{ className?: string }>> = {
'switch-worktree': GitBranch,
'toggle-sidebar': PanelLeft,
'toggle-doc-panel': PanelRight,
- 'toggle-terminal': SquareTerminal,
+ 'toggle-terminal': PANE_ICON.terminal,
'move-terminal': SquareTerminal,
- 'toggle-agent-panel': MessageSquare,
+ 'toggle-agent-panel': PANE_ICON.agents,
+ 'toggle-editor': PANE_ICON.editor,
'toggle-show-hidden-files': Eye,
'toggle-show-ok-folders': Folder,
'toggle-show-only-markdown-files': FileText,
@@ -375,7 +379,8 @@ function resolvePaletteLabel(cmd: CommandIdentity, ctx: PaletteCommandContext):
) {
return i18n._(PALETTE_COMMAND_LABELS[overrideKey as PaletteLabelKey]);
}
- const visible = ctx.viewMenuState[cmd.stateToggle.stateField] === true;
+ const visible =
+ (ctx.viewMenuState[cmd.stateToggle.stateField] ?? cmd.stateToggle.defaultVisible) === true;
const key = visible ? cmd.stateToggle.hideKey : cmd.stateToggle.showKey;
return i18n._(paletteLabelDescriptor(key as PaletteLabelKey, platform));
}
diff --git a/packages/app/src/components/doc-panel-visibility.ts b/packages/app/src/components/doc-panel-visibility.ts
new file mode 100644
index 000000000..602d68297
--- /dev/null
+++ b/packages/app/src/components/doc-panel-visibility.ts
@@ -0,0 +1,9 @@
+let onScreen = false;
+
+export function setDocPanelOnScreen(next: boolean): void {
+ onScreen = next;
+}
+
+export function isDocPanelOnScreen(): boolean {
+ return onScreen;
+}
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
new file mode 100644
index 000000000..28c5859ff
--- /dev/null
+++ b/packages/app/src/components/editor-area-hidden-editor.dom.test.tsx
@@ -0,0 +1,184 @@
+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
new file mode 100644
index 000000000..508c71f66
--- /dev/null
+++ b/packages/app/src/components/editor-area-hidden-editor.test.ts
@@ -0,0 +1,165 @@
+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
new file mode 100644
index 000000000..b581bff72
--- /dev/null
+++ b/packages/app/src/components/editor-area-hidden-editor.ts
@@ -0,0 +1,56 @@
+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
new file mode 100644
index 000000000..16223a5ca
--- /dev/null
+++ b/packages/app/src/components/editor-area-inner-follow.test.ts
@@ -0,0 +1,90 @@
+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
new file mode 100644
index 000000000..e571a6380
--- /dev/null
+++ b/packages/app/src/components/editor-area-inner-follow.ts
@@ -0,0 +1,38 @@
+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 e736fe9bc..e0208be11 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
@@ -6,6 +6,8 @@ import {
describeRailFloorShortfall,
describeRailWidthShortfall,
findRailPanelGroup,
+ reportUnexpectedPanelGroupFailure,
+ resolveInnerRowChromePx,
resolveRailPanelSpace,
resolveRailPanelSpacePx,
} from './editor-area-panel-space';
@@ -85,6 +87,47 @@ afterEach(() => {
document.body.replaceChildren();
});
+describe('a panel library failure is reported only when it is not the library still registering', () => {
+ function warningsFor(error: unknown, context?: Record<string, unknown>): unknown[] {
+ const warnings: unknown[] = [];
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {
+ warnings.push(JSON.parse(String(message)));
+ });
+ reportUnexpectedPanelGroupFailure('panel-resize-failed', error, context);
+ warnSpy.mockRestore();
+ return warnings;
+ }
+
+ 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',
+ ])('%s is expected and stays quiet', (message) => {
+ expect(warningsFor(new Error(message))).toEqual([]);
+ });
+
+ test.each<[string, unknown, string]>([
+ ['an unrelated error', new Error('size out of range'), 'size out of range'],
+ ['a message that only mentions not found', new Error('Panel not found'), 'Panel not found'],
+ ['a thrown non-Error', 'layout exploded', 'layout exploded'],
+ ])('%s is reported with its event and message', (_label, error, message) => {
+ expect(warningsFor(error)).toEqual([{ event: 'panel-resize-failed', error: message }]);
+ });
+
+ test('context adds fields but never replaces the event or the error', () => {
+ expect(
+ warningsFor(new Error('size out of range'), {
+ event: 'renamed',
+ error: 'masked',
+ decision: 'sync-rail-columns',
+ }),
+ ).toEqual([
+ { event: 'panel-resize-failed', error: 'size out of range', decision: 'sync-rail-columns' },
+ ]);
+ });
+});
+
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([
@@ -523,3 +566,52 @@ 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 c68b5157a..d804710fb 100644
--- a/packages/app/src/components/editor-area-panel-space.ts
+++ b/packages/app/src/components/editor-area-panel-space.ts
@@ -1,5 +1,23 @@
const GROUP_SELECTOR = ':scope > [data-group]';
const PANEL_SELECTOR = ':scope > [data-panel]';
+const PANEL_GROUP_UNAVAILABLE_MESSAGE =
+ /^(?:Could not find Group with id "|Group .+ not found$|Layout not found for Panel |Panel constraints not found for Panel )/;
+
+export function reportUnexpectedPanelGroupFailure(
+ event: string,
+ error: unknown,
+ context?: Readonly<Record<string, unknown>>,
+) {
+ if (error instanceof Error && PANEL_GROUP_UNAVAILABLE_MESSAGE.test(error.message)) return;
+ const { event: _shadowedEvent, error: _shadowedError, ...fields } = context ?? {};
+ console.warn(
+ JSON.stringify({
+ event,
+ error: error instanceof Error ? error.message : String(error),
+ ...fields,
+ }),
+ );
+}
export function findRailPanelGroup(container: Element | null | undefined): HTMLElement | null {
const group = container?.querySelector(GROUP_SELECTOR);
@@ -64,6 +82,21 @@ export function resolveRailPanelSpacePx(container: Element | null | undefined):
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;
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
new file mode 100644
index 000000000..d289c0a71
--- /dev/null
+++ b/packages/app/src/components/editor-card-rows-preserve-side-panel.dom.test.tsx
@@ -0,0 +1,240 @@
+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/handoff/preferred-session-events.test.ts b/packages/app/src/components/handoff/preferred-session-events.test.ts
index ae2f83884..922c8f2c8 100644
--- a/packages/app/src/components/handoff/preferred-session-events.test.ts
+++ b/packages/app/src/components/handoff/preferred-session-events.test.ts
@@ -5,6 +5,46 @@ import {
} from './preferred-session-events';
describe('preferred-session-events', () => {
+ test('reports an unclaimed request when no session host is subscribed', () => {
+ const target = new EventTarget();
+
+ expect(requestPreferredSession(target)).toBe(false);
+ });
+
+ test('reports one matching host claim for a live request', () => {
+ const target = new EventTarget();
+ let launches = 0;
+ const unsubscribe = subscribeToPreferredSessionRequests(() => {
+ launches += 1;
+ }, target);
+
+ expect(requestPreferredSession(target)).toBe(true);
+ expect(launches).toBe(1);
+ unsubscribe();
+ });
+
+ test('a nonmatching host declines and only the first matching host launches', () => {
+ const target = new EventTarget();
+ const launches: string[] = [];
+ const subscribe = (host: string, matches: boolean) =>
+ Reflect.apply(subscribeToPreferredSessionRequests, undefined, [
+ () => launches.push(host),
+ target,
+ () => matches,
+ ]) as () => void;
+ const stopWrong = subscribe('wrong', false);
+ const stopMatching = subscribe('matching', true);
+ const stopSecond = subscribe('second', true);
+
+ const claimed = requestPreferredSession(target);
+
+ expect(launches).toEqual(['matching']);
+ expect(claimed).toBe(true);
+ stopWrong();
+ stopMatching();
+ stopSecond();
+ });
+
test('delivers a request to the subscriber and stops after unsubscribe', () => {
const target = new EventTarget();
let received = 0;
diff --git a/packages/app/src/components/handoff/preferred-session-events.ts b/packages/app/src/components/handoff/preferred-session-events.ts
index e9e484b6b..9f54c12d9 100644
--- a/packages/app/src/components/handoff/preferred-session-events.ts
+++ b/packages/app/src/components/handoff/preferred-session-events.ts
@@ -4,8 +4,8 @@ export function requestPreferredSession(
target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'
? new EventTarget()
: window,
-): void {
- target.dispatchEvent(new CustomEvent(PREFERRED_SESSION_EVENT));
+): boolean {
+ return !target.dispatchEvent(new CustomEvent(PREFERRED_SESSION_EVENT, { cancelable: true }));
}
export function subscribeToPreferredSessionRequests(
@@ -14,8 +14,13 @@ export function subscribeToPreferredSessionRequests(
'undefined'
? new EventTarget()
: window,
+ matches: () => boolean = () => true,
): () => void {
- const listener = () => onRequest();
+ const listener = (event: Event) => {
+ if (event.defaultPrevented || !matches()) return;
+ event.preventDefault();
+ onRequest();
+ };
target.addEventListener(PREFERRED_SESSION_EVENT, listener);
return () => target.removeEventListener(PREFERRED_SESSION_EVENT, listener);
}
diff --git a/packages/app/src/components/icons/claude.tsx b/packages/app/src/components/icons/claude.tsx
index 942258ba2..d53122c55 100644
--- a/packages/app/src/components/icons/claude.tsx
+++ b/packages/app/src/components/icons/claude.tsx
@@ -13,17 +13,10 @@ export function ClaudeIcon(props: SVGProps<SVGSVGElement>) {
{...props}
>
<title>Claude icon</title>
- <g clipPath="url(#clip0_claude)">
- <path
- d="M4.704 15.96L9.432 13.32L9.504 13.08L9.432 12.96H9.192L8.4 12.912L5.712 12.84L3.36 12.72L1.08 12.6L0.504 12.48L0 11.76L0.048 11.4L0.528 11.088L1.224 11.136L2.736 11.256L5.016 11.4L6.672 11.496L9.12 11.784H9.504L9.552 11.616L9.432 11.52L9.336 11.424L6.96 9.84L4.416 8.16L3.072 7.176L2.352 6.696L1.992 6.216L1.848 5.208L2.496 4.488L3.384 4.56L3.6 4.608L4.488 5.304L6.408 6.768L8.88 8.64L9.24 8.928L9.384 8.832L9.408 8.76L9.24 8.496L7.92 6L6.48 3.504L5.832 2.472L5.664 1.848C5.592 1.608 5.568 1.368 5.568 1.128L6.288 0.12L6.72 0L7.728 0.144L8.112 0.48L8.736 1.92L9.72 4.152L11.28 7.176L11.76 8.088L12 8.904L12.072 9.144H12.24V9.024L12.36 7.296L12.6 5.208L12.84 2.52L12.912 1.752L13.296 0.84L14.016 0.36L14.64 0.624L15.12 1.32L15.048 1.752L14.784 3.6L14.16 6.504L13.8 8.472H14.016L14.256 8.208L15.24 6.912L16.896 4.848L17.616 4.008L18.48 3.12L19.032 2.688H20.064L20.808 3.816L20.472 4.992L19.416 6.336L18.528 7.464L17.256 9.168L16.488 10.536L16.56 10.632H16.728L19.608 10.008L21.144 9.744L22.968 9.432L23.808 9.816L23.904 10.2L23.568 11.016L21.6 11.496L19.296 11.976L15.864 12.768L15.816 12.792L15.864 12.864L17.4 13.008L18.072 13.056H19.704L22.728 13.296L23.52 13.776L23.976 14.424L23.904 14.904L22.68 15.528L21.048 15.144L17.208 14.232L15.912 13.92H15.72V14.016L16.824 15.096L18.816 16.896L21.36 19.224L21.48 19.8L21.168 20.28L20.832 20.232L18.624 18.552L17.76 17.832L15.84 16.2H15.72V16.368L16.152 17.016L18.504 20.544L18.624 21.624L18.456 21.96L17.832 22.2L17.184 22.056L15.792 20.136L14.352 17.976L13.224 16.008L13.104 16.104L12.408 23.352L12.096 23.712L11.376 24L10.776 23.52L10.44 22.8L10.776 21.312L11.16 19.392L11.472 17.856L11.76 15.96L11.928 15.336V15.288H11.76L10.32 17.28L8.16 20.232L6.432 22.056L6.024 22.224L5.304 21.864L5.376 21.192L5.76 20.64L8.16 17.568L9.6 15.672L10.56 14.568L10.536 14.448H10.464L4.128 18.576L3 18.72L2.52 18.24L2.568 17.52L2.808 17.28L4.728 15.96H4.704Z"
- fill="currentColor"
- />
- </g>
- <defs>
- <clipPath id="clip0_claude">
- <rect width="24" height="24" fill="white" />
- </clipPath>
- </defs>
+ <path
+ d="M4.704 15.96L9.432 13.32L9.504 13.08L9.432 12.96H9.192L8.4 12.912L5.712 12.84L3.36 12.72L1.08 12.6L0.504 12.48L0 11.76L0.048 11.4L0.528 11.088L1.224 11.136L2.736 11.256L5.016 11.4L6.672 11.496L9.12 11.784H9.504L9.552 11.616L9.432 11.52L9.336 11.424L6.96 9.84L4.416 8.16L3.072 7.176L2.352 6.696L1.992 6.216L1.848 5.208L2.496 4.488L3.384 4.56L3.6 4.608L4.488 5.304L6.408 6.768L8.88 8.64L9.24 8.928L9.384 8.832L9.408 8.76L9.24 8.496L7.92 6L6.48 3.504L5.832 2.472L5.664 1.848C5.592 1.608 5.568 1.368 5.568 1.128L6.288 0.12L6.72 0L7.728 0.144L8.112 0.48L8.736 1.92L9.72 4.152L11.28 7.176L11.76 8.088L12 8.904L12.072 9.144H12.24V9.024L12.36 7.296L12.6 5.208L12.84 2.52L12.912 1.752L13.296 0.84L14.016 0.36L14.64 0.624L15.12 1.32L15.048 1.752L14.784 3.6L14.16 6.504L13.8 8.472H14.016L14.256 8.208L15.24 6.912L16.896 4.848L17.616 4.008L18.48 3.12L19.032 2.688H20.064L20.808 3.816L20.472 4.992L19.416 6.336L18.528 7.464L17.256 9.168L16.488 10.536L16.56 10.632H16.728L19.608 10.008L21.144 9.744L22.968 9.432L23.808 9.816L23.904 10.2L23.568 11.016L21.6 11.496L19.296 11.976L15.864 12.768L15.816 12.792L15.864 12.864L17.4 13.008L18.072 13.056H19.704L22.728 13.296L23.52 13.776L23.976 14.424L23.904 14.904L22.68 15.528L21.048 15.144L17.208 14.232L15.912 13.92H15.72V14.016L16.824 15.096L18.816 16.896L21.36 19.224L21.48 19.8L21.168 20.28L20.832 20.232L18.624 18.552L17.76 17.832L15.84 16.2H15.72V16.368L16.152 17.016L18.504 20.544L18.624 21.624L18.456 21.96L17.832 22.2L17.184 22.056L15.792 20.136L14.352 17.976L13.224 16.008L13.104 16.104L12.408 23.352L12.096 23.712L11.376 24L10.776 23.52L10.44 22.8L10.776 21.312L11.16 19.392L11.472 17.856L11.76 15.96L11.928 15.336V15.288H11.76L10.32 17.28L8.16 20.232L6.432 22.056L6.024 22.224L5.304 21.864L5.376 21.192L5.76 20.64L8.16 17.568L9.6 15.672L10.56 14.568L10.536 14.448H10.464L4.128 18.576L3 18.72L2.52 18.24L2.568 17.52L2.808 17.28L4.728 15.96H4.704Z"
+ fill="currentColor"
+ />
</svg>
);
}
diff --git a/packages/app/src/components/icons/editor-pane.tsx b/packages/app/src/components/icons/editor-pane.tsx
new file mode 100644
index 000000000..27978bc46
--- /dev/null
+++ b/packages/app/src/components/icons/editor-pane.tsx
@@ -0,0 +1,45 @@
+import type { SVGProps } from 'react';
+
+export function EditorPaneIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ width={24}
+ height={24}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.7}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ xmlns="http://www.w3.org/2000/svg"
+ aria-hidden="true"
+ {...props}
+ >
+ <rect x="3" y="4" width="18" height="16" rx="2" />
+ <path d="M9 4v16" />
+ <path d="M12.5 9.5h5M12.5 13h3.2" />
+ </svg>
+ );
+}
+
+export function PaneLayoutIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ width={24}
+ height={24}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ xmlns="http://www.w3.org/2000/svg"
+ aria-hidden="true"
+ {...props}
+ >
+ <rect x="3" y="4.5" width="8" height="15" rx="1.6" />
+ <rect x="13" y="4.5" width="8" height="7" rx="1.6" />
+ <rect x="13" y="13.5" width="8" height="6" rx="1.6" />
+ </svg>
+ );
+}
diff --git a/packages/app/src/components/icons/icon-ids.dom.test.tsx b/packages/app/src/components/icons/icon-ids.dom.test.tsx
new file mode 100644
index 000000000..8a1a6a848
--- /dev/null
+++ b/packages/app/src/components/icons/icon-ids.dom.test.tsx
@@ -0,0 +1,46 @@
+import { render } from '@testing-library/react';
+import type { ComponentType, SVGProps } from 'react';
+import { describe, expect, test } from 'vitest';
+import { ClaudeIcon } from './claude';
+import { CodexBrandIcon } from './codex';
+import { OkIcon } from './ok';
+import { OpenClawIcon } from './openclaw';
+
+function idReferences(root: ParentNode): Array<{ element: Element; id: string }> {
+ const found: Array<{ element: Element; id: string }> = [];
+ for (const element of root.querySelectorAll('*')) {
+ for (const attribute of element.getAttributeNames()) {
+ const match = /url\(#([^)]+)\)/.exec(element.getAttribute(attribute) ?? '');
+ if (match?.[1]) found.push({ element, id: match[1] });
+ }
+ }
+ return found;
+}
+
+describe.each<[string, ComponentType<SVGProps<SVGSVGElement>>]>([
+ ['ClaudeIcon', ClaudeIcon],
+ ['OpenClawIcon', OpenClawIcon],
+ ['CodexBrandIcon', CodexBrandIcon],
+ ['OkIcon', OkIcon],
+])('%s on a page with two copies', (_name, Icon) => {
+ test('every id is unique and every id reference resolves inside its own svg', () => {
+ const { container } = render(
+ <>
+ <Icon />
+ <Icon />
+ </>,
+ );
+ const ids = [...container.querySelectorAll('[id]')].map((element) => element.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const { element, id } of idReferences(container)) {
+ const owner = element.closest('svg');
+ expect(owner?.querySelector(`[id="${id}"]`), `${id} resolves inside its svg`).not.toBeNull();
+ }
+ });
+});
+
+test('ClaudeIcon carries no ids and no id references at all', () => {
+ const { container } = render(<ClaudeIcon />);
+ expect(container.querySelectorAll('[id]')).toHaveLength(0);
+ expect(idReferences(container)).toHaveLength(0);
+});
diff --git a/packages/app/src/components/icons/ok.tsx b/packages/app/src/components/icons/ok.tsx
index b2e08b474..d6d30802a 100644
--- a/packages/app/src/components/icons/ok.tsx
+++ b/packages/app/src/components/icons/ok.tsx
@@ -1,6 +1,7 @@
-import type { SVGProps } from 'react';
+import { type SVGProps, useId } from 'react';
export function OkIcon(props: SVGProps<SVGSVGElement>) {
+ const filterId = `ok-shadow-${useId().replace(/:/g, '')}`;
return (
<svg
role="img"
@@ -13,7 +14,7 @@ export function OkIcon(props: SVGProps<SVGSVGElement>) {
{...props}
>
<title>OpenKnowledge icon</title>
- <g filter="url(#filter0_d_ok)">
+ <g filter={`url(#${filterId})`}>
<path
d="M66.8902 16.1017C58.2694 3.86669 46.1739 -0.690239 29.9182 2.17749C21.3995 3.67813 13.4602 9.555 8.67934 17.9009C3.93974 26.1701 2.98514 35.6533 6.05714 43.9166C9.31574 52.6868 16.7168 58.4752 24.2299 63.4231C25.7973 64.4562 26.1351 65.7172 26.3551 68.9896C26.5221 71.4625 26.799 75.6011 30.6842 77.7204C31.8176 78.3372 33.0648 78.6515 34.3946 78.6515C37.0796 78.6515 39.4033 77.3649 40.5189 76.7482C47.1049 73.1046 68.8878 59.7147 72.6453 40.4027C74.3444 31.6679 70.9797 21.9019 66.8922 16.1017H66.8902Z"
fill="white"
@@ -33,7 +34,7 @@ export function OkIcon(props: SVGProps<SVGSVGElement>) {
</g>
<defs>
<filter
- id="filter0_d_ok"
+ id={filterId}
x="-9.53674e-07"
y="-0.0799994"
width="77.3817"
diff --git a/packages/app/src/components/icons/openclaw.tsx b/packages/app/src/components/icons/openclaw.tsx
index 27690449c..22e9b6f5a 100644
--- a/packages/app/src/components/icons/openclaw.tsx
+++ b/packages/app/src/components/icons/openclaw.tsx
@@ -1,6 +1,7 @@
-import type { SVGProps } from 'react';
+import { type SVGProps, useId } from 'react';
export function OpenClawIcon(props: SVGProps<SVGSVGElement>) {
+ const maskId = `openclaw-eyes-${useId().replace(/:/g, '')}`;
return (
<svg
role="img"
@@ -13,12 +14,12 @@ export function OpenClawIcon(props: SVGProps<SVGSVGElement>) {
{...props}
>
<title>OpenClaw icon</title>
- <mask id="openclaw-eyes" maskUnits="userSpaceOnUse" x={0} y={0} width={120} height={120}>
+ <mask id={maskId} maskUnits="userSpaceOnUse" x={0} y={0} width={120} height={120}>
<rect width={120} height={120} fill="white" />
<circle cx={45} cy={35} r={6} fill="black" />
<circle cx={75} cy={35} r={6} fill="black" />
</mask>
- <g fill="currentColor" mask="url(#openclaw-eyes)">
+ <g fill="currentColor" mask={`url(#${maskId})`}>
{}
<path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" />
{}
diff --git a/packages/app/src/components/pane-icons.ts b/packages/app/src/components/pane-icons.ts
new file mode 100644
index 000000000..40b3481a2
--- /dev/null
+++ b/packages/app/src/components/pane-icons.ts
@@ -0,0 +1,10 @@
+import { Sparkles, SquareTerminal } from 'lucide-react';
+import type { ComponentType, SVGProps } from 'react';
+import { EditorPaneIcon } from '@/components/icons/editor-pane';
+import type { PaneId } from '@/lib/pane-visibility-store';
+
+export const PANE_ICON = {
+ editor: EditorPaneIcon,
+ agents: Sparkles,
+ terminal: SquareTerminal,
+} as const satisfies Record<PaneId, ComponentType<SVGProps<SVGSVGElement>>>;
diff --git a/packages/app/src/components/right-rail-admission.ts b/packages/app/src/components/right-rail-admission.ts
index 63b4aeb16..b54a48291 100644
--- a/packages/app/src/components/right-rail-admission.ts
+++ b/packages/app/src/components/right-rail-admission.ts
@@ -14,6 +14,7 @@ interface RightRailVisibility {
interface RightRailAdmissionInput {
readonly workspaceWidthPx: number;
readonly otherRailWidthPx: number;
+ readonly editorMinimumWidthPx?: number;
readonly agentsMinimumWidthPx: number;
readonly previous: RightRailVisibility;
readonly current: RightRailVisibility;
@@ -27,18 +28,24 @@ export type RightRailAdmissionDecision =
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.ceil(peerWidthPx / (1 - EDITOR_RESIDUAL_FRACTION));
+ return Math.max(
+ Math.ceil(peerWidthPx / (1 - EDITOR_RESIDUAL_FRACTION)),
+ peerWidthPx + editorMinimumWidthPx,
+ );
}
export function resolveRightRailAdmission({
workspaceWidthPx,
otherRailWidthPx,
+ editorMinimumWidthPx,
agentsMinimumWidthPx,
previous,
current,
@@ -48,6 +55,7 @@ export function resolveRightRailAdmission({
const minimumWidthPx = minimumWorkspaceWidthForRightRailPeers({
otherRailWidthPx,
+ editorMinimumWidthPx,
agentsMinimumWidthPx,
});
if (workspaceWidthPx >= minimumWidthPx) return { kind: 'none' };
diff --git a/packages/app/src/components/skills-dock-expanded-store.test.ts b/packages/app/src/components/skills-dock-expanded-store.test.ts
index f7073cdc7..33621525f 100644
--- a/packages/app/src/components/skills-dock-expanded-store.test.ts
+++ b/packages/app/src/components/skills-dock-expanded-store.test.ts
@@ -1,4 +1,9 @@
import { afterEach, expect, test } from 'vitest';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import {
__resetSkillsDockExpandedForTests,
readSkillsDockExpanded,
@@ -9,6 +14,7 @@ import {
afterEach(() => {
__resetSkillsDockExpandedForTests();
+ __resetPaneVisibilityStoreForTests();
});
test('ships collapsed when nothing was ever stored', () => {
@@ -34,3 +40,12 @@ test('notifies subscribers so an outside reveal reaches the mounted dock', () =>
writeSkillsDockExpanded(false);
expect(seen).toEqual([true]);
});
+
+test('asking for the dock also asks a hidden editor to show, since the dock lives in it', () => {
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+
+ requestSkillsDockExpanded();
+
+ expect(requests).toEqual([{ pane: 'editor', open: true }]);
+});
diff --git a/packages/app/src/components/skills-dock-expanded-store.ts b/packages/app/src/components/skills-dock-expanded-store.ts
index c7117a8ec..16c9503d5 100644
--- a/packages/app/src/components/skills-dock-expanded-store.ts
+++ b/packages/app/src/components/skills-dock-expanded-store.ts
@@ -1,3 +1,5 @@
+import { revealEditor } from '@/lib/reveal-editor';
+
const STORAGE_KEY = 'ok-skills-dock-expanded-v1';
function storage(): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null {
@@ -35,6 +37,7 @@ export function subscribeSkillsDockExpanded(listener: (expanded: boolean) => voi
}
export function requestSkillsDockExpanded(): void {
+ revealEditor();
writeSkillsDockExpanded(true);
}
diff --git a/packages/app/src/components/ui/pane-card.dom.test.tsx b/packages/app/src/components/ui/pane-card.dom.test.tsx
new file mode 100644
index 000000000..127ea1f43
--- /dev/null
+++ b/packages/app/src/components/ui/pane-card.dom.test.tsx
@@ -0,0 +1,190 @@
+import { cleanup, render, screen } from '@testing-library/react';
+import { Component, type ReactNode, Suspense, useEffect } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+import { PANE_CARD_DIVIDER_PX, PANE_CARD_GAP_PX, PANE_CARD_INSET_PX, PaneCard } from './pane-card';
+
+afterEach(cleanup);
+
+function card(container: HTMLElement): HTMLElement {
+ const el = container.querySelector<HTMLElement>('[data-slot="pane-card"]');
+ if (!el) throw new Error('no pane card rendered');
+ return el;
+}
+
+const SHAPE_TOKENS = [
+ 'rounded-xl',
+ 'shadow-[0_2px_8px_0_rgb(0_0_0/0.08),0_1px_2px_-1px_rgb(0_0_0/0.1)]',
+];
+const FILL_TOKENS = [
+ 'relative',
+ 'flex',
+ 'min-h-0',
+ 'min-w-0',
+ 'flex-1',
+ 'flex-col',
+ 'overflow-hidden',
+];
+
+describe('PaneCard', () => {
+ test('the card variant is a plain div carrying today’s shape, clipping and background', () => {
+ const { container } = render(<PaneCard pane="editor">body</PaneCard>);
+ const el = card(container);
+
+ expect(el.tagName).toBe('DIV');
+ expect(screen.queryByRole('region')).toBeNull();
+ expect(el.getAttribute('data-pane')).toBe('editor');
+ expect(el.getAttribute('data-variant')).toBe('card');
+ expectVisualClassTokens(el.getAttribute('class'), [
+ ...FILL_TOKENS,
+ ...SHAPE_TOKENS,
+ 'bg-background',
+ ]);
+ expectVisualClassTokensAbsent(el.getAttribute('class'), ['bg-card', 'ring-1', 'overflow-auto']);
+ });
+
+ test('the flat variant keeps the fill and background but drops the rounding and shadow', () => {
+ const { container } = render(
+ <PaneCard pane="terminal" variant="flat">
+ body
+ </PaneCard>,
+ );
+ const el = card(container);
+
+ expect(el.getAttribute('data-variant')).toBe('flat');
+ expectVisualClassTokens(el.getAttribute('class'), [...FILL_TOKENS, 'bg-background']);
+ expectVisualClassTokensAbsent(el.getAttribute('class'), SHAPE_TOKENS);
+ });
+
+ test.each(['editor', 'agents', 'terminal'] as const)('identifies the %s pane', (pane) => {
+ const { container } = render(<PaneCard pane={pane}>body</PaneCard>);
+ expect(card(container).getAttribute('data-pane')).toBe(pane);
+ });
+
+ test('the card is never a resizable row or panel, so panel-space selectors skip it', () => {
+ const { container } = render(<PaneCard pane="agents">body</PaneCard>);
+ const el = card(container);
+
+ expect(el.hasAttribute('data-panel')).toBe(false);
+ expect(el.hasAttribute('data-group')).toBe(false);
+ expect(el.hasAttribute('data-separator')).toBe(false);
+ });
+
+ test('switching variants restyles the same element and never remounts its children', () => {
+ let mounts = 0;
+ function Child() {
+ useEffect(() => {
+ mounts += 1;
+ }, []);
+ return <div data-testid="child">child</div>;
+ }
+ const view = render(
+ <PaneCard pane="editor" variant="card">
+ <Child />
+ </PaneCard>,
+ );
+ const cardBefore = card(view.container);
+ const childBefore = screen.getByTestId('child');
+
+ view.rerender(
+ <PaneCard pane="editor" variant="flat">
+ <Child />
+ </PaneCard>,
+ );
+
+ expect(card(view.container)).toBe(cardBefore);
+ expect(screen.getByTestId('child')).toBe(childBefore);
+ expect(card(view.container).getAttribute('data-variant')).toBe('flat');
+ expect(mounts).toBe(1);
+ });
+
+ test('caller className and attributes compose onto the same element', () => {
+ const { container } = render(
+ <PaneCard pane="editor" className="mx-1" data-placement="bottom" aria-label="Editor">
+ body
+ </PaneCard>,
+ );
+ const el = card(container);
+
+ expectVisualClassTokens(el.getAttribute('class'), ['mx-1', 'rounded-xl', 'bg-background']);
+ expect(el.getAttribute('data-placement')).toBe('bottom');
+ expect(el.getAttribute('aria-label')).toBe('Editor');
+ });
+
+ test('asChild renders the caller element and keeps the identifying attributes on it', () => {
+ render(
+ <PaneCard pane="agents" asChild>
+ <section aria-label="Agents">body</section>
+ </PaneCard>,
+ );
+ const region = screen.getByRole('region', { name: 'Agents' });
+
+ expect(region.tagName).toBe('SECTION');
+ expect(region.getAttribute('data-slot')).toBe('pane-card');
+ expect(region.getAttribute('data-pane')).toBe('agents');
+ });
+
+ test('a suspending child reaches the boundary outside the card, so the card owns no Suspense', () => {
+ let resolve: (() => void) | null = null;
+ const gate = new Promise<void>((done) => {
+ resolve = done;
+ });
+ function Suspending() {
+ throw gate;
+ }
+ render(
+ <Suspense fallback={<div data-testid="outer-fallback" />}>
+ <PaneCard pane="editor">
+ <Suspending />
+ </PaneCard>
+ </Suspense>,
+ );
+
+ expect(screen.getByTestId('outer-fallback')).toBeTruthy();
+ expect(document.querySelector('[data-slot="pane-card"]')).toBeNull();
+ resolve?.();
+ });
+
+ test('a throwing child reaches the boundary outside the card, so the card owns no error boundary', () => {
+ class OuterBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false };
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+ render() {
+ return this.state.failed ? <div data-testid="outer-error" /> : this.props.children;
+ }
+ }
+ function Throwing(): ReactNode {
+ throw new Error('boom');
+ }
+ const originalError = console.error;
+ console.error = () => {};
+ try {
+ render(
+ <OuterBoundary>
+ <PaneCard pane="editor">
+ <Throwing />
+ </PaneCard>
+ </OuterBoundary>,
+ );
+ } finally {
+ console.error = originalError;
+ }
+
+ expect(screen.getByTestId('outer-error')).toBeTruthy();
+ expect(document.querySelector('[data-slot="pane-card"]')).toBeNull();
+ });
+});
+
+describe('pane card gap accounting', () => {
+ test('the gap between two cards is 8px including a 1px divider', () => {
+ expect(PANE_CARD_GAP_PX).toBe(8);
+ expect(PANE_CARD_DIVIDER_PX).toBe(1);
+ expect(PANE_CARD_INSET_PX).toBe(7);
+ expect(PANE_CARD_INSET_PX + PANE_CARD_DIVIDER_PX).toBe(PANE_CARD_GAP_PX);
+ });
+});
diff --git a/packages/app/src/components/ui/pane-card.tsx b/packages/app/src/components/ui/pane-card.tsx
new file mode 100644
index 000000000..d1d835b39
--- /dev/null
+++ b/packages/app/src/components/ui/pane-card.tsx
@@ -0,0 +1,57 @@
+import { Slot } from 'radix-ui';
+import type * as React from 'react';
+import type { PaneId } from '@/lib/pane-visibility-store';
+import { cn } from '@/lib/utils';
+
+export type PaneCardVariant = 'card' | 'flat';
+
+export const PANE_CARD_GAP_PX = 8;
+export const PANE_CARD_DIVIDER_PX = 1;
+export const PANE_CARD_INSET_PX = PANE_CARD_GAP_PX - PANE_CARD_DIVIDER_PX;
+export const PANE_CARD_GAP_LEAD_INSET_PX = 4;
+export const PANE_CARD_GAP_TRAIL_INSET_PX = PANE_CARD_INSET_PX - PANE_CARD_GAP_LEAD_INSET_PX;
+export const PANE_CARD_TOP_BAR_CLASS = 'h-11 shrink-0';
+export const SECONDARY_PANEL_SURFACE_CLASS = cn(
+ 'bg-sidebar [:is(html[data-color-theme=solarized],html[data-color-theme=monokai])_&]:[--muted-foreground:var(--sidebar-foreground)]',
+ '[html[data-color-theme=gruvbox]_&]:[--secondary-panel-accent:color-mix(in_srgb,var(--primary),white_10%)]',
+ '[html[data-color-theme=solarized]_&]:[--secondary-panel-accent:color-mix(in_srgb,var(--primary),white_15%)]',
+ '[html[data-color-theme=catppuccin-latte]_&]:[--secondary-panel-accent:color-mix(in_srgb,var(--primary),black_10%)]',
+);
+
+const PANE_CARD_DIVIDER_CLASS: Record<'horizontal' | 'vertical', string> = {
+ vertical: 'z-10 bg-transparent after:w-2!',
+ horizontal: 'z-10 bg-transparent aria-[orientation=horizontal]:after:h-2!',
+};
+
+export function paneCardDividerClass(
+ variant: PaneCardVariant,
+ orientation: 'horizontal' | 'vertical',
+): string | undefined {
+ return variant === 'card' ? PANE_CARD_DIVIDER_CLASS[orientation] : undefined;
+}
+
+const PANE_CARD_BASE_CLASS =
+ 'relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background';
+const PANE_CARD_SHAPE_CLASS =
+ 'rounded-xl shadow-[0_2px_8px_0_rgb(0_0_0/0.08),0_1px_2px_-1px_rgb(0_0_0/0.1)]';
+
+interface PaneCardProps extends React.ComponentProps<'div'> {
+ readonly pane: PaneId;
+ readonly variant?: PaneCardVariant;
+ readonly asChild?: boolean;
+}
+
+function PaneCard({ pane, variant = 'card', asChild = false, className, ...props }: PaneCardProps) {
+ const Comp = asChild ? Slot.Root : 'div';
+ return (
+ <Comp
+ data-slot="pane-card"
+ data-pane={pane}
+ data-variant={variant}
+ className={cn(PANE_CARD_BASE_CLASS, variant === 'card' && PANE_CARD_SHAPE_CLASS, className)}
+ {...props}
+ />
+ );
+}
+
+export { PaneCard };
diff --git a/packages/app/src/components/ui/resizable.tsx b/packages/app/src/components/ui/resizable.tsx
index 8e7739fcb..5e6177f73 100644
--- a/packages/app/src/components/ui/resizable.tsx
+++ b/packages/app/src/components/ui/resizable.tsx
@@ -28,7 +28,7 @@ function ResizableHandle({
<ResizablePrimitive.Separator
data-slot="resizable-handle"
className={cn(
- 'relative flex w-px items-center justify-center bg-border ring-offset-background after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-hidden aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90',
+ 'relative flex w-px items-center justify-center bg-border ring-offset-background after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-hidden aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90 [&>div]:opacity-0 [&>div]:transition-opacity hover:[&>div]:opacity-100 focus-visible:[&>div]:opacity-100 data-[separator=hover]:[&>div]:opacity-100 data-[separator=active]:[&>div]:opacity-100',
className,
)}
{...props}
diff --git a/packages/app/src/components/ui/sidebar.dom.test.tsx b/packages/app/src/components/ui/sidebar.dom.test.tsx
index fee3d3010..5dbdb3634 100644
--- a/packages/app/src/components/ui/sidebar.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.dom.test.tsx
@@ -90,6 +90,18 @@ describe('Sidebar runtime contracts', () => {
).toBe('20rem');
});
+ test('the inset refuses to render outside a SidebarProvider, like the rest of the sidebar', async () => {
+ const { SidebarInset } = await import('./sidebar');
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ expect(() => {
+ render(<SidebarInset>Main</SidebarInset>);
+ }).toThrow('useSidebar must be used within a SidebarProvider.');
+ } finally {
+ consoleErrorSpy.mockRestore();
+ }
+ });
+
test('desktop sidebar trigger controls a labeled sidebar landmark', async () => {
await renderSidebarShell(1400);
diff --git a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
index a2f8653eb..84d1bd459 100644
--- a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
@@ -251,8 +251,8 @@ describe('SidebarProvider — focus safety on auto-collapse (FR-9 left side)', (
});
});
-describe('SidebarProvider — trigger click writes the current-partition slot (FR-3, FR-5, D13)', () => {
- test('click in above partition writes a slot under the `above` key', () => {
+describe('SidebarProvider — trigger click writes one intent for every partition', () => {
+ test('click in above partition writes the same slot for every partition', () => {
setInnerWidth(1280);
installMatchMedia(true);
render(<Fixture />);
@@ -266,11 +266,11 @@ describe('SidebarProvider — trigger click writes the current-partition slot (F
expect(getSidebarState()).toBe('collapsed');
expect(readPins(window.localStorage)).toEqual({
- left: { above: 'collapsed' },
+ left: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' },
});
});
- test('click in below partition PRESERVES the existing above slot (D13 — slots are independent)', () => {
+ test('click in below partition replaces an earlier slot in every partition', () => {
window.localStorage.setItem(SIDEBAR_PINS_KEY, JSON.stringify({ left: { above: 'open' } }));
setInnerWidth(900);
installMatchMedia(false);
@@ -285,11 +285,11 @@ describe('SidebarProvider — trigger click writes the current-partition slot (F
expect(getSidebarState()).toBe('expanded');
expect(readPins(window.localStorage)).toEqual({
- left: { above: 'open', below: 'open' },
+ left: { above: 'open', below: 'open', embedded: 'open' },
});
});
- test('matchMedia re-resolution followed by click writes the NEW partition slot (closure freshness)', () => {
+ test('matchMedia re-resolution followed by click writes the fresh intent everywhere (closure freshness)', () => {
setInnerWidth(1280);
const mql = installMatchMedia(true);
render(<Fixture />);
@@ -307,7 +307,7 @@ describe('SidebarProvider — trigger click writes the current-partition slot (F
});
expect(readPins(window.localStorage)).toEqual({
- left: { below: 'open' },
+ left: { above: 'open', below: 'open', embedded: 'open' },
});
});
});
diff --git a/packages/app/src/components/ui/sidebar.tsx b/packages/app/src/components/ui/sidebar.tsx
index 9decf926c..3730e0d48 100644
--- a/packages/app/src/components/ui/sidebar.tsx
+++ b/packages/app/src/components/ui/sidebar.tsx
@@ -12,8 +12,14 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { useSidebarResize } from '@/hooks/use-sidebar-resize';
import { formatShortcutLabel, matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
+import { revealEditorBeforeActing } from '@/lib/reveal-editor';
import { LEFT_COLLAPSE_THRESHOLD, resolvePartition } from '@/lib/sidebar-partition';
-import { applyToggle, readPins, resolveEffectiveState } from '@/lib/sidebar-pin-store';
+import {
+ applyToggleAtEveryWidth,
+ openIntentAfterPartitionChange,
+ readPins,
+ resolveEffectiveState,
+} from '@/lib/sidebar-pin-store';
import { cn } from '@/lib/utils';
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
@@ -26,19 +32,27 @@ const SIDEBAR_WIDTH_COOKIE_NAME = 'sidebar_width';
const SIDEBAR_WIDTH_VALUE_PATTERN = /^\d+(?:\.\d+)?(?:rem|px)$/;
type OpenHandler = React.Dispatch<React.SetStateAction<boolean>>;
+type OpenRequestHandler = (open: boolean) => boolean | null;
+type CoverSelectionHandler = (editorDocName: string | null) => void;
type SidebarContextProps = {
state: 'expanded' | 'collapsed';
open: boolean;
setOpen: OpenHandler;
toggleSidebar: () => void;
+ canDock: boolean;
+ setCanDock: React.Dispatch<React.SetStateAction<boolean>>;
+ registerOpenRequestHandler: (handler: OpenRequestHandler) => () => void;
+ registerCoverSelectionHandler: (handler: CoverSelectionHandler) => () => void;
+ cover: boolean;
+ dismissCover: (restoreFocus?: boolean) => void;
width: string;
setWidth: React.Dispatch<React.SetStateAction<string>>;
isDraggingRail: boolean;
setIsDraggingRail: React.Dispatch<React.SetStateAction<boolean>>;
showPushPulse: boolean;
setShowPushPulse: React.Dispatch<React.SetStateAction<boolean>>;
- notifySidebarFileSelected: () => void;
+ notifySidebarFileSelected: (editorDocName?: string | null) => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
@@ -93,6 +107,24 @@ function SidebarProvider({
const [width, setWidth] = React.useState(() => getInitialSidebarWidth(defaultWidth));
const [isDraggingRail, setIsDraggingRail] = React.useState(false);
const [showPushPulse, setShowPushPulse] = React.useState(false);
+ const [canDock, setCanDock] = React.useState(true);
+ const [cover, setCover] = React.useState(false);
+ const coverOpenerRef = React.useRef<HTMLElement | null>(null);
+ const openRequestHandlerRef = React.useRef<OpenRequestHandler | null>(null);
+
+ function registerOpenRequestHandler(handler: OpenRequestHandler) {
+ openRequestHandlerRef.current = handler;
+ return () => {
+ if (openRequestHandlerRef.current === handler) openRequestHandlerRef.current = null;
+ };
+ }
+ const coverSelectionHandlerRef = React.useRef<CoverSelectionHandler | null>(null);
+ function registerCoverSelectionHandler(handler: CoverSelectionHandler) {
+ coverSelectionHandlerRef.current = handler;
+ return () => {
+ if (coverSelectionHandlerRef.current === handler) coverSelectionHandlerRef.current = null;
+ };
+ }
const [_open, _setOpen] = React.useState(() => {
const pins = readPins();
@@ -101,18 +133,55 @@ function SidebarProvider({
});
const open = openProp ?? _open;
- const setOpen: OpenHandler = (value) => {
+ function dismissCover(restoreFocus = true) {
+ setCover(false);
+ if (!restoreFocus) return;
+ const opener = coverOpenerRef.current;
+ requestAnimationFrame(() => {
+ const candidates = [
+ opener,
+ document.querySelector<HTMLElement>('[data-sidebar="trigger"]'),
+ document.querySelector<HTMLElement>('[data-header-pane-button="editor"]'),
+ ];
+ for (const candidate of candidates) {
+ if (
+ candidate?.isConnected &&
+ candidate.tabIndex >= 0 &&
+ !candidate.matches(':disabled') &&
+ candidate.closest('[inert]') == null &&
+ candidate.getClientRects().length > 0
+ ) {
+ candidate.focus();
+ if (document.activeElement === candidate) return;
+ }
+ }
+ });
+ }
+ const dismissCoverEvent = React.useEffectEvent(dismissCover);
+
+ const setOpen = (value: React.SetStateAction<boolean>) => {
const openState = typeof value === 'function' ? value(openRef.current) : value;
+ const requestedCanDock =
+ openRequestHandlerRef.current == null ? canDock : openRequestHandlerRef.current(openState);
+ if (requestedCanDock == null) return false;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
- applyToggle('left', partition, openState ? 'open' : 'collapsed');
+ applyToggleAtEveryWidth('left', openState ? 'open' : 'collapsed');
+ if (openState && !requestedCanDock) {
+ coverOpenerRef.current =
+ document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ setCover(true);
+ } else {
+ setCover(false);
+ }
+ return true;
};
function toggleSidebar() {
- setOpen((prev) => !prev);
+ return setOpen(!(open && (canDock || cover)));
}
const openRef = React.useRef(open);
@@ -120,7 +189,12 @@ function SidebarProvider({
openRef.current = open;
});
- function notifySidebarFileSelected() {
+ function notifySidebarFileSelected(editorDocName: string | null = null) {
+ if (cover) {
+ dismissCover(editorDocName === null);
+ coverSelectionHandlerRef.current?.(editorDocName);
+ return;
+ }
if (window.innerWidth >= LEFT_COLLAPSE_THRESHOLD) return;
if (!openRef.current) return;
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
@@ -133,23 +207,31 @@ function SidebarProvider({
const newPartition = resolvePartition(embeddedHost, window.innerWidth, 'left');
setPartition(newPartition);
const pins = readPins();
- const effective = resolveEffectiveState('left', newPartition, pins);
- _setOpen(effective === 'open');
+ if (openRequestHandlerRef.current == null) {
+ _setOpen(resolveEffectiveState('left', newPartition, pins) === 'open');
+ return;
+ }
+ const intent = openIntentAfterPartitionChange('left', newPartition, pins);
+ if (intent !== undefined) _setOpen(intent);
};
mql.addEventListener('change', onChange);
return () => mql.removeEventListener('change', onChange);
}, [embeddedHost]);
React.useLayoutEffect(() => {
- if (open) return;
+ if (cover && canDock) dismissCoverEvent();
+ }, [cover, canDock]);
+
+ React.useLayoutEffect(() => {
+ if (open && (canDock || cover)) return;
const sidebarEl = document.getElementById(SIDEBAR_ID);
if (!sidebarEl?.contains(document.activeElement)) return;
const trigger = document.querySelector<HTMLElement>('[data-sidebar="trigger"]');
trigger?.focus();
- }, [open]);
+ }, [open, canDock, cover]);
React.useEffect(() => {
- if (partition === 'above' || !open) return;
+ if (partition === 'above' || !open || !canDock || cover) return;
const onEscape = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
if (isOverlayLayerOpen()) return;
@@ -161,8 +243,8 @@ function SidebarProvider({
};
window.addEventListener('keydown', onEscape, { capture: true });
return () => window.removeEventListener('keydown', onEscape, { capture: true });
- // biome-ignore lint/correctness/useExhaustiveDependencies: setOpen is render-bound; partition + open gate the subscription lifecycle
- }, [partition, open, setOpen]);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: setOpen is render-bound; partition, open, canDock and cover gate the subscription lifecycle
+ }, [partition, open, canDock, cover, setOpen]);
React.useEffect(() => {
if (typeof window !== 'undefined' && window.okDesktop != null) return;
@@ -170,7 +252,7 @@ function SidebarProvider({
if (!matchesKeyboardShortcut(event, 'toggle-files-sidebar')) return;
if (isOverlayLayerOpen()) return;
event.preventDefault();
- toggleSidebar();
+ if (toggleSidebar()) revealEditorBeforeActing();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
@@ -179,7 +261,7 @@ function SidebarProvider({
toggleSidebar,
]);
- const state = open ? 'expanded' : 'collapsed';
+ const state = open && (canDock || cover) ? 'expanded' : 'collapsed';
return (
<SidebarContext.Provider
@@ -188,6 +270,12 @@ function SidebarProvider({
open,
setOpen,
toggleSidebar,
+ canDock,
+ setCanDock,
+ registerOpenRequestHandler,
+ registerCoverSelectionHandler,
+ cover,
+ dismissCover,
width,
setWidth,
isDraggingRail,
@@ -207,7 +295,7 @@ function SidebarProvider({
} as React.CSSProperties
}
className={cn(
- 'group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar',
+ 'group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-desk',
className,
)}
{...props}
@@ -231,7 +319,7 @@ function Sidebar({
collapsible?: 'offcanvas' | 'icon' | 'none';
}) {
const { t } = useLingui();
- const { state, isDraggingRail } = useSidebar();
+ const { state, isDraggingRail, cover } = useSidebar();
if (collapsible === 'none') {
return (
@@ -251,7 +339,7 @@ function Sidebar({
return (
<div
- className="group peer text-sidebar-foreground"
+ className={cn('group peer text-sidebar-foreground', cover && 'relative size-full')}
data-state={state}
data-collapsible={state === 'collapsed' ? collapsible : ''}
data-variant={variant}
@@ -269,6 +357,7 @@ function Sidebar({
? 'group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]'
: 'group-data-[collapsible=icon]:w-(--sidebar-width-icon)',
'group-data-[dragging=true]:duration-0! group-data-[dragging=true]_*:!duration-0',
+ cover && 'hidden',
)}
/>
<nav
@@ -276,12 +365,16 @@ function Sidebar({
aria-label={t`File sidebar`}
data-slot="sidebar-container"
data-side={side}
+ inert={state === 'collapsed'}
className={cn(
- 'fixed inset-y-0 z-10 flex h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear motion-reduce:transition-none motion-reduce:duration-0 data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]',
- variant === 'floating' || variant === 'inset'
+ 'absolute inset-y-0 z-10 flex w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear motion-reduce:transition-none motion-reduce:duration-0 data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]',
+ variant === 'floating'
? 'p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]'
- : 'group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l',
+ : variant === 'inset'
+ ? 'group-data-[side=left]:border-e group-data-[side=right]:border-s group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]'
+ : 'group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l',
'group-data-[dragging=true]:duration-0! group-data-[dragging=true]_*:!duration-0',
+ cover && 'inset-0 size-full transition-none',
className,
)}
{...props}
@@ -339,11 +432,11 @@ function SidebarRail({
enableToggle?: boolean;
}) {
const { t } = useLingui();
- const { toggleSidebar, setWidth, state, width, setIsDraggingRail } = useSidebar();
+ const { toggleSidebar, setWidth, state, width, setIsDraggingRail, cover } = useSidebar();
const { dragRef, handleMouseDown } = useSidebarResize({
direction: 'right',
- enableDrag,
- enableToggle,
+ enableDrag: enableDrag && !cover,
+ enableToggle: enableToggle && !cover,
onResize: setWidth,
onToggle: toggleSidebar,
currentWidth: width,
@@ -353,6 +446,7 @@ function SidebarRail({
setIsDraggingRail,
widthCookieName: SIDEBAR_WIDTH_COOKIE_NAME,
widthCookieMaxAge: SIDEBAR_COOKIE_MAX_AGE,
+ isNested: true,
});
return (
@@ -374,9 +468,10 @@ function SidebarRail({
'in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize',
'[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize',
'group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar',
- '[[data-side=left][data-collapsible=offcanvas]_&]:-right-2',
- '[[data-side=right][data-collapsible=offcanvas]_&]:-left-2',
+ '[[data-side=left][data-collapsible=offcanvas]_&]:-right-4',
+ '[[data-side=right][data-collapsible=offcanvas]_&]:-left-4',
'md:group-data-[variant=inset]:after:inset-y-5',
+ cover && 'hidden',
className,
)}
{...props}
@@ -384,10 +479,10 @@ function SidebarRail({
);
}
-function SidebarInset({ className, onAnimationEnd, ...props }: React.ComponentProps<'main'>) {
+function SidebarInset({ className, onAnimationEnd, ...props }: React.ComponentProps<'div'>) {
const { showPushPulse, setShowPushPulse } = useSidebar();
- const handleAnimationEnd: React.AnimationEventHandler<HTMLElement> = (event) => {
+ const handleAnimationEnd: React.AnimationEventHandler<HTMLDivElement> = (event) => {
onAnimationEnd?.(event);
if (event.animationName === 'sidebar-push-pulse') {
setShowPushPulse(false);
@@ -395,14 +490,11 @@ function SidebarInset({ className, onAnimationEnd, ...props }: React.ComponentPr
};
return (
- <main
+ <div
data-slot="sidebar-inset"
data-push-pulse={showPushPulse ? '' : undefined}
onAnimationEnd={handleAnimationEnd}
- className={cn(
- 'relative flex w-full flex-1 flex-col bg-background peer-data-[variant=inset]:m-2 peer-data-[variant=inset]:ml-0 peer-data-[variant=inset]:rounded-xl peer-data-[variant=inset]:shadow-sm peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2',
- className,
- )}
+ className={cn('relative flex w-full flex-1 flex-col bg-background', className)}
{...props}
/>
);
diff --git a/packages/app/src/components/use-live-xterm-theme.dom.test.tsx b/packages/app/src/components/use-live-xterm-theme.dom.test.tsx
index 95b051430..3e9ff90d0 100644
--- a/packages/app/src/components/use-live-xterm-theme.dom.test.tsx
+++ b/packages/app/src/components/use-live-xterm-theme.dom.test.tsx
@@ -1,6 +1,8 @@
import { render } from '@testing-library/react';
-import { act } from 'react';
+import type { ITheme } from '@xterm/xterm';
+import { act, useEffect } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { subscribeColorThemeEpoch } from '@/lib/color-theme-epoch';
import { COLOR_THEME_ATTRIBUTE } from '@/lib/use-apply-config-color-theme';
import { computeLiveXtermTheme } from './terminal-theme';
import { useLiveXtermTheme } from './use-live-xterm-theme';
@@ -95,3 +97,205 @@ describe('useLiveXtermTheme frame coalescing', () => {
view.unmount();
});
});
+
+describe('useLiveXtermTheme palette delivery', () => {
+ const lightPalette = { '--background': 'rgb(255, 255, 255)', '--foreground': 'rgb(10, 10, 10)' };
+ const intermediatePalette = {
+ '--background': 'rgb(143, 143, 143)',
+ '--foreground': 'rgb(102, 102, 102)',
+ };
+ const darkPalette = { '--background': 'rgb(16, 32, 48)', '--foreground': 'rgb(240, 224, 208)' };
+ let palette: Record<string, string> = lightPalette;
+ let transitioning = false;
+ let originalGetAnimations: typeof document.documentElement.getAnimations;
+
+ function ThemeProbe({
+ onTheme,
+ resolvedTheme,
+ }: {
+ onTheme: (theme: ITheme) => void;
+ resolvedTheme: string | undefined;
+ }) {
+ const theme = useLiveXtermTheme(resolvedTheme);
+ useEffect(() => {
+ onTheme(theme);
+ }, [onTheme, theme]);
+ return (
+ <output data-testid="terminal-palette">{`${theme.foreground}/${theme.background}`}</output>
+ );
+ }
+
+ async function nextFrame(): Promise<void> {
+ await act(async () => {
+ vi.advanceTimersToNextFrame();
+ });
+ }
+
+ async function changeTheme(name: string): Promise<void> {
+ await act(async () => {
+ document.documentElement.setAttribute(COLOR_THEME_ATTRIBUTE, name);
+ await Promise.resolve();
+ });
+ }
+
+ beforeEach(async () => {
+ vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] });
+ palette = lightPalette;
+ transitioning = false;
+ const root = document.documentElement;
+ originalGetAnimations = root.getAnimations;
+ root.getAnimations = () =>
+ transitioning ? ([{ transitionProperty: '--background' }] as unknown as Animation[]) : [];
+ const real = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(((element: Element) => {
+ const token = /var\((--[\w-]+)\)/.exec(element.getAttribute('style') ?? '')?.[1];
+ if (!token) return real(element);
+ return { backgroundColor: palette[token] ?? 'transparent' } as CSSStyleDeclaration;
+ }) as typeof window.getComputedStyle);
+ const unsubscribe = subscribeColorThemeEpoch(() => {});
+ await changeTheme('fixture-prime');
+ await nextFrame();
+ unsubscribe();
+ root.removeAttribute(COLOR_THEME_ATTRIBUTE);
+ });
+
+ afterEach(() => {
+ document.documentElement.getAnimations = originalGetAnimations;
+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('keeps an established terminal palette until the custom dark palette settles', async () => {
+ const received: ITheme[] = [];
+ const view = render(
+ <ThemeProbe resolvedTheme="dark" onTheme={(theme) => received.push(theme)} />,
+ );
+ expect(received).toHaveLength(1);
+ expect(received[0]).toMatchObject({
+ background: '#ffffffff',
+ foreground: '#0a0a0aff',
+ });
+
+ transitioning = true;
+ palette = intermediatePalette;
+ await changeTheme('custom-dark');
+ await nextFrame();
+ await nextFrame();
+ expect(received).toHaveLength(1);
+
+ transitioning = false;
+ palette = darkPalette;
+ await nextFrame();
+ expect(received).toHaveLength(2);
+ expect(received[1]).toMatchObject({
+ background: '#102030ff',
+ foreground: '#f0e0d0ff',
+ });
+ view.unmount();
+ });
+
+ it('keeps the settled palette when resolved mode changes during a fade', async () => {
+ const received: ITheme[] = [];
+ const onTheme = (theme: ITheme) => received.push(theme);
+ const view = render(<ThemeProbe resolvedTheme="light" onTheme={onTheme} />);
+ expect(received).toHaveLength(1);
+ expect(received[0]).toMatchObject({
+ background: '#ffffffff',
+ foreground: '#0a0a0aff',
+ });
+
+ transitioning = true;
+ palette = intermediatePalette;
+ view.rerender(<ThemeProbe resolvedTheme="dark" onTheme={onTheme} />);
+ expect(received).toHaveLength(1);
+
+ await changeTheme('custom-dark');
+ await nextFrame();
+ expect(received).toHaveLength(1);
+
+ transitioning = false;
+ palette = darkPalette;
+ await nextFrame();
+ expect(received).toHaveLength(2);
+ expect(received[1]).toMatchObject({
+ background: '#102030ff',
+ foreground: '#f0e0d0ff',
+ });
+ view.unmount();
+ });
+
+ it.each([
+ { mode: 'light', resolvedTheme: 'light', background: '#ffffff', foreground: '#262626' },
+ { mode: 'dark', resolvedTheme: 'dark', background: '#171717', foreground: '#e5e5e5' },
+ { mode: 'unresolved', resolvedTheme: undefined, background: '#ffffff', foreground: '#262626' },
+ ])(
+ 'initializes a newly mounted $mode terminal with readable fallback colors',
+ async ({ resolvedTheme, background, foreground }) => {
+ transitioning = true;
+ palette = intermediatePalette;
+ const received: ITheme[] = [];
+ const view = render(
+ <ThemeProbe resolvedTheme={resolvedTheme} onTheme={(theme) => received.push(theme)} />,
+ );
+ expect(received).toHaveLength(1);
+ expect(received[0]).toMatchObject({ background, foreground });
+
+ await nextFrame();
+ await nextFrame();
+ expect(received).toHaveLength(1);
+
+ transitioning = false;
+ palette = darkPalette;
+ await nextFrame();
+ expect(received.at(-1)).toMatchObject({
+ background: '#102030ff',
+ foreground: '#f0e0d0ff',
+ });
+ view.unmount();
+ },
+ );
+
+ it('preserves safe colors when a terminal unmounts and remounts during the fade', async () => {
+ const first = render(<ThemeProbe resolvedTheme="dark" onTheme={() => undefined} />);
+ transitioning = true;
+ palette = intermediatePalette;
+ await changeTheme('custom-dark');
+ await nextFrame();
+ first.unmount();
+ await nextFrame();
+
+ const secondReceived: ITheme[] = [];
+ const second = render(
+ <ThemeProbe resolvedTheme="dark" onTheme={(theme) => secondReceived.push(theme)} />,
+ );
+ expect(secondReceived.length).toBeGreaterThan(0);
+ expect(secondReceived.map((theme) => theme.background)).not.toContain('#8f8f8fff');
+ expect(secondReceived.map((theme) => theme.foreground)).not.toContain('#666666ff');
+
+ transitioning = false;
+ palette = darkPalette;
+ await nextFrame();
+ expect(secondReceived.at(-1)).toMatchObject({
+ background: '#102030ff',
+ foreground: '#f0e0d0ff',
+ });
+ second.unmount();
+ });
+
+ it('applies a changed palette on the next frame when no root color animation runs', async () => {
+ const received: ITheme[] = [];
+ const view = render(
+ <ThemeProbe resolvedTheme="dark" onTheme={(theme) => received.push(theme)} />,
+ );
+ palette = darkPalette;
+ await changeTheme('custom-dark');
+ await nextFrame();
+
+ expect(received.at(-1)).toMatchObject({
+ background: '#102030ff',
+ foreground: '#f0e0d0ff',
+ });
+ view.unmount();
+ });
+});
diff --git a/packages/app/src/components/use-live-xterm-theme.ts b/packages/app/src/components/use-live-xterm-theme.ts
index 720b86b24..06f9e8e82 100644
--- a/packages/app/src/components/use-live-xterm-theme.ts
+++ b/packages/app/src/components/use-live-xterm-theme.ts
@@ -1,7 +1,12 @@
import type { ITheme } from '@xterm/xterm';
import { useEffect, useState } from 'react';
import { useColorThemeEpoch } from '@/lib/color-theme-epoch';
-import { computeLiveXtermTheme, liveTokenReaderForEpoch } from './terminal-theme';
+import { themeColorTransitionsActive } from '@/lib/theme-color-transitions';
+import {
+ computeLiveXtermTheme,
+ liveTokenReaderForEpoch,
+ xtermThemeForMode,
+} from './terminal-theme';
function themesEqual(a: ITheme, b: ITheme): boolean {
const keys = new Set([...Object.keys(a), ...Object.keys(b)] as (keyof ITheme)[]);
@@ -11,11 +16,15 @@ function themesEqual(a: ITheme, b: ITheme): boolean {
export function useLiveXtermTheme(resolvedTheme: string | undefined): ITheme {
const epoch = useColorThemeEpoch();
- const [theme, setTheme] = useState<ITheme>(() =>
- computeLiveXtermTheme(resolvedTheme, liveTokenReaderForEpoch(epoch)),
- );
+ const [theme, setTheme] = useState<ITheme>(() => {
+ if (typeof document !== 'undefined' && themeColorTransitionsActive()) {
+ return xtermThemeForMode(resolvedTheme);
+ }
+ return computeLiveXtermTheme(resolvedTheme, liveTokenReaderForEpoch(epoch));
+ });
useEffect(() => {
+ if (themeColorTransitionsActive()) return;
const next = computeLiveXtermTheme(resolvedTheme, liveTokenReaderForEpoch(epoch));
setTheme((prev) => (themesEqual(prev, next) ? prev : next));
}, [epoch, resolvedTheme]);
diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsx
index b8acc6787..7033f9114 100644
--- a/packages/app/src/editor/DocumentContext.dom.test.tsx
+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx
@@ -7,6 +7,11 @@ import { Toaster } from '@/components/ui/sonner';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { hashFromAssetPath } from '@/lib/doc-hash';
import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import {
consumeHashNavigationSuppression,
recordAppShellCrashTrip,
@@ -353,6 +358,50 @@ function CloseActiveHarness() {
);
}
+function HiddenEditorRevealHarness() {
+ const ctx = useDocumentContext();
+ return (
+ <>
+ <span data-testid="open-tabs">{ctx.openTabs.join('|')}</span>
+ <button
+ type="button"
+ onClick={() =>
+ ctx.openTargetTransition({ kind: 'skills', target: 'skills' }, { deliberate: false })
+ }
+ >
+ Sync skills
+ </button>
+ <button type="button" onClick={() => ctx.clearTarget()}>
+ Clear target
+ </button>
+ <button type="button" onClick={() => ctx.openBlobRunner()}>
+ Blob run
+ </button>
+ </>
+ );
+}
+
+function BridgeHiddenEditorRevealHarness({ bridge }: { bridge: OkDesktopBridge }) {
+ useLayoutEffect(() => {
+ window.okDesktop = bridge;
+ return () => {
+ delete window.okDesktop;
+ };
+ }, [bridge]);
+ return <HiddenEditorRevealHarness />;
+}
+
+function hideEditorAndRecordRequests(): PaneVisibilityRequest[] {
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ return requests;
+}
+
function BridgeCloseActiveHarness({ bridge }: { bridge: OkDesktopBridge }) {
useLayoutEffect(() => {
window.okDesktop = bridge;
@@ -590,9 +639,10 @@ describe('DocumentContext preview-tab promotion on user edit', () => {
describe('DocumentContext tab close force contract', () => {
afterEach(() => {
+ __resetPaneVisibilityStoreForTests();
+ mockCollabUrl = null;
cleanup();
delete window.okDesktop;
- mockCollabUrl = null;
globalThis.fetch = originalFetch;
window.localStorage.clear();
window.location.hash = '';
@@ -821,6 +871,59 @@ describe('DocumentContext tab close force contract', () => {
expect(screen.getByTestId('pane-state').textContent).not.toContain('new-tab:1');
});
+ test('with the editor hidden, Close Tab asks it to show first', async () => {
+ seedActiveOtherTabSession();
+ const stub = makeEditorBridgeStub(
+ persistedTabSession(
+ [PINNED_TAB_ID, OTHER_TAB_ID],
+ [],
+ OTHER_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ );
+ render(<BridgeCloseActiveHarness bridge={stub.bridge} />, { wrapper: ProviderHarness });
+ await new Promise((r) => setTimeout(r, 0));
+ const requests = hideEditorAndRecordRequests();
+
+ stub.fire('close-active-tab-or-window');
+
+ expect(requests).toEqual([{ pane: 'editor', open: true }]);
+ expect(screen.getByTestId('open-tabs').textContent).toBe(PINNED_TAB_ID);
+ });
+
+ test('a non-deliberate skills sync leaves a hidden editor hidden, while Blob Run shows it', async () => {
+ mockCollabUrl = 'ws://localhost:1/collab';
+ render(<HiddenEditorRevealHarness />, { wrapper: ProviderHarness });
+ await new Promise((r) => setTimeout(r, 0));
+ const requests = hideEditorAndRecordRequests();
+
+ act(() => screen.getByRole('button', { name: 'Sync skills' }).click());
+ expect(requests).toEqual([]);
+
+ act(() => screen.getByRole('button', { name: 'Blob run' }).click());
+ expect(requests).toEqual([{ pane: 'editor', open: true }]);
+ });
+
+ test('clearing the target over restored tabs leaves a hidden editor hidden', async () => {
+ seedActiveOtherTabSession();
+ const stub = makeEditorBridgeStub(
+ persistedTabSession(
+ [PINNED_TAB_ID, OTHER_TAB_ID],
+ [],
+ OTHER_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ );
+ render(<BridgeHiddenEditorRevealHarness bridge={stub.bridge} />, { wrapper: ProviderHarness });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.getByTestId('open-tabs').textContent).toBe(`${PINNED_TAB_ID}|${OTHER_TAB_ID}`);
+ const requests = hideEditorAndRecordRequests();
+
+ act(() => screen.getByRole('button', { name: 'Clear target' }).click());
+
+ expect(requests).toEqual([]);
+ });
+
test('desktop close-active-tab-or-window action closes tabs before closing the editor window', async () => {
seedActiveOtherTabSession();
const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {});
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index 5a373a364..a825c9d1c 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -3,6 +3,7 @@ import { mediaKindForSidebarAssetExtension } from '@inkeep/open-knowledge-core/c
import { PrincipalSuccessSchema } from '@inkeep/open-knowledge-core/schemas/api';
import type { Principal } from '@inkeep/open-knowledge-core/types/principal';
import { createContext, type ReactNode, use, useEffect, useRef, useState } from 'react';
+import { isDocPanelOnScreen } from '@/components/doc-panel-visibility';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
import { docNameForNavigationTarget } from '@/components/navigation-targets';
import { consumePrewarmClick } from '@/components/prewarm-correlation';
@@ -27,6 +28,7 @@ import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import { markNoteWindowDocDeleted } from '@/lib/note-window-deleted-store';
import { isNoteWindow } from '@/lib/note-window-mode';
import { mark } from '@/lib/perf';
+import { revealEditor, revealEditorBeforeActing } from '@/lib/reveal-editor';
import { refreshServerInfo } from '@/lib/server-info-refresh';
import { showTabSessionRestoreRecoveryNotice } from '@/lib/tab-session-restore-recovery-notice';
import {
@@ -35,6 +37,7 @@ import {
} from '@/lib/tab-session-restore-suppression';
import { useCollabUrl } from '@/lib/use-collab-url';
import { resolveSyncWorkspace } from '@/lib/use-workspace';
+import { noteWorkspaceHashWrite } from '@/lib/workspace-hash-writes';
import { getEditorForDoc } from './active-editor';
import { handleBranchSwitched } from './branch-invalidation';
import {
@@ -207,6 +210,7 @@ interface DocumentContextValue {
}
export interface OpenTargetOptions {
+ deliberate?: boolean;
disposition?: TabOpenDisposition;
consumeActiveNewTab?: boolean;
tabBehavior?: 'append' | 'replace-active';
@@ -320,6 +324,7 @@ function hashFromTabId(tabId: string): string {
function navigateToHash(nextHash: string): void {
if (typeof window !== 'undefined' && !isSameHash(window.location.hash, nextHash)) {
+ noteWorkspaceHashWrite(nextHash);
window.location.hash = nextHash;
}
}
@@ -1225,6 +1230,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
existingTabBehavior: ExistingTabOpenBehavior = 'activate-owner',
) => {
if (collabUrl === null) return;
+ if (options.deliberate !== false) revealEditor();
const paneId = requestedPaneId ?? workspaceRef.current.focusedPaneId;
const p = getPool(collabUrl);
if (target.kind === 'skills') {
@@ -1303,6 +1309,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
activateTabInPaneById(workspaceRef.current.focusedPaneId, tabId);
const openBlobRunner = () => {
+ revealEditor();
activateOrOpenSurfaceNewTab(workspaceRef.current.focusedPaneId, 'blob-runner');
};
@@ -1582,6 +1589,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
useEffect(() => {
return subscribeLocalMenuAction((action) => {
if (action !== 'close-active-tab-or-window') return;
+ revealEditorBeforeActing();
if (!closeActiveTabOrWindow()) window.close();
});
}, [
@@ -1802,7 +1810,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
setDocPanelExpandSignal((prev) => prev + 1);
return;
}
- if (docPanelMode === 'agent' && docPanelAgentId === connectionId) {
+ if (docPanelMode === 'agent' && docPanelAgentId === connectionId && isDocPanelOnScreen()) {
setDocPanelModeState('doc');
return;
}
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index b7069773e..2d8fc134c 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -84,7 +84,11 @@ function cleanupSourceEditorEntry(docName: string, entry: CmCacheEntry): void {
}
}
-function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docName: string): void {
+function applyOutlineNavigation(
+ view: EditorView,
+ detail: OutlineNavDetail,
+ docName: string,
+): boolean {
const lines = sourceHeadingLines(view.state.doc);
const heading = lines[detail.index];
const trace = {
@@ -95,7 +99,7 @@ function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docN
};
if (!heading) {
emitDiagnosticBreadcrumb(OUTLINE_NAV_BREADCRUMB, { ...trace, outcome: 'no-target' });
- return;
+ return false;
}
const claimed = runScrollNavigation(docName, 'outline', () => {
@@ -110,6 +114,7 @@ function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docN
outcome: claimed ? 'scrolled' : 'declined',
targetLine: view.state.doc.lineAt(heading.from).number,
});
+ return claimed;
}
export function applyRawMdxNavigation(
@@ -397,7 +402,7 @@ export function SourceEditor({
});
return;
}
- applyOutlineNavigation(view, detail, docName);
+ if (applyOutlineNavigation(view, detail, docName)) detail.onNavigated?.(view.contentDOM);
clearPendingSourceNavigation(docName);
}
window.addEventListener(OUTLINE_NAV_EVENT, onNav);
@@ -410,7 +415,10 @@ export function SourceEditor({
if (!detail || detail.docName !== docName || !isSourceModeActive) return;
const view = viewRef.current;
if (!view) return;
- if (applyLintNavigation(view, detail, docName)) clearPendingSourceNavigation(docName);
+ if (applyLintNavigation(view, detail, docName)) {
+ clearPendingSourceNavigation(docName);
+ detail.onNavigated?.(view.contentDOM);
+ }
}
window.addEventListener(LINT_NAV_EVENT, onLintNav);
return () => window.removeEventListener(LINT_NAV_EVENT, onLintNav);
@@ -427,9 +435,13 @@ export function SourceEditor({
if (pendingNavigation.kind !== 'selection-offset') {
consumePendingSourceNavigation(docName);
if (pendingNavigation.kind === 'outline') {
- applyOutlineNavigation(view, pendingNavigation.detail, docName);
+ if (applyOutlineNavigation(view, pendingNavigation.detail, docName)) {
+ pendingNavigation.detail.onNavigated?.(view.contentDOM);
+ }
} else if (pendingNavigation.kind === 'lint') {
- applyLintNavigation(view, pendingNavigation.detail, docName);
+ if (applyLintNavigation(view, pendingNavigation.detail, docName)) {
+ pendingNavigation.detail.onNavigated?.(view.contentDOM);
+ }
} else if (pendingNavigation.kind === 'raw-mdx') {
applyRawMdxNavigation(
view,
diff --git a/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsx b/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsx
index 776a800c0..0e2a2187f 100644
--- a/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsx
+++ b/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsx
@@ -7,9 +7,12 @@ import { Suspense } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
+import { REPEAT_ANCHOR_NAV_EVENT } from './anchor-navigation-event';
import { sharedExtensions } from './extensions/shared';
+import { toInternalHashHref } from './internal-link-helpers';
const DOC_NAME = 'hash-ladder-doc';
+const HANGUL_HEADING = '한국어';
let editorEntry: {
editor: Editor;
@@ -78,7 +81,7 @@ describe('TiptapEditor deep-link hash ladder', () => {
const ydoc = new Y.Doc();
const ytext = ydoc.getText('source');
- ytext.insert(0, '# Target Heading\n\nbody');
+ ytext.insert(0, `# Target Heading\n\nbody\n\n# ${HANGUL_HEADING}\n\nmore`);
const editor = new Editor({
element: host,
extensions: sharedExtensions,
@@ -91,6 +94,12 @@ describe('TiptapEditor deep-link hash ladder', () => {
content: [{ type: 'text', text: 'Target Heading' }],
},
{ type: 'paragraph', content: [{ type: 'text', text: 'body' }] },
+ {
+ type: 'heading',
+ attrs: { level: 1 },
+ content: [{ type: 'text', text: HANGUL_HEADING }],
+ },
+ { type: 'paragraph', content: [{ type: 'text', text: 'more' }] },
],
},
});
@@ -147,6 +156,12 @@ describe('TiptapEditor deep-link hash ladder', () => {
return result;
}
+ function headingById(id: string): HTMLElement {
+ const heading = editorEntry?.editor.view.dom.querySelector<HTMLElement>(`#${CSS.escape(id)}`);
+ if (!heading) throw new Error(`no heading rendered with id ${id}`);
+ return heading;
+ }
+
test('anchor id is present so the ladder has a target to find', () => {
expect(editorEntry?.editor.view.dom.querySelector('#target-heading')).not.toBeNull();
});
@@ -171,4 +186,30 @@ describe('TiptapEditor deep-link hash ladder', () => {
expect(scrollIntoView).toHaveBeenCalled();
});
+
+ test('a decomposed-jamo hash anchor scrolls the heading whose id is composed', async () => {
+ const composed = HANGUL_HEADING.normalize('NFC');
+ const decomposed = HANGUL_HEADING.normalize('NFD');
+ expect(decomposed).not.toBe(composed);
+ const heading = headingById(composed);
+ window.location.hash = toInternalHashHref({ docName: DOC_NAME, anchor: decomposed });
+
+ await renderEditor(false);
+
+ expect(scrollIntoView.mock.contexts).toContain(heading);
+ expect(scrollIntoView.mock.contexts).not.toContain(headingById('target-heading'));
+ });
+
+ test('the repeat-anchor event scrolls the heading the hash already names again', async () => {
+ const heading = headingById('target-heading');
+ await renderEditor(false);
+ expect(scrollIntoView.mock.contexts).toContain(heading);
+ scrollIntoView.mockClear();
+
+ act(() => {
+ window.dispatchEvent(new Event(REPEAT_ANCHOR_NAV_EVENT));
+ });
+
+ expect(scrollIntoView.mock.contexts).toEqual([heading]);
+ });
});
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index b22290be2..8f7a6be8a 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -11,7 +11,7 @@ import type { AgentFlashEntry } from '@inkeep/open-knowledge-core/types/awarenes
import { deriveIconColor } from '@inkeep/open-knowledge-core/utils/identity';
import { randomUUID } from '@inkeep/open-knowledge-core/utils/random-uuid';
import { t } from '@lingui/core/macro';
-import { type AnyExtension, Editor, type EditorOptions, Extension } from '@tiptap/core';
+import { type AnyExtension, Editor, type EditorOptions, Extension, isMacOS } from '@tiptap/core';
import Collaboration from '@tiptap/extension-collaboration';
import Placeholder from '@tiptap/extension-placeholder';
import { EditorContent } from '@tiptap/react';
@@ -19,6 +19,7 @@ import { initProseMirrorDoc, yCursorPlugin, ySyncPluginKey } from '@tiptap/y-tip
import { type FC, use, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { SelectionAnnouncer } from '@/components/editor/SelectionAnnouncer';
+import { useEditorPaneOnScreen } from '@/lib/use-editor-pane-on-screen';
import {
clearRenameSnapshot,
editorScrollContainerOf,
@@ -30,7 +31,7 @@ import { getInteractionLayer } from './interaction-layer-host';
const editorCtorStartTimes = new WeakMap<object, number>();
-import type { Transaction as PMTransaction } from '@tiptap/pm/state';
+import { type Transaction as PMTransaction, TextSelection } from '@tiptap/pm/state';
import type { EditorView as PMEditorView } from '@tiptap/pm/view';
import { CommentAnchorLayer } from '@/comments/anchor-decorations';
import { CommentMarginRail } from '@/comments/CommentMarginRail';
@@ -52,6 +53,7 @@ import { useSingleFileMode } from '@/lib/single-file-mode';
import { useIdentity } from '../presence/identity';
import { registerEditor, unregisterEditor } from './active-editor';
import { changedRangeIsOnScreen } from './agent-follow-scroll';
+import { REPEAT_ANCHOR_NAV_EVENT } from './anchor-navigation-event';
import { findAnchorTarget } from './anchor-target';
import { applyLintFixes } from './apply-lint-fix.ts';
import { getAwarenessHeartbeat } from './awareness-heartbeat-runtime';
@@ -304,6 +306,64 @@ export function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[]
];
}
+function admitFocusedTextCaret(view: PMEditorView, event: KeyboardEvent): void {
+ const isLineEndKey =
+ !event.altKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ (isMacOS()
+ ? event.key === 'ArrowRight' && event.metaKey
+ : event.key === 'End' && !event.metaKey);
+ if (
+ event.isComposing ||
+ view.composing ||
+ !view.editable ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ (!isLineEndKey && (event.metaKey || event.key.length !== 1)) ||
+ !view.hasFocus() ||
+ !(view.state.selection instanceof TextSelection) ||
+ !view.state.selection.empty
+ ) {
+ return;
+ }
+
+ const domSelection = view.dom.ownerDocument.getSelection();
+ const focusNode = domSelection?.focusNode;
+ if (!domSelection?.isCollapsed || !focusNode || !view.dom.contains(focusNode)) return;
+ const focusElement =
+ focusNode.nodeType === Node.ELEMENT_NODE ? (focusNode as Element) : focusNode.parentElement;
+ if (focusElement?.closest('[contenteditable="false"]')) return;
+
+ const pos = view.posAtDOM(focusNode, domSelection.focusOffset, 1);
+ const $pos = view.state.doc.resolve(pos);
+ if (!$pos.parent.isTextblock) return;
+ const nextSelection =
+ view.someProp('createSelectionBetween', (create) => create(view, $pos, $pos)) ??
+ TextSelection.between($pos, $pos, 1);
+ if (!(nextSelection instanceof TextSelection) || !nextSelection.empty) return;
+ if (focusNode.nodeType === Node.ELEMENT_NODE) {
+ const element = focusNode as Element;
+ const textNode = view.dom.ownerDocument
+ .createTreeWalker(element, NodeFilter.SHOW_TEXT)
+ .nextNode();
+ if (
+ textNode &&
+ !textNode.parentElement?.closest('[contenteditable="false"]') &&
+ view.posAtDOM(textNode, 0, 1) === pos
+ ) {
+ const range = view.dom.ownerDocument.createRange();
+ range.setStart(textNode, 0);
+ range.collapse(true);
+ domSelection.removeAllRanges();
+ domSelection.addRange(range);
+ }
+ }
+ if (pos === view.state.selection.head) return;
+ view.dispatch(view.state.tr.setSelection(nextSelection));
+}
+
function buildEditorOptions(args: BuildEditorOptionsArgs): Partial<EditorOptions> {
const { provider, clipboard, ctorStart } = args;
return {
@@ -340,6 +400,10 @@ function buildEditorOptions(args: BuildEditorOptionsArgs): Partial<EditorOptions
handlePaste: (view, event) => clipboard.paste(view, event),
handleDrop: clipboard.drop,
handleDOMEvents: {
+ keydown: (view, event) => {
+ admitFocusedTextCaret(view, event);
+ return false;
+ },
copy: (view, event) => clipboard.copy(view, event as ClipboardEvent, false),
cut: (view, event) => clipboard.copy(view, event as ClipboardEvent, true),
},
@@ -483,6 +547,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
flashStateRef,
portalTarget,
}) => {
+ const editorPaneOnScreen = useEditorPaneOnScreen();
const portalSlotRef = useRef<HTMLDivElement | null>(null);
const singleFile = useSingleFileMode();
const [editorContentRevision, setEditorContentRevision] = useState(0);
@@ -856,7 +921,12 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
const liveView = (): PMEditorView | null =>
(editor as unknown as { editorView?: PMEditorView }).editorView ?? null;
- const flashAndScroll = (view: PMEditorView, from: number, to: number): void => {
+ const flashAndScroll = (
+ view: PMEditorView,
+ from: number,
+ to: number,
+ followChange: boolean,
+ ): void => {
view.dispatch(
view.state.tr.setMeta(agentInsertFlashKey, { add: { from, to }, now: Date.now() }),
);
@@ -870,9 +940,10 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
);
}, AGENT_INSERT_FLASH_MS + 50);
- if (!loadFollowFilePref()) return;
+ if (!followChange || !loadFollowFilePref()) return;
if (document.visibilityState !== 'visible') return;
if (view.hasFocus()) return;
+ if (view.dom.closest('[data-editor-pane-panel][inert]')) return;
const elementAtPos = (sv: PMEditorView, pos: number): HTMLElement | null => {
try {
const domRef = sv.domAtPos(pos);
@@ -888,7 +959,13 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
};
const scrollToChange = (): void => {
const sv = liveView();
- if (sv == null || sv.hasFocus() || document.visibilityState !== 'visible') return;
+ if (
+ sv == null ||
+ sv.hasFocus() ||
+ document.visibilityState !== 'visible' ||
+ sv.dom.closest('[data-editor-pane-panel][inert]')
+ )
+ return;
if (isScrollRestoreSuppressed(docName)) return;
const docSize = sv.state.doc.content.size;
const clamp = (pos: number): number => Math.max(0, Math.min(pos, docSize - 1));
@@ -931,7 +1008,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
const view = liveView();
if (view == null) return;
if (fresh !== null) lastAgentFlashKeyRef.current = fresh.key;
- flashAndScroll(view, range.from, range.to);
+ flashAndScroll(view, range.from, range.to, true);
};
editor.on('transaction', onTransaction);
@@ -946,7 +1023,12 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
const range = blockRangeToPositions(view.state.doc, blocks.from, blocks.to);
if (range === null) return;
lastAgentFlashKeyRef.current = fresh.key;
- flashAndScroll(view, range.from, range.to);
+ flashAndScroll(
+ view,
+ range.from,
+ range.to,
+ view.dom.closest('[data-editor-pane-projected]') === null,
+ );
};
const activationRaf = requestAnimationFrame(replayFromEntry);
const onSynced = (): void => {
@@ -1055,16 +1137,23 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
scheduleScrollFromHash();
}
+ function repeatScrollFromHash() {
+ handledHash = null;
+ scheduleScrollFromHash();
+ }
+
scheduleScrollFromHash();
provider.on('synced', retryPendingOrSchedule);
editor.on('transaction', retryPendingOrSchedule);
window.addEventListener('hashchange', scheduleScrollFromHash);
+ window.addEventListener(REPEAT_ANCHOR_NAV_EVENT, repeatScrollFromHash);
return () => {
if (timeoutId !== undefined) clearTimeout(timeoutId);
provider.off('synced', retryPendingOrSchedule);
editor.off('transaction', retryPendingOrSchedule);
window.removeEventListener('hashchange', scheduleScrollFromHash);
+ window.removeEventListener(REPEAT_ANCHOR_NAV_EVENT, repeatScrollFromHash);
};
}, [provider, editor, docName, activeDocName, isSourceMode]);
@@ -1112,6 +1201,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
scrollHeightBefore,
});
if (!claimed) return;
+ detail.onNavigated?.(realView.dom);
clearTimeout(settleTimer);
settleTimer = setTimeout(() => {
emitDiagnosticBreadcrumb(OUTLINE_NAV_SETTLED_BREADCRUMB, {
@@ -1172,7 +1262,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
data-agent-flash-agent-id=""
>
{}
- {!isSourceMode && (
+ {!isSourceMode && editorPaneOnScreen && (
<BubbleMenuBar editor={editor} shortcutEnabled={docName === activeDocName} />
)}
{}
diff --git a/packages/app/src/editor/anchor-navigation-event.ts b/packages/app/src/editor/anchor-navigation-event.ts
new file mode 100644
index 000000000..3cac874d7
--- /dev/null
+++ b/packages/app/src/editor/anchor-navigation-event.ts
@@ -0,0 +1,5 @@
+export const REPEAT_ANCHOR_NAV_EVENT = 'open-knowledge:repeat-anchor-nav';
+
+export function requestRepeatAnchorNavigation(): void {
+ window.dispatchEvent(new Event(REPEAT_ANCHOR_NAV_EVENT));
+}
diff --git a/packages/app/src/editor/extensions/internal-link.ts b/packages/app/src/editor/extensions/internal-link.ts
index d4f2418e0..4717d4c53 100644
--- a/packages/app/src/editor/extensions/internal-link.ts
+++ b/packages/app/src/editor/extensions/internal-link.ts
@@ -13,8 +13,8 @@ import { openExternalUrl } from '@/lib/external-link';
import { resolveLinkTargetIntent } from '../../components/link-target-intent';
import {
activateAssetLink,
+ navigateToMarkdownTarget,
openInternalHashHrefInNewTab,
- toInternalHashHref,
} from '../internal-link-helpers';
import { getPageListCache, type PageListCacheSnapshot } from '../page-list-cache';
import { createAssetContextMenuPlugin } from '../plugins/asset-context-menu';
@@ -164,9 +164,7 @@ export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({
if (newTab) {
openInternalHashHrefInNewTab({ docName: target.docName, anchor: target.anchor });
} else {
- window.location.assign(
- toInternalHashHref({ docName: target.docName, anchor: target.anchor }),
- );
+ navigateToMarkdownTarget(target);
}
return true;
}
@@ -174,7 +172,7 @@ export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({
if (newTab) {
openInternalHashHrefInNewTab({ docName, anchor: target.anchor });
} else {
- window.location.assign(toInternalHashHref({ docName, anchor: target.anchor }));
+ navigateToMarkdownTarget(target);
}
return true;
case 'external':
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
index d91361d36..5639997e0 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
@@ -361,6 +361,7 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
const pending = peekPendingSourceNavigation(docName);
if (pending?.kind === 'lint' && scrollToLintBlock(pending.detail)) {
clearPendingSourceNavigation(docName);
+ pending.detail.onNavigated?.(view.dom);
}
}
if (sourceAtStart !== null && !destroyed && getSource?.() !== sourceAtStart) {
@@ -439,7 +440,10 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
function onLintNav(event: Event) {
const detail = (event as CustomEvent<LintNavDetail>).detail;
if (!detail || detail.docName !== docName || destroyed) return;
- if (scrollToLintBlock(detail)) clearPendingSourceNavigation(docName);
+ if (scrollToLintBlock(detail)) {
+ clearPendingSourceNavigation(docName);
+ detail.onNavigated?.(view.dom);
+ }
}
startPass();
diff --git a/packages/app/src/editor/internal-link-helpers.anchor.dom.test.ts b/packages/app/src/editor/internal-link-helpers.anchor.dom.test.ts
index 1a7f392a0..2fee501a5 100644
--- a/packages/app/src/editor/internal-link-helpers.anchor.dom.test.ts
+++ b/packages/app/src/editor/internal-link-helpers.anchor.dom.test.ts
@@ -1,4 +1,7 @@
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
+import { anchorFromHash } from '../lib/doc-hash';
+import { REPEAT_ANCHOR_NAV_EVENT } from './anchor-navigation-event';
+import { findAnchorTarget } from './anchor-target';
import { navigateToMarkdownTarget } from './internal-link-helpers';
beforeAll(() => {
@@ -13,28 +16,49 @@ afterAll(() => {
afterEach(() => {
document.body.replaceChildren();
+ window.location.hash = '';
vi.restoreAllMocks();
});
-function mountHeading(id: string): ReturnType<typeof vi.fn> {
+function mountHeading(id: string): HTMLElement {
const heading = document.createElement('h2');
heading.id = id;
- const scrollIntoView = vi.fn();
- heading.scrollIntoView = scrollIntoView;
+ heading.textContent = id;
document.body.append(heading);
- return scrollIntoView;
+ return heading;
+}
+
+function anchorOfCurrentHash(): string {
+ return anchorFromHash(window.location.hash) ?? '';
}
describe('navigateToMarkdownTarget — in-document anchors', () => {
- test('scrolls to the heading whose id is the anchor', () => {
- const scrollIntoView = mountHeading('install');
+ test('navigates to the heading whose id is the anchor', () => {
+ const heading = mountHeading('install');
+ window.location.hash = '#/docs/guide';
navigateToMarkdownTarget({ kind: 'anchor', anchor: 'install' }, '#/docs/guide');
- expect(scrollIntoView).toHaveBeenCalledOnce();
+ expect(window.location.hash).toBe('#/docs/guide#install');
+ expect(findAnchorTarget(document, anchorOfCurrentHash())).toBe(heading);
});
- test('scrolls to a Korean heading from an anchor saved as decomposed jamo', () => {
- const scrollIntoView = mountHeading('한국어');
+ test('navigates to a Korean heading from an anchor saved as decomposed jamo', () => {
+ const heading = mountHeading('한국어');
+ window.location.hash = '#/docs/guide';
navigateToMarkdownTarget({ kind: 'anchor', anchor: '한국어'.normalize('NFD') }, '#/docs/guide');
- expect(scrollIntoView).toHaveBeenCalledOnce();
+ expect(findAnchorTarget(document, anchorOfCurrentHash())).toBe(heading);
+ });
+
+ test('a link to the anchor already in the address asks the editor to scroll again', () => {
+ const target = '#/docs/guide#install';
+ window.location.hash = target;
+ const repeat = vi.fn();
+ window.addEventListener(REPEAT_ANCHOR_NAV_EVENT, repeat);
+ try {
+ navigateToMarkdownTarget({ kind: 'anchor', anchor: 'install' }, target);
+ expect(repeat).toHaveBeenCalledOnce();
+ expect(window.location.hash).toBe(target);
+ } finally {
+ window.removeEventListener(REPEAT_ANCHOR_NAV_EVENT, repeat);
+ }
});
});
diff --git a/packages/app/src/editor/internal-link-helpers.ts b/packages/app/src/editor/internal-link-helpers.ts
index ba1440d1f..58a7fea72 100644
--- a/packages/app/src/editor/internal-link-helpers.ts
+++ b/packages/app/src/editor/internal-link-helpers.ts
@@ -8,9 +8,9 @@ import {
classifyMarkdownHref,
type DocLinkTarget,
} from '@inkeep/open-knowledge-core/utils/link-targets';
-import { hashFromAssetPath, hashFromDocName } from '../lib/doc-hash';
+import { hashFromAssetPath, hashFromDocName, isSameHash } from '../lib/doc-hash';
import { openExternalUrl } from '../lib/external-link';
-import { findAnchorTarget } from './anchor-target';
+import { requestRepeatAnchorNavigation } from './anchor-navigation-event';
import { dispatchAssetClick } from './asset-dispatch';
import { isSafeNavigationUrl } from './safe-navigation-url';
@@ -43,7 +43,12 @@ export function openHashHrefInNewTab(href: string): void {
}
function navigateToInternalHashHref(resolved: Pick<DocLinkTarget, 'docName' | 'anchor'>): void {
- window.location.assign(toInternalHashHref(resolved));
+ const href = toInternalHashHref(resolved);
+ if (resolved.anchor && isSameHash(window.location.hash, href)) {
+ requestRepeatAnchorNavigation();
+ return;
+ }
+ window.location.assign(href);
}
export function openInternalHashHrefInNewTab(
@@ -110,13 +115,7 @@ export function handleChipLinkClick(
function navigateToAnchorHref(anchor: string, locationHash = window.location.hash): void {
const currentDocName = getCurrentDocNameFromHash(locationHash);
if (!currentDocName) return;
-
- const element = findAnchorTarget(document, anchor);
- if (element) {
- element.scrollIntoView({ behavior: 'smooth', block: 'start' });
- }
-
- window.location.assign(hashFromDocName(currentDocName, anchor));
+ navigateToInternalHashHref({ docName: currentDocName, anchor });
}
export function navigateToMarkdownTarget(
diff --git a/packages/app/src/globals.alpha-aware.test.ts b/packages/app/src/globals.alpha-aware.test.ts
index d90ecd865..411dcb091 100644
--- a/packages/app/src/globals.alpha-aware.test.ts
+++ b/packages/app/src/globals.alpha-aware.test.ts
@@ -4,20 +4,30 @@ import { describe, expect, test } from 'vitest';
const CSS = readFileSync(join(__dirname, 'globals.css'), 'utf8');
+function themedDeskSelectors(css: string): string[] {
+ return [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].flatMap((match) => {
+ const selector = (match[1] ?? '').replace(/:not\(\s*\[data-color-theme\]\s*\)/g, '');
+ const body = match[2] ?? '';
+ return /\[data-color-theme\b/.test(selector) && /--desk\s*:/.test(body)
+ ? [selector.trim()]
+ : [];
+ });
+}
+
describe('globals.css alpha-aware retrofit', () => {
test('html.electron-mode renders the html background as transparent so vibrancy is exposed', () => {
expect(CSS).toMatch(/html\.electron-mode\s*\{[^}]*background-color\s*:\s*transparent[^}]*\}/);
});
- test('body in electron-mode renders bg-sidebar alpha-aware via relative-color syntax (preserves single source of truth)', () => {
+ test('body in electron-mode renders the desk alpha-aware via relative-color syntax (preserves single source of truth)', () => {
expect(CSS).toMatch(
- /html\.electron-mode\s+body\s*\{[^}]*background-color\s*:\s*oklch\(\s*from\s+var\(--sidebar\)\s+l\s+c\s+h\s*\/\s*0?\.\d+\s*\)[^}]*\}/,
+ /html\.electron-mode\s+body\s*\{[^}]*background-color\s*:\s*oklch\(\s*from\s+var\(--desk\)\s+l\s+c\s+h\s*\/\s*0?\.\d+\s*\)[^}]*\}/,
);
});
- test('[data-slot="sidebar-wrapper"] in electron-mode renders alpha-aware (overrides inset variant has-data: bg-sidebar)', () => {
+ test('[data-slot="sidebar-wrapper"] in electron-mode renders the desk alpha-aware (overrides inset variant has-data: bg-desk)', () => {
expect(CSS).toMatch(
- /html\.electron-mode\s+\[data-slot=["']sidebar-wrapper["']\]\s*\{[^}]*background-color\s*:\s*oklch\(\s*from\s+var\(--sidebar\)\s+l\s+c\s+h\s*\/\s*0?\.\d+\s*\)[^}]*\}/,
+ /html\.electron-mode\s+\[data-slot=["']sidebar-wrapper["']\]\s*\{[^}]*background-color\s*:\s*oklch\(\s*from\s+var\(--desk\)\s+l\s+c\s+h\s*\/\s*0?\.\d+\s*\)[^}]*\}/,
);
});
@@ -30,7 +40,7 @@ describe('globals.css alpha-aware retrofit', () => {
test('alpha used for outer canvas is the same value across html / body / sidebar-wrapper / sidebar-inner (no drift)', () => {
const alphas = [
...CSS.matchAll(
- /html\.electron-mode[^{]*\{[^}]*oklch\(\s*from\s+var\(--sidebar\)\s+l\s+c\s+h\s*\/\s*(0?\.\d+)\s*\)[^}]*\}/g,
+ /html\.electron-mode[^{]*\{[^}]*oklch\(\s*from\s+var\(--(?:sidebar|desk)\)\s+l\s+c\s+h\s*\/\s*(0?\.\d+)\s*\)[^}]*\}/g,
),
].map((m) => m[1]);
expect(alphas.length).toBeGreaterThanOrEqual(3);
@@ -39,6 +49,33 @@ describe('globals.css alpha-aware retrofit', () => {
});
});
+describe('globals.css — the desk token follows the active colour theme', () => {
+ test('--desk stays relative to the sidebar in light and named dark themes, with a fixed default dark frame', () => {
+ const root = CSS.match(/:root\s*\{([\s\S]*?)\n\}/)?.[1] ?? '';
+ expect(root).toMatch(/--desk:\s*oklch\(from var\(--sidebar\)\s+calc\(l - 0\.015\)\s+c\s+h\)/);
+ const dark = CSS.match(/\n\.dark\s*\{([\s\S]*?)\n\}/)?.[1] ?? '';
+ expect(dark).not.toMatch(/--desk\s*:/);
+ expect(CSS).toMatch(
+ /html\.dark:not\(\[data-color-theme\]\)\s*\{[^}]*--desk:\s*oklch\(0\.28 0 0\)/,
+ );
+ expect(themedDeskSelectors(CSS)).toEqual([]);
+ expect(themedDeskSelectors('html.dark[data-color-theme="dracula"] { --desk: red; }')).toEqual([
+ 'html.dark[data-color-theme="dracula"]',
+ ]);
+ });
+});
+
+describe('globals.css — the file list inside the editor card is opaque', () => {
+ test('the file list surface inside the editor card is solid --sidebar, after the alpha-aware rule so it wins on desktop', () => {
+ const alpha = CSS.search(/html\.electron-mode\s+\[data-slot=["']sidebar-inner["']\]\s*\{/);
+ const opaque = CSS.search(
+ /html\s+\[data-editor-file-list-slot\]\s+\[data-slot=["']sidebar-inner["']\]\s*\{[^}]*background-color\s*:\s*var\(--sidebar\)\s*;[^}]*\}/,
+ );
+ expect(alpha).toBeGreaterThan(-1);
+ expect(opaque).toBeGreaterThan(alpha);
+ });
+});
+
describe('globals.css STOP rule — inner editor surfaces stay opaque', () => {
test('[data-slot="sidebar-inset"] is NEVER targeted by an alpha-aware electron-mode rule', () => {
expect(CSS).not.toMatch(
@@ -52,7 +89,8 @@ describe('globals.css STOP rule — inner editor surfaces stay opaque', () => {
expect(CSS).not.toMatch(/html\.electron-mode[^{]*\{[^}]*--background\s*:/);
});
- test('--sidebar token is not redeclared under html.electron-mode (relative-color syntax targets bg-color directly)', () => {
+ test('--sidebar and --desk tokens are not redeclared under html.electron-mode (relative-color syntax targets bg-color directly)', () => {
expect(CSS).not.toMatch(/html\.electron-mode[^{]*\{[^}]*--sidebar\s*:/);
+ expect(CSS).not.toMatch(/html\.electron-mode[^{]*\{[^}]*--desk\s*:/);
});
});
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index 3fb0b0627..c7ec3c32f 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -16,6 +16,11 @@
background-color: var(--background);
}
+[data-editor-hidden] [data-rmiz-content] {
+ /* biome-ignore lint/complexity/noImportantStyles: react-medium-image-zoom writes visibility: visible as an inline style, which no selector specificity can outrank. */
+ visibility: hidden !important;
+}
+
/*
* Explicit source root for Tailwind v4 content scanning.
*
@@ -440,6 +445,21 @@
}
}
+@utility floating-card-surface {
+ @apply rounded-lg border border-border bg-card shadow-[0_2px_8px_0_rgb(0_0_0/0.08),0_1px_2px_-1px_rgb(0_0_0/0.1)];
+}
+
+@utility corner-card-column {
+ & .floating-card-surface {
+ pointer-events: auto;
+ }
+}
+
+/* UPSTREAM([email protected]): a modal Radix menu or dialog locks the page by writing pointer-events none inline on body, and the cards must honor that lock. */
+body[style*="pointer-events: none"] .corner-card-column .floating-card-surface {
+ pointer-events: none;
+}
+
/* Reduced-motion override — keep the opacity crossfade as a comprehension
aid (the panel still appears/disappears) but pin the height so the
layout-triggering animation doesn't fire. Matches the rest of this
@@ -1082,6 +1102,11 @@
opacity: 0.3;
}
+section[data-editor-pane-id] {
+ container-type: inline-size;
+ container-name: editor-document;
+}
+
/* Editor layout — grid on wrapper; content column max 1024px (lg), side rails minmax(gutter, 1fr) */
.tiptap-editor {
--content-max-width: 1024px;
@@ -1339,32 +1364,36 @@
--ok-trailing-zone: 2rem;
}
-/* Phone-width rails. The 4rem side rails are a desktop reading measure; on a
- ~390px screen they eat 128px, leaving a ~246px text column and starving the
- floating composer — whose card is a content-column child — down to a
- single-digit-pixel input that cannot be typed into.
-
- The two declarations move together on purpose: .ProseMirror escapes its
- content column into the rail (negative margin, compensating padding) to win
- drag-handle hit area on the left and border slack on the right. Shrink the
- rail without shrinking the escape and the border-box overhangs the editor and
- overflows the viewport, so the negative margin must never exceed
- --margin-width. Must also stay AFTER the .ProseMirror base rule — a media
- query adds no specificity, so an earlier block would lose to it.
- .ProseMirror.composer-prosemirror zeroes both below at higher specificity and
- is deliberately unaffected.
-
- Gated on a coarse pointer, not width alone. The block drag handle renders at
- content-start minus 52px, which a 1rem rail cannot hold — it lands at -28px
- and is clipped. A touch device never reveals that handle (it is hover-only),
- so nothing is lost there, while a narrow desktop window with a mouse keeps
- both the wide rail and a working handle. Consequence worth knowing when
- testing: resizing a desktop browser narrow does NOT reproduce this layout;
- emulate a touch device. */
+@container editor-document (width < 40rem) {
+ .tiptap-editor,
+ .property-panel {
+ --margin-left-width: 3.75rem;
+ --margin-right-width: 1rem;
+ }
+
+ .tiptap-editor:where(:dir(rtl)),
+ .property-panel:where(:dir(rtl)) {
+ --margin-left-width: 1rem;
+ --margin-right-width: 3.75rem;
+ }
+
+ .editor-content-aligned:where(:not(.property-panel)) {
+ --margin-left-width: 1rem;
+ --margin-right-width: 1rem;
+ }
+
+ .ProseMirror:not(.composer-prosemirror) {
+ margin-right: -1rem;
+ padding-right: 1rem;
+ }
+}
+
@media (width < 40rem) and (pointer: coarse) {
.tiptap-editor,
.editor-content-aligned {
--margin-width: 1rem;
+ --margin-left-width: 1rem;
+ --margin-right-width: 1rem;
}
.ProseMirror {
@@ -3349,6 +3378,7 @@ button:active:not(:disabled) {
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
+ --color-desk: var(--desk);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
@@ -3448,6 +3478,8 @@ button:active:not(:disabled) {
--chart-4: oklch(0.55 0.18 290);
--chart-5: oklch(0.58 0.21 25);
--radius: 0.625rem;
+ --desk: oklch(from var(--sidebar) calc(l - 0.015) c h);
+ --desk-hover: oklch(from var(--sidebar-hover) calc(l - 0.015) c h);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
@@ -3474,7 +3506,7 @@ button:active:not(:disabled) {
that wants theme-adaptive coloring. Light values are the Tailwind v4
`-700`/`-800` saturated palette (good contrast on `--background:
oklch(1 0 0)`); the matching `.dark` block below shifts to `-300`/
- `-400` for WCAG AA on `--background: oklch(0.145 0 0)`. Hex
+ `-400` for WCAG AA on `--background: oklch(0.195 0 0)`. Hex
fallbacks are GitHub-light defaults — only used if Tailwind's
default theme tokens haven't loaded (SSR / preview-render edge).
*/
@@ -3541,9 +3573,9 @@ button:active:not(:disabled) {
.dark {
color-scheme: dark;
- --background: oklch(0.145 0 0);
+ --background: oklch(0.195 0 0);
--foreground: oklch(0.985 0 0);
- --card: oklch(0.205 0 0);
+ --card: oklch(0.245 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
@@ -3573,13 +3605,14 @@ button:active:not(:disabled) {
--chart-3: oklch(0.77 0.14 70);
--chart-4: oklch(0.72 0.16 290);
--chart-5: oklch(0.72 0.2 25);
- --sidebar: oklch(0.205 0 0);
+ --sidebar: oklch(0.21 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.274 0.006 286.033);
--sidebar-accent-foreground: var(--color-sky-blue);
--sidebar-hover: oklch(0.269 0 0 / 50%);
+ --desk-hover: var(--sidebar-hover);
--sidebar-hover-foreground: oklch(0.985 0 0);
--sidebar-hover-muted-foreground: var(--muted-foreground);
--sidebar-hover-destructive-foreground: var(--destructive);
@@ -3593,7 +3626,7 @@ button:active:not(:disabled) {
/*
Syntax-highlight tokens — dark-theme overrides. Lighter shades
(`-300` / `-400`) clear WCAG AA on the dark `--background:
- oklch(0.145 0 0)`. Hex fallbacks are mid-light shades that survive
+ oklch(0.195 0 0)`. Hex fallbacks are mid-light shades that survive
on dark for the SSR / preview-render edge.
*/
--syntax-keyword: var(--color-purple-300, #d2a8ff);
@@ -3636,6 +3669,20 @@ button:active:not(:disabled) {
--ansi-bright-white: #ffffff;
}
+html.dark:not([data-color-theme]) {
+ --desk: oklch(0.28 0 0);
+ --file-tree-foreground: color-mix(in oklab, var(--sidebar-foreground) 75%, var(--sidebar));
+}
+
+html.dark:not([data-color-theme]) [data-app-header-leading] [data-variant="secondary"] {
+ background-color: color-mix(in oklab, var(--desk) 96%, var(--sidebar-foreground));
+ color: var(--muted-foreground);
+}
+
+html.dark [data-app-header] button[data-variant="ghost"]:is(:hover, [data-state="open"]) {
+ background-color: oklch(from var(--desk) calc(l + 0.04) c h);
+}
+
/*
Electron-mode outer-canvas alpha-aware retrofit.
@@ -3666,19 +3713,28 @@ button:active:not(:disabled) {
html.electron-mode {
background-color: transparent;
/*
- macOS traffic-light safe-area reserve. The Electron main process spreads
- `trafficLightPosition: { x: 22, y: 24 }` on darwin (see
- `packages/desktop/src/main/index.ts`), placing OS-drawn close/min/zoom
- buttons in the renderer's top-left at x=22..~100. Any full-viewport
- overlay must reserve enough left padding to clear that footprint.
- 78px = trafficLightPosition.x (22) + 3 buttons × ~18px + margin. This
- token is the single source for that reserve — EditorHeader, FileSidebar's
- SidebarHeader, GraphPanel, and ConnectingBanner all consume it rather than
- re-declaring the literal.
+ macOS traffic-light safe-area reserve. The Electron main process places
+ the OS-drawn close/min/zoom buttons in the renderer's top-left: at
+ x=16, y=15 inside a project window's 44px AppHeader (lined up with the
+ file list's content edge), x=22, y=17 in note windows and x=22, y=24 in
+ every other window (see
+ `packages/desktop/src/main/window-chrome.ts` and `note-window.ts`). Any
+ top-row chrome or full-viewport overlay must reserve enough left padding
+ to clear that footprint. 78px = trafficLightPosition.x (22) + 3 buttons
+ × ~18px + margin. This token is the single source for that reserve:
+ AppHeader, the note and single-file windows' EditorHeader, GraphPanel,
+ and the connection and branch banners all consume it rather than
+ re-declaring the literal. The AppHeader adds 10px to it, so on darwin
+ back and forward start 12px after the window buttons at x=16, and on
+ the web the first button's icon lines up with the file list, 16px from
+ the edge. Windows and Linux re-declare it as 0px inside the AppHeader for
+ the same alignment (see the rule after the reduced-transparency block).
Web hosts (no `window.okDesktop`) never gain the `electron-mode` class,
- so the variable is undefined there. Consumers MUST use the fallback
- form `pl-[var(--ok-titlebar-reserve-left,1rem)]` — `,1rem` matches the
- base `px-4` so web layout is unchanged. A bare no-fallback
+ so the variable is undefined there. Consumers MUST always supply a
+ fallback, and its value is the padding that consumer wants on the web:
+ `pl-[var(--ok-titlebar-reserve-left,1rem)]` for the ones whose base is
+ `px-4`, and `,0px` for the AppHeader, which supplies its own 10px on top
+ and so wants nothing added underneath. A bare no-fallback
`pl-[var(--ok-titlebar-reserve-left)]` is invalid-at-computed-value-time
on web and collapses `padding-left` to `0`, discarding the consumer's
base padding — a regression, not intended behavior. See precedent #49.
@@ -3711,12 +3767,31 @@ html.electron-mode.electron-platform-linux {
);
}
+@media (hover: hover) {
+ [data-app-header]
+ :is([data-variant^="ghost"], [data-slot="menubar-trigger"]):not([aria-pressed="true"]):hover {
+ background-color: var(--desk-hover);
+ }
+}
+
+[data-app-header]
+ :is([data-variant^="ghost"], [data-slot="menubar-trigger"]):not([aria-pressed="true"]):is(
+ [data-state="open"],
+ [aria-expanded="true"]
+ ) {
+ background-color: var(--desk-hover);
+}
+
html.electron-mode body {
- background-color: oklch(from var(--sidebar) l c h / 0.85);
+ background-color: oklch(from var(--desk) l c h / 0.85);
}
html.electron-mode [data-slot="sidebar-wrapper"] {
- background-color: oklch(from var(--sidebar) l c h / 0.85);
+ background-color: oklch(from var(--desk) l c h / 0.85);
+}
+
+html.electron-mode [data-app-header] {
+ background-color: oklch(from var(--desk) l c h / 0.85);
}
html.electron-mode [data-slot="sidebar-inner"] {
@@ -3747,15 +3822,19 @@ html.electron-mode [data-slot="sidebar-inner"] {
*/
@media (prefers-reduced-transparency: reduce) {
html.electron-mode {
- background-color: var(--sidebar);
+ background-color: var(--desk);
}
html.electron-mode body {
- background-color: var(--sidebar);
+ background-color: var(--desk);
}
html.electron-mode [data-slot="sidebar-wrapper"] {
- background-color: var(--sidebar);
+ background-color: var(--desk);
+ }
+
+ html.electron-mode [data-app-header] {
+ background-color: var(--desk);
}
html.electron-mode [data-slot="sidebar-inner"] {
@@ -3763,6 +3842,15 @@ html.electron-mode [data-slot="sidebar-inner"] {
}
}
+html.electron-mode.electron-platform-win32 [data-app-header],
+html.electron-mode.electron-platform-linux [data-app-header] {
+ --ok-titlebar-reserve-left: 0px;
+}
+
+html [data-editor-file-list-slot] [data-slot="sidebar-inner"] {
+ background-color: var(--sidebar);
+}
+
/* prose-no-margin — margin reset for first/last children inside wrappers.
Applied to the jsx-component-wrapper's nested editable region so block
children don't carry their natural top/bottom prose margins into the
@@ -6774,3 +6862,38 @@ html.electron-mode [data-slot="sidebar-inner"] {
colours: the app it annotates is entirely system-coloured in this mode. */
forced-color-adjust: none;
}
+
+[data-agents-panel-mount][data-chat-alone]
+ [data-agent-thread-root]
+ > :not(.absolute):not([data-testid="agent-thread-transcript"]):not(
+ :has([data-testid="agent-thread-transcript"])
+ ) {
+ width: 100%;
+ max-width: var(--chat-reading-width);
+ margin-inline: auto;
+}
+
+[data-agents-panel-mount][data-chat-alone] [data-testid="agent-thread-transcript"] {
+ padding-inline: max(0.75rem, calc((100% - var(--chat-reading-width)) / 2 + 0.75rem));
+}
+
+[data-agents-panel-mount] {
+ --chat-reading-width: 48rem;
+}
+
+[data-editor-pane-projected] [data-editor-pane-panel]:not([data-editor-pane-selected]),
+[data-editor-pane-projected] [data-editor-pane-tab-group]:not([data-editor-pane-selected]) {
+ position: absolute;
+ inset: 0;
+ visibility: hidden;
+ pointer-events: none;
+}
+
+[data-editor-pane-projected] [data-editor-pane-resize-handle] {
+ display: none;
+}
+
+[data-editor-pane-projected] [data-editor-pane-panel][data-editor-pane-selected],
+[data-editor-pane-projected] [data-editor-pane-tab-group][data-editor-pane-selected] {
+ min-width: 0;
+}
diff --git a/packages/app/src/globals.reduced-transparency.test.ts b/packages/app/src/globals.reduced-transparency.test.ts
index 100d28766..212139858 100644
--- a/packages/app/src/globals.reduced-transparency.test.ts
+++ b/packages/app/src/globals.reduced-transparency.test.ts
@@ -10,21 +10,21 @@ describe('globals.css — prefers-reduced-transparency revert', () => {
expect(CSS).toMatch(/@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)\s*\{/);
});
- test('reverts html.electron-mode to a solid sidebar background', () => {
+ test('reverts html.electron-mode to a solid desk background', () => {
expect(CSS).toMatch(
- /@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s*\{[\s\S]*?background-color:\s*var\(--sidebar\)/,
+ /@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s*\{[\s\S]*?background-color:\s*var\(--desk\)/,
);
});
- test('reverts html.electron-mode body to a solid sidebar background', () => {
+ test('reverts html.electron-mode body to a solid desk background', () => {
expect(CSS).toMatch(
- /@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s+body\s*\{[\s\S]*?background-color:\s*var\(--sidebar\)/,
+ /@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s+body\s*\{[\s\S]*?background-color:\s*var\(--desk\)/,
);
});
- test('reverts the sidebar-wrapper data-slot to a solid sidebar background', () => {
+ test('reverts the sidebar-wrapper data-slot to a solid desk background', () => {
expect(CSS).toMatch(
- /@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s+\[data-slot="sidebar-wrapper"\]\s*\{[\s\S]*?background-color:\s*var\(--sidebar\)/,
+ /@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s+\[data-slot="sidebar-wrapper"\]\s*\{[\s\S]*?background-color:\s*var\(--desk\)/,
);
});
@@ -71,8 +71,9 @@ describe('globals.css — STOP rule preserved (inner surfaces stay opaque)', ()
expect(block).not.toMatch(/--background\b/);
});
- test('@media block does not redeclare --sidebar (no cycle / no shadow)', () => {
+ test('@media block does not redeclare --sidebar or --desk (no cycle / no shadow)', () => {
expect(block).not.toMatch(/--sidebar\s*:/);
+ expect(block).not.toMatch(/--desk\s*:/);
});
});
diff --git a/packages/app/src/hooks/use-editor-footer-identity.ts b/packages/app/src/hooks/use-editor-footer-identity.ts
deleted file mode 100644
index 34d66af63..000000000
--- a/packages/app/src/hooks/use-editor-footer-identity.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { useSidebar } from '@/components/ui/sidebar';
-import { useCurrentBranch } from '@/hooks/use-current-branch';
-import { extractFolderBasename } from '@/lib/path-utils';
-import { useWorkspace } from '@/lib/use-workspace';
-
-export interface EditorFooterIdentity {
- projectName: string | null;
- projectPath: string | null;
- branch: string | null;
-}
-
-export function useEditorFooterIdentity(): EditorFooterIdentity | null {
- const branch = useCurrentBranch();
- const workspace = useWorkspace();
- const { state: sidebarState } = useSidebar();
- const desktopBridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
- const projectSwitcherVisible = desktopBridge && sidebarState === 'expanded';
-
- if (projectSwitcherVisible) return null;
-
- const projectName =
- desktopBridge?.config.projectName ??
- (workspace ? extractFolderBasename(workspace.contentDir) || null : null);
- const projectPath = desktopBridge?.config.projectPath ?? workspace?.contentDir ?? null;
-
- if (projectName === null && branch === null) return null;
- return { projectName, projectPath, branch };
-}
diff --git a/packages/app/src/hooks/use-history-presentation-mode.ts b/packages/app/src/hooks/use-history-presentation-mode.ts
index fbe33adcb..6efb03326 100644
--- a/packages/app/src/hooks/use-history-presentation-mode.ts
+++ b/packages/app/src/hooks/use-history-presentation-mode.ts
@@ -4,12 +4,11 @@ import type { ThreadHistoryMode } from '@/components/acp/ThreadHistoryPanel';
export const HISTORY_PANEL_WIDTH_PX = 248;
const HISTORY_MIN_TRANSCRIPT_WIDTH_PX = 300;
const HISTORY_DIVIDER_WIDTH_PX = 1;
+export const HISTORY_DOCKED_MIN_PANE_WIDTH_PX =
+ HISTORY_PANEL_WIDTH_PX + HISTORY_MIN_TRANSCRIPT_WIDTH_PX + HISTORY_DIVIDER_WIDTH_PX;
function historyModeForPaneWidth(width: number): ThreadHistoryMode {
- return width >=
- HISTORY_PANEL_WIDTH_PX + HISTORY_MIN_TRANSCRIPT_WIDTH_PX + HISTORY_DIVIDER_WIDTH_PX
- ? 'docked'
- : 'cover';
+ return width >= HISTORY_DOCKED_MIN_PANE_WIDTH_PX ? 'docked' : 'cover';
}
export function useHistoryPresentationMode(
diff --git a/packages/app/src/hooks/use-sync-auth-prompt.dom.test.tsx b/packages/app/src/hooks/use-sync-auth-prompt.dom.test.tsx
index f607c2a6c..15d27ea15 100644
--- a/packages/app/src/hooks/use-sync-auth-prompt.dom.test.tsx
+++ b/packages/app/src/hooks/use-sync-auth-prompt.dom.test.tsx
@@ -76,6 +76,25 @@ describe('useSyncAuthPrompt', () => {
expect(toastInfoCalls).toEqual([]);
});
+ test('a GitHub sign-in request opens the modal at the auth step', () => {
+ const onPrompt = vi.fn();
+ render(<TestComponent remote={GITHUB_REMOTE} onPrompt={onPrompt} />);
+
+ act(() => authPromptStore.request());
+
+ expect(onPrompt).toHaveBeenCalledWith('auth');
+ });
+
+ test('an identity request opens the modal at the identity step on any host', () => {
+ const onPrompt = vi.fn();
+ render(<TestComponent remote={GITEA_HTTPS_REMOTE} onPrompt={onPrompt} />);
+
+ act(() => authPromptStore.request('identity'));
+
+ expect(onPrompt).toHaveBeenCalledWith('identity');
+ expect(toastInfoCalls).toEqual([]);
+ });
+
test('a non-GitHub remote gets the stored-credential sentence and no modal', () => {
const onPrompt = vi.fn();
render(<TestComponent remote={GITEA_HTTPS_REMOTE} onPrompt={onPrompt} />);
@@ -104,7 +123,7 @@ describe('useSyncAuthPrompt', () => {
act(() => authPromptStore.request());
- expect(authPromptStore.getSnapshot()).toBe(false);
+ expect(authPromptStore.getSnapshot()).toBeNull();
expect(toastInfoCalls).toHaveLength(1);
});
diff --git a/packages/app/src/hooks/use-sync-auth-prompt.ts b/packages/app/src/hooks/use-sync-auth-prompt.ts
index 9cba5a1e4..048208d99 100644
--- a/packages/app/src/hooks/use-sync-auth-prompt.ts
+++ b/packages/app/src/hooks/use-sync-auth-prompt.ts
@@ -3,26 +3,26 @@ import { useEffect, useSyncExternalStore } from 'react';
import { toast } from 'sonner';
import { hasNonGitHubRemote, remoteTakesStoredToken } from '@/components/SyncStatusBadge';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
-import { authPromptStore } from '@/lib/auth-prompt-store';
+import { type AuthPromptStep, authPromptStore } from '@/lib/auth-prompt-store';
import { openAccountSettings } from '@/lib/use-settings-route';
export function useSyncAuthPrompt(
remote: GitSyncStatus['remote'] | undefined,
- onPrompt: () => void,
+ onPrompt: (step: AuthPromptStep) => void,
): void {
const { t } = useLingui();
const pending = useSyncExternalStore(
authPromptStore.subscribe,
authPromptStore.getSnapshot,
- () => false,
+ () => null,
);
const nonGitHub = hasNonGitHubRemote(remote ?? null);
const takesToken = remoteTakesStoredToken(remote);
useEffect(() => {
- if (!pending) return;
+ if (pending === null) return;
authPromptStore.clear();
- if (!nonGitHub) {
- onPrompt();
+ if (pending === 'identity' || !nonGitHub) {
+ onPrompt(pending);
return;
}
if (!takesToken) {
diff --git a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
index a7eb1fe80..9777dc864 100644
--- a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
+++ b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
@@ -293,9 +293,25 @@ describe('useThemeBridge (Tier-3 mount)', () => {
expect(stubBridge.setThemeSourceCalls[1]).toBe('dark');
});
- test('reports chrome as hex even when the token is authored in a syntax Electron cannot parse', async () => {
- document.documentElement.style.setProperty('--sidebar', 'oklch(0.985 0 0)');
- document.documentElement.style.setProperty('--sidebar-foreground', 'oklch(0.145 0 0)');
+ test('reports the desk, not the file list surface, as the hex window chrome colour', async () => {
+ const tokens = {
+ '--sidebar': 'rgb(250, 250, 250)',
+ '--desk': 'rgb(245, 245, 245)',
+ '--sidebar-foreground': 'rgb(10, 10, 10)',
+ };
+ for (const [name, value] of Object.entries(tokens)) {
+ document.documentElement.style.setProperty(name, value);
+ }
+ const computedStyle = window.getComputedStyle.bind(window);
+ const resolveVarReferences = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((element, pseudo) => {
+ const style = computedStyle(element, pseudo);
+ const token = /^var\((--[\w-]+)\)$/.exec(style.backgroundColor)?.[1];
+ if (token === undefined) return style;
+ const value = document.documentElement.style.getPropertyValue(token).trim();
+ return { backgroundColor: value || 'rgba(0, 0, 0, 0)' } as CSSStyleDeclaration;
+ });
const stubBridge = makeStubBridge();
try {
render(
@@ -311,14 +327,15 @@ describe('useThemeBridge (Tier-3 mount)', () => {
},
{ timeout: ASYNC_EFFECT_TIMEOUT_MS },
);
- const chrome = stubBridge.signalThemeAppliedCalls[0]?.chrome;
- if (chrome) {
- expect(chrome.bg).toMatch(/^#[0-9a-f]{6}$/);
- expect(chrome.symbol).toMatch(/^#[0-9a-f]{6}$/);
- }
+ expect(stubBridge.signalThemeAppliedCalls[0]?.chrome).toEqual({
+ bg: '#f5f5f5',
+ symbol: '#0a0a0a',
+ });
} finally {
- document.documentElement.style.removeProperty('--sidebar');
- document.documentElement.style.removeProperty('--sidebar-foreground');
+ resolveVarReferences.mockRestore();
+ for (const name of Object.keys(tokens)) {
+ document.documentElement.style.removeProperty(name);
+ }
}
});
diff --git a/packages/app/src/hooks/use-theme-bridge.ts b/packages/app/src/hooks/use-theme-bridge.ts
index c85e7d8fe..0770e4053 100644
--- a/packages/app/src/hooks/use-theme-bridge.ts
+++ b/packages/app/src/hooks/use-theme-bridge.ts
@@ -22,7 +22,7 @@ function resolveTokenHex(token: string): string | null {
function readChromeColors(): { bg: string; symbol: string } | undefined {
if (typeof document === 'undefined') return undefined;
try {
- const bg = resolveTokenHex('--sidebar');
+ const bg = resolveTokenHex('--desk');
const symbol = resolveTokenHex('--sidebar-foreground');
if (!bg || !symbol) return undefined;
return { bg, symbol };
diff --git a/packages/app/src/hooks/use-trailing-overflow.ts b/packages/app/src/hooks/use-trailing-overflow.ts
new file mode 100644
index 000000000..c496d16a1
--- /dev/null
+++ b/packages/app/src/hooks/use-trailing-overflow.ts
@@ -0,0 +1,77 @@
+import { useLayoutEffect, useRef, useState } from 'react';
+
+interface TrailingOverflowElements {
+ readonly header: HTMLElement;
+ readonly leading: HTMLElement;
+ readonly trailing: HTMLElement;
+}
+
+export interface TrailingOverflowOptions {
+ header: HTMLElement | null;
+ leading: HTMLElement | null;
+ trailing: HTMLElement | null;
+ centre?: HTMLElement | null;
+ signature: string;
+ slack: number;
+ measureTrailingWidth: (elements: TrailingOverflowElements) => number;
+ measureAvailableWidth: (
+ elements: TrailingOverflowElements,
+ latchedTrailingWidth: number,
+ ) => number;
+}
+
+export function useTrailingOverflow({
+ header,
+ leading,
+ trailing,
+ centre = null,
+ signature,
+ slack,
+ measureTrailingWidth,
+ measureAvailableWidth,
+}: TrailingOverflowOptions): boolean {
+ const [overflowed, setOverflowed] = useState(false);
+ const overflowedRef = useRef(false);
+ const measuredSignatureRef = useRef<string | null>(null);
+ const latchedTrailingWidthRef = useRef(0);
+ const measureRef = useRef({ measureTrailingWidth, measureAvailableWidth });
+
+ useLayoutEffect(() => {
+ measureRef.current = { measureTrailingWidth, measureAvailableWidth };
+ });
+
+ useLayoutEffect(() => {
+ if (!header || !leading || !trailing) return;
+
+ if (measuredSignatureRef.current !== signature) {
+ measuredSignatureRef.current = signature;
+ overflowedRef.current = false;
+ latchedTrailingWidthRef.current = 0;
+ }
+
+ const update = () => {
+ if (header.offsetWidth <= 0) return;
+ const elements = { header, leading, trailing };
+ if (!overflowedRef.current) {
+ latchedTrailingWidthRef.current = measureRef.current.measureTrailingWidth(elements);
+ }
+ const available = measureRef.current.measureAvailableWidth(
+ elements,
+ latchedTrailingWidthRef.current,
+ );
+ const next = latchedTrailingWidthRef.current + slack > available;
+ overflowedRef.current = next;
+ setOverflowed(next);
+ };
+ update();
+
+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update);
+ observer?.observe(header);
+ observer?.observe(leading);
+ observer?.observe(trailing);
+ if (centre) observer?.observe(centre);
+ return () => observer?.disconnect();
+ }, [header, leading, trailing, centre, signature, slack]);
+
+ return overflowed;
+}
diff --git a/packages/app/src/lib/acp/launch-agent-thread.ts b/packages/app/src/lib/acp/launch-agent-thread.ts
index df87fcc24..b95b60406 100644
--- a/packages/app/src/lib/acp/launch-agent-thread.ts
+++ b/packages/app/src/lib/acp/launch-agent-thread.ts
@@ -55,18 +55,21 @@ export function launchAgentThread(
titleHint: string | null,
stageDraft?: string | ThreadDraftContent | null,
attachments?: readonly AttachmentPart[],
+ onCreated?: (info: ThreadInfo) => void,
): Promise<ThreadLaunchOutcome> {
const launchKey = `${agent.source}:${agent.id}`;
if (inflightLaunches.has(launchKey)) return Promise.resolve('deduped');
inflightLaunches.add(launchKey);
- return getAgentThreadClient()
- .createThread({
- agent,
- prompt: prompt ?? undefined,
- docName: docName ?? undefined,
- titleHint: titleHint ?? undefined,
- ...(attachments !== undefined && attachments.length > 0 ? { attachments } : {}),
- })
+ const client = getAgentThreadClient();
+ const request = {
+ agent,
+ prompt: prompt ?? undefined,
+ docName: docName ?? undefined,
+ titleHint: titleHint ?? undefined,
+ ...(attachments !== undefined && attachments.length > 0 ? { attachments } : {}),
+ };
+ return client
+ .createThread(request, onCreated)
.then((info) => {
warnWhenLaunchedImagesAreUnsupported(info, attachments);
if (stageDraft != null) {
diff --git a/packages/app/src/lib/acp/launcher-selection.ts b/packages/app/src/lib/acp/launcher-selection.ts
index cac1fb24e..bc1d312ab 100644
--- a/packages/app/src/lib/acp/launcher-selection.ts
+++ b/packages/app/src/lib/acp/launcher-selection.ts
@@ -17,6 +17,16 @@ export type LauncherSelection =
| { readonly kind: 'terminal' }
| { readonly kind: 'none' };
+export const LAUNCHER_KIND_PANE: Readonly<
+ Record<LauncherSelection['kind'], 'agents' | 'terminal'>
+> = {
+ thread: 'agents',
+ none: 'agents',
+ cli: 'terminal',
+ terminal: 'terminal',
+ desktop: 'terminal',
+};
+
export function enabledThreadAgents(
agents: readonly RegisteredAgent[],
overrides: EnabledOverrides,
diff --git a/packages/app/src/lib/acp/thread-client.test.ts b/packages/app/src/lib/acp/thread-client.test.ts
index 7b46020be..ebeb154a8 100644
--- a/packages/app/src/lib/acp/thread-client.test.ts
+++ b/packages/app/src/lib/acp/thread-client.test.ts
@@ -647,6 +647,143 @@ describe('retry and sign-in lifecycle', () => {
});
describe('createThread channel wait', () => {
+ test('a malformed created frame rejects the pending launch instead of stranding it', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const client = new AgentThreadClient();
+ const sent: Array<Record<string, unknown>> = [];
+ const internals = client as unknown as { ws: unknown };
+ internals.ws = {
+ readyState: WebSocket.OPEN,
+ send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
+ };
+ const pending = client.createThread({ agent: { source: 'custom', id: 'agent' } }, (info) => {
+ if (info.threadId === '') throw new Error('empty thread');
+ });
+ await Promise.resolve();
+ const reqId = sent.find((frame) => frame.op === 'create')?.reqId;
+ expect(typeof reqId).toBe('string');
+
+ expect(() =>
+ client.receiveServerFrame(JSON.stringify({ op: 'created', reqId })),
+ ).not.toThrow();
+ await expect(pending).rejects.toThrow(/invalid created thread info: info/);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('a malformed created frame with no pending launch names the failing field and thread', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const client = new AgentThreadClient();
+
+ client.receiveServerFrame(
+ JSON.stringify({
+ op: 'created',
+ reqId: 'create-unknown',
+ info: {
+ threadId: 'thread-bad',
+ agent: { source: 'custom', id: 'agent', name: 'Agent' },
+ title: 'Agent',
+ status: 'ready',
+ createdAt: 'yesterday',
+ lastActivityAt: 1,
+ lastSeq: -1,
+ },
+ }),
+ );
+
+ expect(client.getThread('thread-bad')).toBeNull();
+ expect(warn).toHaveBeenCalledWith(
+ '[agent-threads] invalid created thread info',
+ expect.objectContaining({ field: 'createdAt', threadId: 'thread-bad' }),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('a created frame with a status this build does not know still starts the thread', async () => {
+ const client = new AgentThreadClient();
+ const sent: Array<Record<string, unknown>> = [];
+ const internals = client as unknown as { ws: unknown };
+ internals.ws = {
+ readyState: WebSocket.OPEN,
+ send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
+ };
+ const created = vi.fn();
+ const pending = client.createThread({ agent: { source: 'custom', id: 'agent' } }, created);
+ await Promise.resolve();
+ const reqId = sent.find((frame) => frame.op === 'create')?.reqId;
+
+ client.receiveServerFrame(
+ JSON.stringify({
+ op: 'created',
+ reqId,
+ info: {
+ threadId: 'thread-1',
+ agent: { source: 'custom', id: 'agent', name: 'Agent' },
+ title: 'Agent',
+ status: 'sleeping',
+ createdAt: 1,
+ lastActivityAt: 1,
+ lastSeq: -1,
+ },
+ }),
+ );
+
+ await expect(pending).resolves.toMatchObject({ threadId: 'thread-1', status: 'sleeping' });
+ expect(created).toHaveBeenCalledWith(expect.objectContaining({ threadId: 'thread-1' }));
+ });
+
+ test('a creation callback failure still starts and lists the thread the server created', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const client = new AgentThreadClient();
+ const sent: Array<Record<string, unknown>> = [];
+ const internals = client as unknown as { ws: unknown };
+ internals.ws = {
+ readyState: WebSocket.OPEN,
+ send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
+ };
+ const callbackFailure = new Error('creation callback failed');
+ const pending = client.createThread({ agent: { source: 'custom', id: 'agent' } }, () => {
+ throw callbackFailure;
+ });
+ await Promise.resolve();
+ const reqId = sent.find((frame) => frame.op === 'create')?.reqId;
+ expect(typeof reqId).toBe('string');
+
+ expect(() =>
+ client.receiveServerFrame(
+ JSON.stringify({
+ op: 'created',
+ reqId,
+ info: {
+ threadId: 'thread-1',
+ agent: { source: 'custom', id: 'agent', name: 'Agent' },
+ title: 'Agent',
+ status: 'ready',
+ createdAt: 1,
+ lastActivityAt: 1,
+ lastSeq: -1,
+ },
+ }),
+ ),
+ ).not.toThrow();
+ await expect(pending).resolves.toMatchObject({ threadId: 'thread-1' });
+ expect(client.getThread('thread-1')?.info.threadId).toBe('thread-1');
+ expect(error).toHaveBeenCalledWith(
+ '[agent-threads] created-thread callback failed for',
+ 'thread-1',
+ callbackFailure,
+ );
+ } finally {
+ error.mockRestore();
+ }
+ });
+
test('rejects with ThreadChannelUnavailableError when no URL is ever bound', async () => {
const client = new AgentThreadClient();
const waitFor = (
diff --git a/packages/app/src/lib/acp/thread-client.ts b/packages/app/src/lib/acp/thread-client.ts
index 6f950dbdc..866769027 100644
--- a/packages/app/src/lib/acp/thread-client.ts
+++ b/packages/app/src/lib/acp/thread-client.ts
@@ -35,6 +35,10 @@ interface PendingCreate {
timer: ReturnType<typeof setTimeout>;
}
+interface PendingThreadCreate extends PendingCreate {
+ onCreated?: (info: ThreadInfo) => void;
+}
+
interface PendingTerminalAuthLaunch {
resolve: (launch: ThreadAuthTerminalLaunch) => void;
reject: (err: Error) => void;
@@ -47,6 +51,28 @@ interface PendingQueueEdit {
timer: ReturnType<typeof setTimeout>;
}
+function invalidCreatedThreadInfoField(value: unknown): string | null {
+ if (typeof value !== 'object' || value === null) return 'info';
+ const info = value as Partial<ThreadInfo>;
+ if (typeof info.threadId !== 'string' || info.threadId.length === 0) return 'threadId';
+ const agent = info.agent;
+ if (typeof agent !== 'object' || agent === null) return 'agent';
+ if (typeof agent.id !== 'string') return 'agent.id';
+ if (typeof agent.name !== 'string') return 'agent.name';
+ if (agent.source !== 'custom' && agent.source !== 'registry') return 'agent.source';
+ if (typeof info.title !== 'string') return 'title';
+ if (typeof info.status !== 'string') return 'status';
+ if (typeof info.createdAt !== 'number') return 'createdAt';
+ if (typeof info.lastActivityAt !== 'number') return 'lastActivityAt';
+ if (typeof info.lastSeq !== 'number') return 'lastSeq';
+ return null;
+}
+
+function createdThreadIdOf(value: unknown): string | null {
+ if (typeof value !== 'object' || value === null || !('threadId' in value)) return null;
+ return typeof value.threadId === 'string' ? value.threadId : null;
+}
+
const SEQ_GAP_EVENT: ThreadEvent = Object.freeze({
kind: 'agent_stderr',
line: '[missing log entry]',
@@ -103,7 +129,7 @@ export class AgentThreadClient {
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private threads = new Map<string, ThreadState>();
private listeners = new Set<() => void>();
- private pendingCreates = new Map<string, PendingCreate>();
+ private pendingCreates = new Map<string, PendingThreadCreate>();
private pendingResumes = new Map<string, PendingCreate>();
private pendingRetries = new Map<string, PendingCreate>();
private pendingTerminalAuthLaunches = new Map<string, PendingTerminalAuthLaunch>();
@@ -114,6 +140,7 @@ export class AgentThreadClient {
private lastViewedByThread = new Map<string, number>();
private resumingThreads = new Set<string>();
private reqCounter = 0;
+ private connectionGeneration = 0;
private status: ThreadConnectionStatus = 'idle';
private version = 0;
private initialRosterIds: ReadonlySet<string> | null = null;
@@ -198,15 +225,20 @@ export class AgentThreadClient {
getConnectionStatus = (): ThreadConnectionStatus => this.status;
+ getConnectionGeneration = (): number => this.connectionGeneration;
+
getThreadScope = (): string | null => this.url;
- async createThread(params: {
- agent: { source: 'registry' | 'custom'; id: string };
- prompt?: string;
- attachments?: readonly AttachmentPart[];
- docName?: string;
- titleHint?: string;
- }): Promise<ThreadInfo> {
+ async createThread(
+ params: {
+ agent: { source: 'registry' | 'custom'; id: string };
+ prompt?: string;
+ attachments?: readonly AttachmentPart[];
+ docName?: string;
+ titleHint?: string;
+ },
+ onCreated?: (info: ThreadInfo) => void,
+ ): Promise<ThreadInfo> {
this.connectNow();
await this.waitForOpen(CHANNEL_WAIT_MS);
this.reqCounter += 1;
@@ -216,7 +248,7 @@ export class AgentThreadClient {
this.pendingCreates.delete(reqId);
reject(new Error('thread creation timed out'));
}, CREATE_TIMEOUT_MS);
- this.pendingCreates.set(reqId, { resolve, reject, timer });
+ this.pendingCreates.set(reqId, { resolve, reject, timer, onCreated });
});
const settingsKey = agentSettingsKey(params.agent);
const config = getRememberedAgentConfig(settingsKey);
@@ -507,6 +539,7 @@ export class AgentThreadClient {
this.scheduleReconnect();
return;
}
+ this.connectionGeneration += 1;
this.ws = ws;
ws.onopen = () => {
if (this.ws !== ws) return;
@@ -614,9 +647,32 @@ export class AgentThreadClient {
switch (frame.op) {
case 'created': {
const pending = this.pendingCreates.get(frame.reqId);
+ const invalidField = invalidCreatedThreadInfoField(frame.info);
+ if (invalidField !== null) {
+ console.warn('[agent-threads] invalid created thread info', {
+ field: invalidField,
+ threadId: createdThreadIdOf(frame.info),
+ reqId: frame.reqId,
+ });
+ if (pending !== undefined) {
+ this.pendingCreates.delete(frame.reqId);
+ clearTimeout(pending.timer);
+ pending.reject(new Error(`invalid created thread info: ${invalidField}`));
+ }
+ return;
+ }
if (pending !== undefined) {
this.pendingCreates.delete(frame.reqId);
clearTimeout(pending.timer);
+ try {
+ pending.onCreated?.(frame.info);
+ } catch (error) {
+ console.error(
+ '[agent-threads] created-thread callback failed for',
+ frame.info.threadId,
+ error,
+ );
+ }
pending.resolve(frame.info);
}
this.upsertInfo(frame.info);
diff --git a/packages/app/src/lib/acp/use-preferred-session-selection.ts b/packages/app/src/lib/acp/use-preferred-session-selection.ts
new file mode 100644
index 000000000..fd13e2b0b
--- /dev/null
+++ b/packages/app/src/lib/acp/use-preferred-session-selection.ts
@@ -0,0 +1,46 @@
+import type { TerminalCli } from '@inkeep/open-knowledge-core/handoff';
+import { usePreferBareTerminal } from '../terminal-new-tab-store';
+import { useStickyAgent } from '../unified-agent-store';
+import { useEnabledOverrides } from './enabled-agents';
+import {
+ enabledTerminalClis,
+ enabledThreadAgents,
+ resolveLauncherSelection,
+} from './launcher-selection';
+import {
+ pickEffectiveDefaultAgent,
+ useDefaultRegisteredAgent,
+ useRegisteredAgents,
+} from './registered-agents';
+
+export function usePreferredSessionSelection({
+ installedClis,
+ terminalAvailable,
+ threadsAvailable,
+}: {
+ installedClis: Partial<Record<TerminalCli, boolean>>;
+ terminalAvailable: boolean;
+ threadsAvailable: boolean;
+}) {
+ const registeredAgents = useRegisteredAgents();
+ const defaultRegisteredAgent = useDefaultRegisteredAgent();
+ const enabledOverrides = useEnabledOverrides();
+ const sticky = useStickyAgent();
+ const preferBareTerminal = usePreferBareTerminal();
+
+ return resolveLauncherSelection({
+ sticky,
+ effectiveThreadAgent: pickEffectiveDefaultAgent(
+ enabledThreadAgents(registeredAgents, enabledOverrides),
+ defaultRegisteredAgent,
+ ),
+ enabledClis: enabledTerminalClis(enabledOverrides, installedClis),
+ enabledDesktopTargets: [],
+ installedClis,
+ terminalAvailable,
+ threadsAvailable,
+ desktopSelectable: false,
+ preferBareTerminal,
+ bareTerminalFallback: true,
+ });
+}
diff --git a/packages/app/src/lib/auth-prompt-store.ts b/packages/app/src/lib/auth-prompt-store.ts
index f6ca2dd5f..56dc5a422 100644
--- a/packages/app/src/lib/auth-prompt-store.ts
+++ b/packages/app/src/lib/auth-prompt-store.ts
@@ -1,28 +1,30 @@
+export type AuthPromptStep = 'auth' | 'identity';
+
export interface AuthPromptStore {
- request(): void;
+ request(step?: AuthPromptStep): void;
clear(): void;
- getSnapshot(): boolean;
+ getSnapshot(): AuthPromptStep | null;
subscribe(listener: () => void): () => void;
}
function createAuthPromptStore(): AuthPromptStore {
- let pending = false;
+ let pending: AuthPromptStep | null = null;
const listeners = new Set<() => void>();
- function set(next: boolean): void {
+ function set(next: AuthPromptStep | null): void {
if (pending === next) return;
pending = next;
for (const l of listeners) l();
}
return {
- request(): void {
- set(true);
+ request(step: AuthPromptStep = 'auth'): void {
+ set(step);
},
clear(): void {
- set(false);
+ set(null);
},
- getSnapshot(): boolean {
+ getSnapshot(): AuthPromptStep | null {
return pending;
},
subscribe(listener): () => void {
diff --git a/packages/app/src/lib/color-themes.test.ts b/packages/app/src/lib/color-themes.test.ts
index a72182784..381818f0e 100644
--- a/packages/app/src/lib/color-themes.test.ts
+++ b/packages/app/src/lib/color-themes.test.ts
@@ -1,7 +1,13 @@
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { BASE16_SLOTS, ConfigSchema, resolveLeafSchema } from '@inkeep/open-knowledge-core';
+import {
+ BASE16_SLOTS,
+ ConfigSchema,
+ resolveLeafSchema,
+ SIDEBAR_BG_DARK,
+ SIDEBAR_BG_LIGHT,
+} from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
import {
base16ToTokens,
@@ -151,6 +157,14 @@ describe('defaultThemeTokens', () => {
expect(dark[name], name).not.toBe(light[name]);
}
});
+
+ test('the default dark theme swatch uses the sidebar rather than the frame color', () => {
+ expect(defaultThemeTokens('dark').sidebar).toBe(SIDEBAR_BG_DARK);
+ });
+
+ test('the default light theme swatch uses the sidebar rather than the frame color', () => {
+ expect(defaultThemeTokens('light').sidebar).toBe(SIDEBAR_BG_LIGHT);
+ });
});
describe('generated stylesheet', () => {
diff --git a/packages/app/src/lib/color-themes.ts b/packages/app/src/lib/color-themes.ts
index dc7f30eb7..df977553f 100644
--- a/packages/app/src/lib/color-themes.ts
+++ b/packages/app/src/lib/color-themes.ts
@@ -1,4 +1,4 @@
-import { CHROME_BG_DARK, CHROME_BG_LIGHT } from '@inkeep/open-knowledge-core/constants/chrome';
+import { SIDEBAR_BG_DARK, SIDEBAR_BG_LIGHT } from '@inkeep/open-knowledge-core/constants/chrome';
import { PREVIEW_THEME_TOKENS } from '@inkeep/open-knowledge-core/constants/preview-theme-tokens';
import {
BASE16_SLOTS,
@@ -75,7 +75,7 @@ function baseToken(name: string, mode: 'light' | 'dark'): string {
export function defaultThemeTokens(mode: 'light' | 'dark'): Record<string, string> {
return {
- sidebar: mode === 'dark' ? CHROME_BG_DARK : CHROME_BG_LIGHT,
+ sidebar: mode === 'dark' ? SIDEBAR_BG_DARK : SIDEBAR_BG_LIGHT,
background: baseToken('--background', mode),
primary: baseToken('--primary', mode),
border: baseToken('--border', mode),
diff --git a/packages/app/src/lib/command-menu-parity.uncached.test.ts b/packages/app/src/lib/command-menu-parity.uncached.test.ts
index a267e68c8..1f91468ad 100644
--- a/packages/app/src/lib/command-menu-parity.uncached.test.ts
+++ b/packages/app/src/lib/command-menu-parity.uncached.test.ts
@@ -82,6 +82,8 @@ const PALETTE_COMMAND_LABELS = new Set<string>([
'Move Terminal to bottom',
'Show Agents',
'Hide Agents',
+ 'Show Editor',
+ 'Hide Editor',
'Show hidden files',
'Show .ok folders',
'Show only markdown files',
@@ -163,6 +165,8 @@ function makeFullDeps(): MenuDeps {
terminalLive: true,
agentPanelVisible: true,
onToggleAgentPanel: noop,
+ editorVisible: true,
+ onToggleEditor: noop,
canExpandAll: true,
canCollapseAll: true,
onExpandAll: noop,
diff --git a/packages/app/src/lib/editor-hidden-focus.ts b/packages/app/src/lib/editor-hidden-focus.ts
new file mode 100644
index 000000000..95ccaa6b0
--- /dev/null
+++ b/packages/app/src/lib/editor-hidden-focus.ts
@@ -0,0 +1,19 @@
+const EDITOR_HIDDEN_FOCUS_TARGETS = [
+ '[data-nothing-open]',
+ '[data-header-pane-button="editor"]',
+] as const;
+
+export function focusAwayFromHiddenEditor(): void {
+ for (const selector of EDITOR_HIDDEN_FOCUS_TARGETS) {
+ const target = document.querySelector<HTMLElement>(selector);
+ if (target == null) continue;
+ target.focus();
+ if (document.activeElement === target) return;
+ }
+}
+
+export function focusWaitsForEditor(): boolean {
+ const active = document.activeElement;
+ if (active == null || active === document.body) return true;
+ return EDITOR_HIDDEN_FOCUS_TARGETS.some((selector) => active.closest(selector) != null);
+}
diff --git a/packages/app/src/lib/editor-sidebar-fit.test.ts b/packages/app/src/lib/editor-sidebar-fit.test.ts
new file mode 100644
index 000000000..32eb11974
--- /dev/null
+++ b/packages/app/src/lib/editor-sidebar-fit.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, test } from 'vitest';
+import { resolveEditorSidebarFit } from './editor-sidebar-fit';
+
+const bothRequested = {
+ filesWidthPx: 288,
+ informationWidthPx: 320,
+ documentMinimumPx: 300,
+ filesOpen: true,
+ informationOpen: true,
+ preferred: null,
+} as const;
+
+describe('editor sidebar fitting', () => {
+ test('both widths and the information divider must fit beside the usable document', () => {
+ expect(resolveEditorSidebarFit({ ...bothRequested, widthPx: 909 })).toEqual({
+ mode: 'both',
+ filesDocked: true,
+ informationDocked: true,
+ });
+ expect(resolveEditorSidebarFit({ ...bothRequested, widthPx: 908 })).toEqual({
+ mode: 'single',
+ filesDocked: true,
+ informationDocked: false,
+ });
+ expect(resolveEditorSidebarFit({ ...bothRequested, widthPx: 621 })).toEqual({
+ mode: 'single',
+ filesDocked: true,
+ informationDocked: false,
+ });
+ expect(resolveEditorSidebarFit({ ...bothRequested, widthPx: 620 })).toEqual({
+ mode: 'cover',
+ filesDocked: false,
+ informationDocked: false,
+ });
+ });
+
+ test('the requested sidebar wins constrained docking while both can return at sufficient width', () => {
+ expect(
+ resolveEditorSidebarFit({ ...bothRequested, widthPx: 800, preferred: 'information' }),
+ ).toEqual({ mode: 'single', filesDocked: false, informationDocked: true });
+ expect(resolveEditorSidebarFit({ ...bothRequested, widthPx: 800, preferred: 'files' })).toEqual(
+ { mode: 'single', filesDocked: true, informationDocked: false },
+ );
+ expect(
+ resolveEditorSidebarFit({ ...bothRequested, widthPx: 909, preferred: 'information' }),
+ ).toEqual({ mode: 'both', filesDocked: true, informationDocked: true });
+ });
+
+ test('a wider remembered information panel puts both sidebars in cover mode even when Files alone fits', () => {
+ expect(
+ resolveEditorSidebarFit({ ...bothRequested, informationWidthPx: 600, widthPx: 800 }),
+ ).toEqual({ mode: 'cover', filesDocked: false, informationDocked: false });
+ expect(
+ resolveEditorSidebarFit({ ...bothRequested, informationWidthPx: 600, widthPx: 901 }),
+ ).toEqual({ mode: 'single', filesDocked: true, informationDocked: false });
+ });
+
+ test('an absent sidebar contributes no fitting budget and an explicitly hidden sidebar stays hidden', () => {
+ expect(resolveEditorSidebarFit({ ...bothRequested, filesWidthPx: null, widthPx: 621 })).toEqual(
+ { mode: 'both', filesDocked: false, informationDocked: true },
+ );
+ expect(resolveEditorSidebarFit({ ...bothRequested, filesOpen: false, widthPx: 800 })).toEqual({
+ mode: 'single',
+ filesDocked: false,
+ informationDocked: true,
+ });
+ expect(
+ resolveEditorSidebarFit({ ...bothRequested, informationOpen: false, widthPx: 909 }),
+ ).toEqual({ mode: 'both', filesDocked: true, informationDocked: false });
+ });
+});
diff --git a/packages/app/src/lib/editor-sidebar-fit.ts b/packages/app/src/lib/editor-sidebar-fit.ts
new file mode 100644
index 000000000..85a46c2cb
--- /dev/null
+++ b/packages/app/src/lib/editor-sidebar-fit.ts
@@ -0,0 +1,43 @@
+export type EditorSidebar = 'files' | 'information';
+
+export type EditorSidebarFit =
+ | { mode: 'cover'; filesDocked: false; informationDocked: false }
+ | { mode: 'both' | 'single'; filesDocked: boolean; informationDocked: boolean };
+
+interface EditorSidebarFitInput {
+ widthPx: number | null;
+ filesWidthPx: number | null;
+ informationWidthPx: number | null;
+ documentMinimumPx: number;
+ filesOpen: boolean;
+ informationOpen: boolean;
+ preferred: EditorSidebar | null;
+}
+
+export function resolveEditorSidebarFit({
+ widthPx,
+ filesWidthPx,
+ informationWidthPx,
+ documentMinimumPx,
+ filesOpen,
+ informationOpen,
+ preferred,
+}: EditorSidebarFitInput): EditorSidebarFit {
+ const filesPresent = filesWidthPx != null;
+ const informationPresent = informationWidthPx != null;
+ const availablePx = widthPx == null ? Infinity : widthPx - documentMinimumPx;
+ const filesRequiredPx = filesWidthPx ?? 0;
+ const informationRequiredPx = informationPresent ? informationWidthPx + 1 : 0;
+ if (availablePx < Math.max(filesRequiredPx, informationRequiredPx)) {
+ return { mode: 'cover', filesDocked: false, informationDocked: false };
+ }
+ const filesWanted = filesPresent && filesOpen;
+ const informationWanted = informationPresent && informationOpen;
+ const bothFit = availablePx >= filesRequiredPx + informationRequiredPx;
+ return {
+ mode: bothFit ? 'both' : 'single',
+ filesDocked: filesWanted && (bothFit || !informationWanted || preferred !== 'information'),
+ informationDocked:
+ informationWanted && (bothFit || !filesWanted || preferred === 'information'),
+ };
+}
diff --git a/packages/app/src/lib/feedback-nudge-store.test.ts b/packages/app/src/lib/feedback-nudge-store.test.ts
index e0f834e78..a955bb10c 100644
--- a/packages/app/src/lib/feedback-nudge-store.test.ts
+++ b/packages/app/src/lib/feedback-nudge-store.test.ts
@@ -254,3 +254,17 @@ describe('createFeedbackNudgeStore', () => {
expect(notified).toBeGreaterThan(0);
});
});
+
+describe('feedback state saved by earlier releases', () => {
+ test('the storage key is still ok-feedback-nudge-v1', () => {
+ expect(FEEDBACK_NUDGE_STORAGE_KEY).toBe('ok-feedback-nudge-v1');
+ });
+
+ test('a prompt already shown and dismissed reads back unchanged and stays ineligible', () => {
+ const stored = { firstSeenAt: 1_790_000_000_000, shownAt: 1_791_500_000_000, dismissed: true };
+ const s = memoryStorage({ 'ok-feedback-nudge-v1': JSON.stringify(stored) });
+ const read = readPersistedState(s);
+ expect(read).toEqual(stored);
+ expect(isFeedbackNudgeEligible(read, NOW, 400)).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/install-deep-link-listener.test.ts b/packages/app/src/lib/install-deep-link-listener.test.ts
index 23f400462..01d9026fd 100644
--- a/packages/app/src/lib/install-deep-link-listener.test.ts
+++ b/packages/app/src/lib/install-deep-link-listener.test.ts
@@ -1,5 +1,10 @@
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { normalizeTargetPath } from '@/components/navigation-targets';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from '@/lib/pane-visibility-store';
import { missDialogStore } from '@/lib/share/miss-dialog-store';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
import type { OkDeepLinkPayload, OkDesktopBridge, OkDesktopConfig } from './desktop-bridge-types';
@@ -269,6 +274,36 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
});
});
+describe('installDeepLinkListener — a hidden editor', () => {
+ beforeEach(() => {
+ __resetPaneVisibilityStoreForTests();
+ });
+
+ afterEach(() => {
+ __resetPaneVisibilityStoreForTests();
+ pendingReceiveNavStore.clear();
+ });
+
+ test.each<{ share: string; payload: DeepLinkPayload; hash: string }>([
+ { share: 'doc', payload: { doc: 'intro.md', kind: 'doc' }, hash: '#/intro.md' },
+ { share: 'folder', payload: { doc: 'docs/sub', kind: 'folder' }, hash: '#/docs/sub/' },
+ ])('a $share deep link shows a hidden editor before navigating to it', ({ payload, hash }) => {
+ const log: Array<PaneVisibilityRequest | string> = [];
+ paneVisibilityStore.subscribeRequests((request) => log.push(request));
+ paneVisibilityStore.publish({
+ editor: { open: false, onScreen: false },
+ agents: null,
+ terminal: null,
+ });
+ const bridge = makeBridge();
+ installDeepLinkListener({ bridge, setHash: (next) => log.push(`navigate ${next}`) });
+
+ bridge.fireDeepLink(payload);
+
+ expect(log).toEqual([{ pane: 'editor', open: true }, `navigate ${hash}`]);
+ });
+});
+
describe('deriveShareReceiveToast (FR9)', () => {
test('returns payload with branch + projectPath when multiCandidate is true', () => {
expect(
diff --git a/packages/app/src/lib/install-deep-link-listener.ts b/packages/app/src/lib/install-deep-link-listener.ts
index 75a775365..34a2458af 100644
--- a/packages/app/src/lib/install-deep-link-listener.ts
+++ b/packages/app/src/lib/install-deep-link-listener.ts
@@ -2,6 +2,7 @@ import { t } from '@lingui/core/macro';
import { toast } from 'sonner';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { encodeShareTargetForHash } from '@/lib/doc-hash';
+import { revealEditor } from '@/lib/reveal-editor';
import { missDialogStore } from '@/lib/share/miss-dialog-store';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
@@ -55,6 +56,7 @@ export function installDeepLinkListener(
return;
}
pendingReceiveNavStore.arm(nav);
+ revealEditor();
setHash(encodeShareTargetForHash(kind, evt.doc, kind === 'doc' ? evt.branch : undefined));
const payload = deriveShareReceiveToast(evt, bridge.config.projectPath);
if (payload !== null) {
diff --git a/packages/app/src/lib/narrow-workspace-session.dom.test.ts b/packages/app/src/lib/narrow-workspace-session.dom.test.ts
new file mode 100644
index 000000000..db9d1bc89
--- /dev/null
+++ b/packages/app/src/lib/narrow-workspace-session.dom.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ readNarrowWorkspaceSession,
+ writeNarrowWorkspaceSession,
+} from './narrow-workspace-session';
+
+const KEY = 'narrow-session-reader-test';
+
+afterEach(() => {
+ window.sessionStorage.clear();
+});
+
+describe('readNarrowWorkspaceSession', () => {
+ test('reads back a record its writer produced', () => {
+ const session = {
+ selected: 'agents' as const,
+ lastInteracted: 'agents' as const,
+ recent: ['agents' as const, 'editor' as const],
+ hidden: ['terminal' as const],
+ };
+ writeNarrowWorkspaceSession(KEY, session);
+
+ expect(readNarrowWorkspaceSession(KEY, true)).toEqual(session);
+ });
+
+ test('rejects a record whose selected pane is also hidden', () => {
+ window.sessionStorage.setItem(
+ KEY,
+ JSON.stringify({
+ version: 1,
+ selected: 'editor',
+ lastInteracted: 'editor',
+ recent: ['editor'],
+ hidden: ['editor'],
+ }),
+ );
+
+ expect(readNarrowWorkspaceSession(KEY, true)).toBeUndefined();
+ });
+});
diff --git a/packages/app/src/lib/narrow-workspace-session.ts b/packages/app/src/lib/narrow-workspace-session.ts
new file mode 100644
index 000000000..7d04d6173
--- /dev/null
+++ b/packages/app/src/lib/narrow-workspace-session.ts
@@ -0,0 +1,65 @@
+import { docNameFromHash } from '@/lib/doc-hash';
+import { isPaneId, type PaneId } from '@/lib/pane-visibility-store';
+import { scopedStorageKey } from '@/lib/storage-scope';
+
+const STORAGE_KEY = 'ok-narrow-workspace-v1';
+
+export interface NarrowWorkspaceSession {
+ selected: PaneId | null;
+ lastInteracted: PaneId | null;
+ recent: PaneId[];
+ hidden: PaneId[];
+}
+
+function isPaneList(value: unknown): value is PaneId[] {
+ return Array.isArray(value) && value.every(isPaneId) && new Set(value).size === value.length;
+}
+
+export function narrowWorkspaceSessionKey(namespace: string, host: 'desktop' | 'web'): string {
+ return scopedStorageKey(STORAGE_KEY, `${host}:${namespace}`);
+}
+
+export function readNarrowWorkspaceSession(
+ key: string,
+ terminalAvailable: boolean,
+): NarrowWorkspaceSession | undefined {
+ try {
+ const raw = window.sessionStorage.getItem(key);
+ if (raw === null) return undefined;
+ const value: unknown = JSON.parse(raw);
+ if (typeof value !== 'object' || value === null || !('version' in value)) return undefined;
+ if (value.version !== 1 || !('selected' in value)) return undefined;
+ if (value.selected !== null && !isPaneId(value.selected)) return undefined;
+ if (value.selected === 'terminal' && !terminalAvailable) return undefined;
+ const recent = 'recent' in value ? value.recent : [];
+ const hidden = 'hidden' in value ? value.hidden : [];
+ const lastInteracted = 'lastInteracted' in value ? value.lastInteracted : value.selected;
+ if (!isPaneList(recent) || !isPaneList(hidden)) return undefined;
+ if (value.selected !== null && hidden.includes(value.selected)) return undefined;
+ if (lastInteracted !== null && !isPaneId(lastInteracted)) return undefined;
+ return {
+ selected: value.selected,
+ lastInteracted: lastInteracted === 'terminal' && !terminalAvailable ? null : lastInteracted,
+ recent: terminalAvailable ? recent : recent.filter((pane) => pane !== 'terminal'),
+ hidden: terminalAvailable ? hidden : hidden.filter((pane) => pane !== 'terminal'),
+ };
+ } catch {
+ return undefined;
+ }
+}
+
+export function writeNarrowWorkspaceSession(key: string, session: NarrowWorkspaceSession): void {
+ try {
+ window.sessionStorage.setItem(key, JSON.stringify({ version: 1, ...session }));
+ } catch {}
+}
+
+export function isExplicitInitialDocumentNavigation(): boolean {
+ const navigation = window.performance.getEntriesByType('navigation')[0];
+ return (
+ navigation !== undefined &&
+ 'type' in navigation &&
+ navigation.type === 'navigate' &&
+ docNameFromHash(window.location.hash) !== null
+ );
+}
diff --git a/packages/app/src/lib/ok-menu-actions.ts b/packages/app/src/lib/ok-menu-actions.ts
index 14abb93ca..4ff9a0d5c 100644
--- a/packages/app/src/lib/ok-menu-actions.ts
+++ b/packages/app/src/lib/ok-menu-actions.ts
@@ -32,6 +32,7 @@ export const OK_MENU_ACTIONS = [
'toggle-terminal',
'move-terminal',
'toggle-agent-panel',
+ 'toggle-editor',
'new-terminal',
'kill-terminal',
'new-worktree',
diff --git a/packages/app/src/lib/onboarding-card-store.test.ts b/packages/app/src/lib/onboarding-card-store.test.ts
index 4adbc47c6..297002b6d 100644
--- a/packages/app/src/lib/onboarding-card-store.test.ts
+++ b/packages/app/src/lib/onboarding-card-store.test.ts
@@ -307,3 +307,39 @@ describe('createOnboardingCardStore — install', () => {
expect(() => createOnboardingCardStore().install()).not.toThrow();
});
});
+
+describe('onboarding state saved by earlier releases', () => {
+ test('the storage key is still ok-onboarding-card-v1', () => {
+ expect(ONBOARDING_CARD_STORAGE_KEY).toBe('ok-onboarding-card-v1');
+ });
+
+ test('a saved checklist reads back unchanged', () => {
+ const stored = {
+ initialized: true,
+ steps: { file: true, askedAi: false },
+ fileBaseline: 4,
+ dismissed: true,
+ completed: false,
+ };
+ const s = memoryStorage({ 'ok-onboarding-card-v1': JSON.stringify(stored) });
+ expect(readPersistedState(s)).toEqual(stored);
+ });
+
+ test('a finished checklist reads back with every saved flag set', () => {
+ const stored = {
+ initialized: true,
+ steps: { file: true, askedAi: true },
+ fileBaseline: 7,
+ dismissed: true,
+ completed: true,
+ };
+ const s = memoryStorage({ 'ok-onboarding-card-v1': JSON.stringify(stored) });
+ const read = readPersistedState(s);
+ expect(read).toEqual(stored);
+ expect(read.initialized).toBe(true);
+ expect(read.steps.file).toBe(true);
+ expect(read.steps.askedAi).toBe(true);
+ expect(read.dismissed).toBe(true);
+ expect(read.completed).toBe(true);
+ });
+});
diff --git a/packages/app/src/lib/pane-visibility-store.test.ts b/packages/app/src/lib/pane-visibility-store.test.ts
new file mode 100644
index 000000000..9cdbcfb97
--- /dev/null
+++ b/packages/app/src/lib/pane-visibility-store.test.ts
@@ -0,0 +1,292 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneId,
+ type PaneVisibility,
+ type PaneVisibilityRequest,
+ type PaneVisibilitySnapshot,
+ paneVisibilityStore,
+} from './pane-visibility-store';
+
+const HIDDEN: PaneVisibility = { open: false, onScreen: false };
+const SHOWN: PaneVisibility = { open: true, onScreen: true };
+const OPEN_OFF_SCREEN: PaneVisibility = { open: true, onScreen: false };
+
+afterEach(() => {
+ __resetPaneVisibilityStoreForTests();
+ vi.unstubAllGlobals();
+});
+
+function recordingStandIn(name: string, touched: string[]): object {
+ return new Proxy(
+ {},
+ {
+ get(_target, key) {
+ touched.push(`${name}.${String(key)}`);
+ return () => undefined;
+ },
+ },
+ );
+}
+
+describe('pane-visibility-store', () => {
+ test('starts with no pane known to exist', () => {
+ expect(paneVisibilityStore.getSnapshot()).toEqual({
+ editor: null,
+ agents: null,
+ terminal: null,
+ });
+ });
+
+ test('a changed publish replaces the snapshot and notifies every subscriber exactly once', () => {
+ const seenA: PaneVisibilitySnapshot[] = [];
+ const seenB: PaneVisibilitySnapshot[] = [];
+ paneVisibilityStore.subscribe(() => seenA.push(paneVisibilityStore.getSnapshot()));
+ paneVisibilityStore.subscribe(() => seenB.push(paneVisibilityStore.getSnapshot()));
+
+ const next: PaneVisibilitySnapshot = { editor: null, agents: SHOWN, terminal: HIDDEN };
+ paneVisibilityStore.publish(next);
+
+ expect(paneVisibilityStore.getSnapshot()).toEqual(next);
+ expect(seenA).toEqual([next]);
+ expect(seenB).toEqual([next]);
+ });
+
+ test.each<[string, PaneVisibilitySnapshot, PaneVisibilitySnapshot]>([
+ [
+ 'agents opens',
+ { editor: null, agents: HIDDEN, terminal: null },
+ { editor: null, agents: SHOWN, terminal: null },
+ ],
+ [
+ 'agents goes off screen while open',
+ { editor: null, agents: SHOWN, terminal: null },
+ { editor: null, agents: OPEN_OFF_SCREEN, terminal: null },
+ ],
+ [
+ 'terminal starts existing',
+ { editor: null, agents: HIDDEN, terminal: null },
+ { editor: null, agents: HIDDEN, terminal: HIDDEN },
+ ],
+ [
+ 'terminal stops existing',
+ { editor: null, agents: HIDDEN, terminal: SHOWN },
+ { editor: null, agents: HIDDEN, terminal: null },
+ ],
+ [
+ 'terminal closes',
+ { editor: null, agents: HIDDEN, terminal: SHOWN },
+ { editor: null, agents: HIDDEN, terminal: HIDDEN },
+ ],
+ [
+ 'agents stops existing',
+ { editor: null, agents: HIDDEN, terminal: null },
+ { editor: null, agents: null, terminal: null },
+ ],
+ [
+ 'editor starts existing',
+ { editor: null, agents: HIDDEN, terminal: null },
+ { editor: SHOWN, agents: HIDDEN, terminal: null },
+ ],
+ [
+ 'editor hides',
+ { editor: SHOWN, agents: HIDDEN, terminal: null },
+ { editor: HIDDEN, agents: HIDDEN, terminal: null },
+ ],
+ ])('publishing a snapshot where %s notifies once', (_label, before, after) => {
+ paneVisibilityStore.publish(before);
+ let calls = 0;
+ paneVisibilityStore.subscribe(() => {
+ calls += 1;
+ });
+
+ paneVisibilityStore.publish(after);
+
+ expect(calls).toBe(1);
+ expect(paneVisibilityStore.getSnapshot()).toEqual(after);
+ });
+
+ test('a value-equal publish notifies nobody and keeps the snapshot identity', () => {
+ paneVisibilityStore.publish({
+ editor: null,
+ agents: { ...OPEN_OFF_SCREEN },
+ terminal: { ...HIDDEN },
+ });
+ const before = paneVisibilityStore.getSnapshot();
+ let calls = 0;
+ paneVisibilityStore.subscribe(() => {
+ calls += 1;
+ });
+
+ paneVisibilityStore.publish({
+ editor: null,
+ agents: { ...OPEN_OFF_SCREEN },
+ terminal: { ...HIDDEN },
+ });
+
+ expect(calls).toBe(0);
+ expect(paneVisibilityStore.getSnapshot()).toBe(before);
+ });
+
+ test('a publish that changes only exclusivity updates it and notifies subscribers once', () => {
+ const snapshot: PaneVisibilitySnapshot = { editor: SHOWN, agents: HIDDEN, terminal: null };
+ paneVisibilityStore.publish(snapshot, false);
+ let calls = 0;
+ paneVisibilityStore.subscribe(() => {
+ calls += 1;
+ });
+
+ paneVisibilityStore.publish({ ...snapshot }, true);
+
+ expect(paneVisibilityStore.isExclusive()).toBe(true);
+ expect(calls).toBe(1);
+ });
+
+ test('publishing the initial empty snapshot again notifies nobody', () => {
+ let calls = 0;
+ paneVisibilityStore.subscribe(() => {
+ calls += 1;
+ });
+
+ paneVisibilityStore.publish({ editor: null, agents: null, terminal: null });
+
+ expect(calls).toBe(0);
+ });
+
+ test('a request reaches every request handler before any snapshot is published', () => {
+ const seenA: PaneVisibilityRequest[] = [];
+ const seenB: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((r) => seenA.push(r));
+ paneVisibilityStore.subscribeRequests((r) => seenB.push(r));
+
+ paneVisibilityStore.request('agents', false);
+
+ expect(seenA).toEqual([{ pane: 'agents', open: false }]);
+ expect(seenB).toEqual([{ pane: 'agents', open: false }]);
+ });
+
+ test('requests carry the pane and the wanted state in order', () => {
+ const sent: Array<[PaneId, boolean]> = [
+ ['terminal', true],
+ ['agents', true],
+ ['terminal', false],
+ ['agents', false],
+ ];
+ const seen: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((r) => seen.push(r));
+
+ for (const [pane, open] of sent) paneVisibilityStore.request(pane, open);
+
+ expect(seen).toEqual([
+ { pane: 'terminal', open: true },
+ { pane: 'agents', open: true },
+ { pane: 'terminal', open: false },
+ { pane: 'agents', open: false },
+ ]);
+ });
+
+ test('a request made before any handler subscribes is handed to the first handler, once', () => {
+ paneVisibilityStore.request('editor', true);
+ const first: PaneVisibilityRequest[] = [];
+ const second: PaneVisibilityRequest[] = [];
+
+ paneVisibilityStore.subscribeRequests((r) => first.push(r));
+ paneVisibilityStore.subscribeRequests((r) => second.push(r));
+
+ expect(first).toEqual([{ pane: 'editor', open: true }]);
+ expect(second).toEqual([]);
+ });
+
+ test('a reset drops a request still waiting for a handler', () => {
+ paneVisibilityStore.request('editor', true);
+ __resetPaneVisibilityStoreForTests();
+ const seen: PaneVisibilityRequest[] = [];
+
+ paneVisibilityStore.subscribeRequests((r) => seen.push(r));
+
+ expect(seen).toEqual([]);
+ });
+
+ test('a request neither changes the snapshot nor notifies snapshot subscribers', () => {
+ const before = paneVisibilityStore.getSnapshot();
+ let calls = 0;
+ paneVisibilityStore.subscribe(() => {
+ calls += 1;
+ });
+ const seen: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((r) => seen.push(r));
+
+ paneVisibilityStore.request('agents', true);
+
+ expect(seen).toHaveLength(1);
+ expect(calls).toBe(0);
+ expect(paneVisibilityStore.getSnapshot()).toBe(before);
+ });
+
+ test('an unsubscribed snapshot listener receives nothing further', () => {
+ let calls = 0;
+ const stop = paneVisibilityStore.subscribe(() => {
+ calls += 1;
+ });
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: null });
+ expect(calls).toBe(1);
+
+ stop();
+ paneVisibilityStore.publish({ editor: null, agents: HIDDEN, terminal: null });
+
+ expect(calls).toBe(1);
+ });
+
+ test('an unsubscribed request handler receives nothing further', () => {
+ const kept: PaneVisibilityRequest[] = [];
+ const dropped: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((r) => kept.push(r));
+ const stop = paneVisibilityStore.subscribeRequests((r) => dropped.push(r));
+ paneVisibilityStore.request('agents', true);
+
+ stop();
+ paneVisibilityStore.request('agents', false);
+
+ expect(dropped).toEqual([{ pane: 'agents', open: true }]);
+ expect(kept).toEqual([
+ { pane: 'agents', open: true },
+ { pane: 'agents', open: false },
+ ]);
+ });
+
+ test('the methods work detached from the store, as useSyncExternalStore and effects call them', () => {
+ const { getSnapshot, subscribe, publish, request, subscribeRequests } = paneVisibilityStore;
+ let calls = 0;
+ subscribe(() => {
+ calls += 1;
+ });
+ const seen: PaneVisibilityRequest[] = [];
+ subscribeRequests((r) => seen.push(r));
+
+ publish({ editor: null, agents: SHOWN, terminal: null });
+ request('terminal', true);
+
+ expect(calls).toBe(1);
+ expect(getSnapshot()).toEqual({ editor: null, agents: SHOWN, terminal: null });
+ expect(seen).toEqual([{ pane: 'terminal', open: true }]);
+ });
+
+ test('publishing and requesting touch neither browser storage nor the desktop bridge', () => {
+ const touched: string[] = [];
+ const storage = recordingStandIn('localStorage', touched);
+ const okDesktop = recordingStandIn('okDesktop', touched);
+ vi.stubGlobal('localStorage', storage);
+ vi.stubGlobal('sessionStorage', recordingStandIn('sessionStorage', touched));
+ vi.stubGlobal('window', { okDesktop, localStorage: storage });
+ expect(globalThis.localStorage).toBe(storage);
+
+ paneVisibilityStore.subscribe(() => {});
+ paneVisibilityStore.subscribeRequests(() => {});
+ paneVisibilityStore.publish({ editor: null, agents: SHOWN, terminal: OPEN_OFF_SCREEN });
+ paneVisibilityStore.request('terminal', false);
+ paneVisibilityStore.request('agents', true);
+ paneVisibilityStore.getSnapshot();
+
+ expect(touched).toEqual([]);
+ });
+});
diff --git a/packages/app/src/lib/pane-visibility-store.ts b/packages/app/src/lib/pane-visibility-store.ts
new file mode 100644
index 000000000..e70b1a0e4
--- /dev/null
+++ b/packages/app/src/lib/pane-visibility-store.ts
@@ -0,0 +1,110 @@
+export type PaneId = 'editor' | 'agents' | 'terminal';
+
+export function assertNeverPaneId(pane: never): never {
+ throw new Error(`unhandled pane: ${String(pane)}`);
+}
+
+export type PaneVisibility = {
+ readonly open: boolean;
+ readonly onScreen: boolean;
+};
+
+export type PaneVisibilitySnapshot = {
+ readonly [P in PaneId]: PaneVisibility | null;
+};
+
+export type PaneVisibilityRequest = {
+ readonly pane: PaneId;
+ readonly open: boolean;
+};
+
+export interface PaneVisibilityStore {
+ getSnapshot(): PaneVisibilitySnapshot;
+ isExclusive(): boolean;
+ subscribe(listener: () => void): () => void;
+ publish(next: PaneVisibilitySnapshot, exclusive?: boolean): void;
+ request(pane: PaneId, open: boolean): void;
+ subscribeRequests(handler: (request: PaneVisibilityRequest) => void): () => void;
+}
+
+const NO_PANES: PaneVisibilitySnapshot = Object.freeze({
+ editor: null,
+ agents: null,
+ terminal: null,
+});
+
+const PANE_IDS = Object.keys(NO_PANES) as readonly PaneId[];
+
+export function isPaneId(value: unknown): value is PaneId {
+ return typeof value === 'string' && Object.hasOwn(NO_PANES, value);
+}
+
+function samePane(a: PaneVisibility | null, b: PaneVisibility | null): boolean {
+ if (a === null || b === null) return a === b;
+ return a.open === b.open && a.onScreen === b.onScreen;
+}
+
+function sameSnapshot(a: PaneVisibilitySnapshot, b: PaneVisibilitySnapshot): boolean {
+ return PANE_IDS.every((pane) => samePane(a[pane], b[pane]));
+}
+
+function createPaneVisibilityStore(): PaneVisibilityStore & { reset(): void } {
+ let snapshot: PaneVisibilitySnapshot = NO_PANES;
+ let exclusive = false;
+ const listeners = new Set<() => void>();
+ const requestHandlers = new Set<(request: PaneVisibilityRequest) => void>();
+ const waitingRequests = new Map<PaneId, PaneVisibilityRequest>();
+
+ return {
+ getSnapshot(): PaneVisibilitySnapshot {
+ return snapshot;
+ },
+ isExclusive(): boolean {
+ return exclusive;
+ },
+ subscribe(listener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ publish(next, nextExclusive = false): void {
+ if (sameSnapshot(snapshot, next) && exclusive === nextExclusive) return;
+ snapshot = next;
+ exclusive = nextExclusive;
+ for (const l of listeners) l();
+ },
+ request(pane, open): void {
+ const request: PaneVisibilityRequest = { pane, open };
+ if (requestHandlers.size === 0) {
+ waitingRequests.set(pane, request);
+ return;
+ }
+ for (const h of requestHandlers) h(request);
+ },
+ subscribeRequests(handler): () => void {
+ requestHandlers.add(handler);
+ const waiting = [...waitingRequests.values()];
+ waitingRequests.clear();
+ for (const request of waiting) handler(request);
+ return () => {
+ requestHandlers.delete(handler);
+ };
+ },
+ reset(): void {
+ snapshot = NO_PANES;
+ exclusive = false;
+ listeners.clear();
+ requestHandlers.clear();
+ waitingRequests.clear();
+ },
+ };
+}
+
+const store = createPaneVisibilityStore();
+
+export const paneVisibilityStore: PaneVisibilityStore = store;
+
+export function __resetPaneVisibilityStoreForTests(): void {
+ store.reset();
+}
diff --git a/packages/app/src/lib/preserve-subtree-scroll.ts b/packages/app/src/lib/preserve-subtree-scroll.ts
new file mode 100644
index 000000000..d3bf2c0eb
--- /dev/null
+++ b/packages/app/src/lib/preserve-subtree-scroll.ts
@@ -0,0 +1,105 @@
+interface ScrollOffset {
+ readonly top: number;
+ readonly left: number;
+}
+
+const trackedOffsets = new WeakMap<HTMLElement, Map<Element, ScrollOffset>>();
+const restoring = new WeakSet<Element>();
+const retrying = new WeakSet<HTMLElement>();
+const RESTORE_RETRY_FRAMES = 30;
+
+function offsetsFor(host: HTMLElement): Map<Element, ScrollOffset> {
+ let offsets = trackedOffsets.get(host);
+ if (offsets === undefined) {
+ offsets = new Map();
+ trackedOffsets.set(host, offsets);
+ }
+ return offsets;
+}
+
+function hasLayout(element: Element): boolean {
+ if (element.getClientRects().length > 0) return true;
+ return Array.from(element.children).some((child) => child.getClientRects().length > 0);
+}
+
+function scrollRoots(host: HTMLElement): Array<HTMLElement | ShadowRoot> {
+ const roots: Array<HTMLElement | ShadowRoot> = [host];
+ for (let index = 0; index < roots.length; index += 1) {
+ for (const element of roots[index].querySelectorAll('*')) {
+ if (element.shadowRoot) roots.push(element.shadowRoot);
+ }
+ }
+ return roots;
+}
+
+function composedContains(host: HTMLElement, element: Element): boolean {
+ let node: Node | null = element;
+ while (node) {
+ if (node === host) return true;
+ const root: Node = node.getRootNode();
+ node = node.parentNode ?? (root instanceof ShadowRoot ? root.host : null);
+ }
+ return false;
+}
+
+function recordVisibleOffsets(host: HTMLElement): void {
+ if (!hasLayout(host)) return;
+ const offsets = offsetsFor(host);
+ for (const root of scrollRoots(host)) {
+ for (const element of root.querySelectorAll('*')) {
+ if (element.scrollTop !== 0 || element.scrollLeft !== 0) {
+ offsets.set(element, { top: element.scrollTop, left: element.scrollLeft });
+ }
+ }
+ }
+}
+
+function reapplyHostScroll(host: HTMLElement, framesLeft = RESTORE_RETRY_FRAMES): void {
+ const offsets = trackedOffsets.get(host);
+ if (offsets === undefined) return;
+ let clamped = false;
+ for (const [element, offset] of offsets) {
+ if (!element.isConnected || !composedContains(host, element)) {
+ offsets.delete(element);
+ continue;
+ }
+ if (!hasLayout(element)) continue;
+ if (element.scrollTop === offset.top && element.scrollLeft === offset.left) continue;
+ restoring.add(element);
+ element.scrollTop = offset.top;
+ element.scrollLeft = offset.left;
+ if (element.scrollTop !== offset.top || element.scrollLeft !== offset.left) clamped = true;
+ }
+ if (!clamped || framesLeft <= 0 || retrying.has(host)) return;
+ retrying.add(host);
+ requestAnimationFrame(() => {
+ retrying.delete(host);
+ reapplyHostScroll(host, framesLeft - 1);
+ });
+}
+
+export function moveHostPreservingScroll(host: HTMLElement, target: Node): void {
+ recordVisibleOffsets(host);
+ target.appendChild(host);
+ reapplyHostScroll(host);
+}
+
+export function observeHostScrollRestore(host: HTMLElement, observed: Element): () => void {
+ const onScroll = (event: Event) => {
+ const element = event.target;
+ if (!(element instanceof Element) || !hasLayout(element)) return;
+ if (restoring.delete(element)) return;
+ offsetsFor(host).set(element, { top: element.scrollTop, left: element.scrollLeft });
+ };
+ const roots = scrollRoots(host);
+ for (const root of roots) root.addEventListener('scroll', onScroll, true);
+ const observer =
+ typeof ResizeObserver === 'undefined'
+ ? null
+ : new ResizeObserver(() => reapplyHostScroll(host));
+ observer?.observe(observed);
+ return () => {
+ observer?.disconnect();
+ for (const root of roots) root.removeEventListener('scroll', onScroll, true);
+ };
+}
diff --git a/packages/app/src/lib/reveal-editor.test.ts b/packages/app/src/lib/reveal-editor.test.ts
new file mode 100644
index 000000000..8499da767
--- /dev/null
+++ b/packages/app/src/lib/reveal-editor.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ __resetPaneVisibilityStoreForTests,
+ type PaneVisibility,
+ type PaneVisibilityRequest,
+ paneVisibilityStore,
+} from './pane-visibility-store';
+import { revealEditor, revealEditorBeforeActing } from './reveal-editor';
+
+const SHOWN: PaneVisibility = { open: true, onScreen: true };
+const HIDDEN: PaneVisibility = { open: false, onScreen: false };
+
+function recordRequests(): PaneVisibilityRequest[] {
+ const requests: PaneVisibilityRequest[] = [];
+ paneVisibilityStore.subscribeRequests((request) => requests.push(request));
+ return requests;
+}
+
+afterEach(() => __resetPaneVisibilityStoreForTests());
+
+describe('revealing the editor', () => {
+ test('every reveal is handed to the editor, whether it reads hidden or shown', () => {
+ const requests = recordRequests();
+ paneVisibilityStore.publish({ editor: SHOWN, agents: null, terminal: null });
+ revealEditor();
+ revealEditorBeforeActing();
+
+ paneVisibilityStore.publish({ editor: HIDDEN, agents: null, terminal: null });
+ revealEditor();
+ revealEditorBeforeActing();
+
+ expect(requests).toEqual([
+ { pane: 'editor', open: true },
+ { pane: 'editor', open: true },
+ { pane: 'editor', open: true },
+ { pane: 'editor', open: true },
+ ]);
+ });
+});
diff --git a/packages/app/src/lib/reveal-editor.ts b/packages/app/src/lib/reveal-editor.ts
new file mode 100644
index 000000000..ce014bfed
--- /dev/null
+++ b/packages/app/src/lib/reveal-editor.ts
@@ -0,0 +1,15 @@
+import { flushSync } from 'react-dom';
+import { paneVisibilityStore } from '@/lib/pane-visibility-store';
+
+function editorHidden(): boolean {
+ return paneVisibilityStore.getSnapshot().editor?.open === false;
+}
+
+export function revealEditor(): void {
+ paneVisibilityStore.request('editor', true);
+}
+
+export function revealEditorBeforeActing(): void {
+ if (editorHidden()) flushSync(revealEditor);
+ else revealEditor();
+}
diff --git a/packages/app/src/lib/sidebar-pin-store.test.ts b/packages/app/src/lib/sidebar-pin-store.test.ts
index 6fd374740..b35bc2c80 100644
--- a/packages/app/src/lib/sidebar-pin-store.test.ts
+++ b/packages/app/src/lib/sidebar-pin-store.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'vitest';
import {
- applyToggle,
+ applyToggleAtEveryWidth,
+ openIntentAfterPartitionChange,
type PinStorage,
readPins,
resolveEffectiveState,
@@ -139,76 +140,44 @@ describe('resolveEffectiveState (Per-Partition Pins)', () => {
});
});
-describe('applyToggle (per-partition slot)', () => {
- test('sets slot for current partition', () => {
- const s = memoryStorage();
- applyToggle('left', 'above', 'collapsed', s);
- expect(readPins(s)).toEqual({ left: { above: 'collapsed' } });
- });
-
- test('toggling in a NEW partition preserves the existing slot for the OTHER partition', () => {
- const s = memoryStorage();
- applyToggle('left', 'above', 'collapsed', s);
- applyToggle('left', 'below', 'open', s);
- expect(readPins(s)).toEqual({
- left: { above: 'collapsed', below: 'open' },
- });
- });
-
- test('toggling the SAME partition overwrites only that slot', () => {
- const s = memoryStorage();
- applyToggle('left', 'above', 'collapsed', s);
- applyToggle('left', 'above', 'open', s);
- expect(readPins(s)).toEqual({ left: { above: 'open' } });
- });
-
- test('embedded slot is independent from above/below', () => {
- const s = memoryStorage();
- applyToggle('left', 'above', 'collapsed', s);
- applyToggle('left', 'below', 'open', s);
- applyToggle('left', 'embedded', 'open', s);
- expect(readPins(s)).toEqual({
- left: { above: 'collapsed', below: 'open', embedded: 'open' },
+describe('applyToggleAtEveryWidth', () => {
+ test('writes the same state to every partition of one side, replacing its earlier slots', () => {
+ const s = memoryStorage({
+ [SIDEBAR_PINS_KEY]: JSON.stringify({ left: { above: 'open' }, right: { below: 'open' } }),
});
- });
-
- test('toggle on one side does not affect the other', () => {
- const s = memoryStorage();
- applyToggle('left', 'above', 'collapsed', s);
- applyToggle('right', 'below', 'open', s);
+ applyToggleAtEveryWidth('left', 'collapsed', s);
expect(readPins(s)).toEqual({
- left: { above: 'collapsed' },
+ left: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' },
right: { below: 'open' },
});
});
- test('scenario: pin-then-cross-threshold uses smart default for new partition', () => {
- const s = memoryStorage();
- applyToggle('left', 'above', 'collapsed', s);
- const pins = readPins(s);
- expect(resolveEffectiveState('left', 'below', pins)).toBe('collapsed');
- });
-
- test('scenario: pin in narrow survives a wide round-trip (the D13 canary)', () => {
- const s = memoryStorage();
- applyToggle('right', 'below', 'open', s);
- applyToggle('right', 'above', 'collapsed', s);
- const pins = readPins(s);
- expect(resolveEffectiveState('right', 'below', pins)).toBe('open');
- expect(resolveEffectiveState('right', 'above', pins)).toBe('collapsed');
- expect(pins).toEqual({
- right: { above: 'collapsed', below: 'open' },
- });
- });
-
- test('applyToggle returns the merged pins even when storage.setItem throws (quota exceeded)', () => {
+ test('returns the merged pins even when storage.setItem throws (quota exceeded)', () => {
const throwingStorage: PinStorage = {
getItem: () => null,
setItem: () => {
throw new DOMException('QuotaExceededError');
},
};
- const result = applyToggle('left', 'above', 'collapsed', throwingStorage);
- expect(result).toEqual({ left: { above: 'collapsed' } });
+ expect(applyToggleAtEveryWidth('left', 'collapsed', throwingStorage)).toEqual({
+ left: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' },
+ });
+ });
+});
+
+describe('openIntentAfterPartitionChange', () => {
+ test('a pinned partition returns its pin', () => {
+ expect(openIntentAfterPartitionChange('left', 'above', { left: { above: 'collapsed' } })).toBe(
+ false,
+ );
+ expect(openIntentAfterPartitionChange('right', 'below', { right: { below: 'open' } })).toBe(
+ true,
+ );
+ });
+
+ test('an unpinned partition opens only where the default is open', () => {
+ expect(openIntentAfterPartitionChange('left', 'above', {})).toBe(true);
+ expect(openIntentAfterPartitionChange('left', 'below', {})).toBeUndefined();
+ expect(openIntentAfterPartitionChange('right', 'embedded', {})).toBeUndefined();
});
});
diff --git a/packages/app/src/lib/sidebar-pin-store.ts b/packages/app/src/lib/sidebar-pin-store.ts
index 317158d20..44bb05257 100644
--- a/packages/app/src/lib/sidebar-pin-store.ts
+++ b/packages/app/src/lib/sidebar-pin-store.ts
@@ -68,15 +68,24 @@ export function resolveEffectiveState(
return pins[side]?.[currentPartition] ?? smartDefault(currentPartition);
}
-export function applyToggle(
+export function applyToggleAtEveryWidth(
side: SidebarSide,
- currentPartition: Partition,
newState: SidebarState,
storage?: PinStorage,
): StoredPins {
const s = storage ?? localStorage;
const pins = readPins(s);
- pins[side] = { ...pins[side], [currentPartition]: newState };
+ pins[side] = { above: newState, below: newState, embedded: newState };
writePins(pins, s);
return pins;
}
+
+export function openIntentAfterPartitionChange(
+ side: SidebarSide,
+ partition: Partition,
+ pins: StoredPins,
+): boolean | undefined {
+ const pinned = pins[side]?.[partition];
+ if (pinned !== undefined) return pinned === 'open';
+ return smartDefault(partition) === 'open' ? true : undefined;
+}
diff --git a/packages/app/src/lib/subscribe-card-store.test.ts b/packages/app/src/lib/subscribe-card-store.test.ts
index 1eccb0d49..aaf44da64 100644
--- a/packages/app/src/lib/subscribe-card-store.test.ts
+++ b/packages/app/src/lib/subscribe-card-store.test.ts
@@ -156,3 +156,31 @@ describe('createSubscribeCardStore', () => {
expect(calls).toBe(1);
});
});
+
+describe('newsletter state saved by earlier releases', () => {
+ test('the storage key is still ok-subscribe-card-v1', () => {
+ expect(SUBSCRIBE_CARD_STORAGE_KEY).toBe('ok-subscribe-card-v1');
+ });
+
+ test('offers used up across three versions read back unchanged and stay ineligible', () => {
+ const stored = {
+ subscribed: false,
+ dismissed: false,
+ shownVersions: ['0.9.0', '1.0.0', '1.1.0'],
+ };
+ const s = memoryStorage({ 'ok-subscribe-card-v1': JSON.stringify(stored) });
+ const read = readPersistedState(s);
+ expect(read).toEqual(stored);
+ expect(isSubscribeCombinedEligible(read, '1.2.0')).toBe(false);
+ });
+
+ test('a subscribed and dismissed newsletter state reads back with both flags set', () => {
+ const stored = { subscribed: true, dismissed: true, shownVersions: ['1.0.0'] };
+ const s = memoryStorage({ 'ok-subscribe-card-v1': JSON.stringify(stored) });
+ const read = readPersistedState(s);
+ expect(read).toEqual(stored);
+ expect(read.subscribed).toBe(true);
+ expect(read.dismissed).toBe(true);
+ expect(isSubscribeCombinedEligible(read, '1.2.0')).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/use-editor-pane-on-screen.ts b/packages/app/src/lib/use-editor-pane-on-screen.ts
new file mode 100644
index 000000000..288636973
--- /dev/null
+++ b/packages/app/src/lib/use-editor-pane-on-screen.ts
@@ -0,0 +1,14 @@
+import { createContext, use, useSyncExternalStore } from 'react';
+import { paneVisibilityStore } from '@/lib/pane-visibility-store';
+
+export const EditorContentOnScreenContext = createContext(true);
+
+export function useEditorPaneOnScreen(): boolean {
+ const contentOnScreen = use(EditorContentOnScreenContext);
+ const paneOnScreen = useSyncExternalStore(
+ paneVisibilityStore.subscribe,
+ () => paneVisibilityStore.getSnapshot().editor?.onScreen ?? true,
+ () => true,
+ );
+ return contentOnScreen && paneOnScreen;
+}
diff --git a/packages/app/src/lib/use-timeline-entry-diff.ts b/packages/app/src/lib/use-timeline-entry-diff.ts
index 250b91050..ef408d30f 100644
--- a/packages/app/src/lib/use-timeline-entry-diff.ts
+++ b/packages/app/src/lib/use-timeline-entry-diff.ts
@@ -13,9 +13,10 @@ export const HISTORICAL_CONTENT_CACHE_LIMIT = 32;
type UseTimelineEntryDiffResult =
| { status: 'idle'; diff: null }
| { status: 'loading'; diff: null }
- | { status: 'error'; diff: null }
+ | { status: 'error'; key: string; diff: null }
| {
status: 'ready';
+ key: string;
diff: string;
additions: number;
deletions: number;
@@ -101,7 +102,11 @@ export function useTimelineEntryDiff(
const shaContent = await fetchHistoricalContent(activeSha);
if (cancelled) return;
if (shaContent === null) {
- setResult({ status: 'error', diff: null });
+ setResult({
+ status: 'error',
+ key: timelineEntryCacheKey(docName, activeSha),
+ diff: null,
+ });
return;
}
@@ -111,7 +116,11 @@ export function useTimelineEntryDiff(
const parentContent = parentSha ? await fetchHistoricalContent(parentSha) : '';
if (cancelled) return;
if (parentContent === null) {
- setResult({ status: 'error', diff: null });
+ setResult({
+ status: 'error',
+ key: timelineEntryCacheKey(docName, activeSha),
+ diff: null,
+ });
return;
}
beforeRaw = parentContent;
@@ -129,6 +138,7 @@ export function useTimelineEntryDiff(
const { additions, deletions } = countDiffStat(patchStr);
setResult({
status: 'ready',
+ key: timelineEntryCacheKey(docName, activeSha),
diff: patchStr,
additions,
deletions,
@@ -144,7 +154,11 @@ export function useTimelineEntryDiff(
mode,
err,
});
- setResult({ status: 'error', diff: null });
+ setResult({
+ status: 'error',
+ key: timelineEntryCacheKey(docName, activeSha),
+ diff: null,
+ });
}
}
}
diff --git a/packages/app/src/lib/workspace-hash-writes.test.ts b/packages/app/src/lib/workspace-hash-writes.test.ts
new file mode 100644
index 000000000..51aa139fe
--- /dev/null
+++ b/packages/app/src/lib/workspace-hash-writes.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'vitest';
+import { consumeWorkspaceHashWrite, noteWorkspaceHashWrite } from './workspace-hash-writes';
+
+describe('telling workspace hash writes from deliberate navigation', () => {
+ test('a hash the workspace wrote is recognised once', () => {
+ noteWorkspaceHashWrite('#/notes/today');
+ expect(consumeWorkspaceHashWrite('#/notes/today')).toBe(true);
+ expect(consumeWorkspaceHashWrite('#/notes/today')).toBe(false);
+ });
+
+ test('a different hash arriving after a workspace write is deliberate', () => {
+ noteWorkspaceHashWrite('#/notes/today');
+ expect(consumeWorkspaceHashWrite('#/notes/tomorrow')).toBe(false);
+ });
+
+ test('with no workspace write pending every hash is deliberate', () => {
+ expect(consumeWorkspaceHashWrite('#/notes/today')).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/workspace-hash-writes.ts b/packages/app/src/lib/workspace-hash-writes.ts
new file mode 100644
index 000000000..34a149ae6
--- /dev/null
+++ b/packages/app/src/lib/workspace-hash-writes.ts
@@ -0,0 +1,13 @@
+import { isSameHash } from '@/lib/doc-hash';
+
+let pendingWorkspaceHash: string | null = null;
+
+export function noteWorkspaceHashWrite(hash: string): void {
+ pendingWorkspaceHash = hash;
+}
+
+export function consumeWorkspaceHashWrite(currentHash: string): boolean {
+ const pending = pendingWorkspaceHash;
+ pendingWorkspaceHash = null;
+ return pending !== null && isSameHash(currentHash, pending);
+}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 8f22bb467..b5bba85d0 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -403,6 +403,7 @@
"3Fcb0I": ["فتح الرسم البياني"],
"3HAPpl": ["لا توجد مخططات تطابق بحثك."],
"3HNlwb": ["مرحبًا بالعالم!"],
+ "3HOAcR": ["لوحة الوكيل"],
"3Ib6FN": ["تحريك لأسفل"],
"3J7d2N": ["عنوان قسم كبير."],
"3JYy1p": ["لم يعد الفرع ", ["0"], " موجودًا. تم الاستنساخ إلى الفرع الافتراضي."],
@@ -602,6 +603,7 @@
],
"5OTgC7": ["افتح مؤلف موجّه «اسأل الذكاء الاصطناعي» السفلي وركّز عليه."],
"5OqaJi": ["أدخل اسم مشروع"],
+ "5Q9-G-": ["لوحة المستند"],
"5QGTaA": ["تعذّر نسخ المسار النسبي"],
"5RiC8D": [
"تُدار مهارات الاكتشاف لجميع أدوات الذكاء الاصطناعي معًا. ثبّت هذه المهارة من استوديو المهارات ضمن الإعدادات."
@@ -899,6 +901,7 @@
"7cAW1G": ["لم يُضبط مفتاح API لنقطة النهاية هذه. أضف واحدًا أعلاه."],
"7czmD1": ["اطّلع OpenKnowledge على لوحة التأليف"],
"7d1a0d": ["عام"],
+ "7dDoQu": ["جزء المحرر"],
"7dZnmw": ["الصلة"],
"7hctf2": ["صِف المشروع الذي تريد إنشاءه"],
"7idx48": ["OKF تم تثبيت مهارة الوكيل"],
@@ -1457,7 +1460,6 @@
"DWJtEo": ["ما الذي سيحدث بعد ذلك"],
"DXd9LM": ["شجرة عمل جديدة"],
"D_WKe_": ["انقر صورة وكيل في شريط الحضور لعرض جلسته."],
- "DbCfXV": ["بحث (", ["searchShortcutLabel"], ")"],
"DbILZA": ["لا توجد تطابقات. بعض الملفات مستثناة من البحث (ملفات مخفية أو متجاهَلة)."],
"DcFr-y": ["حذف OpenKnowledge مستندًا"],
"DcH8-w": ["نقل ", ["0"], " مهارات إلى المشروع"],
@@ -1688,6 +1690,7 @@
")."
],
"FWSjnp": ["تحرير لوحة المصدر وحقول خصائص الكود"],
+ "FYy2EN": ["تغيير حجم لوحة المستند"],
"FZtBeR": ["تفعيل ", ["0"]],
"FeXcUS": [
["display"],
@@ -1757,6 +1760,7 @@
"، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
],
"GBQjiV": ["إضافة مهارة"],
+ "GCrhIF": ["اللوحات"],
"GDvlUT": ["الدور"],
"GEyl32": ["جارٍ بدء تشغيل الطرفية…"],
"GGsM4y": ["محدَّد في الرسم البياني"],
@@ -2399,7 +2403,6 @@
"الرابط الرمزي مؤشِّر إلى المجلد المصدر بدلًا من أن يكون مجلدًا قائمًا بذاته. يقرأ كل موقع البايتات نفسها تمامًا، فلا شيء يمكن أن ينحرف، لكن الموقع يتوقف عن العمل إذا حُذف المصدر."
],
"MTs6g3": ["تعذّرت إعادة الاتصال بعد إعادة تشغيل الخادم"],
- "MU_NVW": ["طي Terminal"],
"MUrVEo": ["لا توجد مشاريع حديثة."],
"MV-Dkb": ["عُثر على ", ["countDisplay"], " ملف Markdown"],
"MVxpbf": ["بحث واستبدال"],
@@ -3280,13 +3283,13 @@
],
"V48OUT": ["حذفت <0>", ["filePath"], "</0> محليًا، لكنه عُدِّل في المستودع البعيد."],
"V4JHny": ["لا تدعم المشاركة سوى المستودعات البعيدة على GitHub."],
- "V6AIOn": ["التنقل في مساحة العمل"],
"V6e25h": ["معاينة السمة"],
"V7QxyT": ["انقطع الاتصال"],
"VAHWL_": ["متصل باسم <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"ابنِ العالم الذي تدور فيه قصتك وتتبّعه. موطن لشخصياتك وأماكنك وفصائلك والسِّيَر التي تربطها، لتبقى التفاصيل متسقة أثناء كتابتك."
],
+ "VBtCdv": ["تعذر التمرير إلى ذلك المقطع. حاول مرة أخرى."],
"VFQXPl": [
"تعرض معاينات الروابط الخارجية بطاقة باسم الموقع وعنوان الصفحة ووصفها عند تمرير المؤشر فوق رابط."
],
@@ -3474,7 +3477,6 @@
"X2zUS5": ["حذف هذا التعليق"],
"X3MMeA": ["لا يوجد لأي من هذه المشكلات إصلاح تلقائي."],
"X59Fx2": ["تعذّر فتح هذا المستند في Slidev."],
- "X7ShnN": ["فتح لوحة الوكلاء"],
"X8kjQX": ["أعد المصادقة مع GitHub"],
"X9VpsP": ["يجري تحميل محتويات المجلد"],
"XA9uvc": ["يتحقق OpenKnowledge من وجود تحديثات وينزّلها في الخلفية."],
@@ -3637,6 +3639,7 @@
"YS9mSt": ["حُدِّث «", ["name"], "» من ", ["0"]],
"YSFv5w": ["لا يوجد مستودع git — لا تنطبق مشاركة الإعدادات هنا."],
"YScUUO": ["يجلب صفحة ويب"],
+ "YStFYH": ["فتح الوكلاء"],
"YTLmTM": ["إزالة مجلد <0>.git</0> الأب"],
"YW7Q86": ["لم تُحمَّل إعدادات البحث بعد — أعد المحاولة بعد قليل"],
"YWK2zy": ["فروق التعارض في ", ["fileName"]],
@@ -3927,6 +3930,7 @@
"لم يتم اكتشاف أي أداة ذكاء اصطناعي بعد. بعد تثبيت واحدة، اربطها من الإعدادات > هذا المشروع."
],
"aTDVi6": ["تم الاحتفاظ بمحتواك"],
+ "aV2vel": ["الجزء ", ["number"]],
"aWlJai": ["يجري بدء تدفق تسجيل الدخول"],
"aXkLuE": ["استجابة التطبيق مشوّهة"],
"a_u4ck": ["يجري تحميل الوسوم"],
@@ -4540,6 +4544,7 @@
"f1-q9m": ["يحتفظ بالمهارات"],
"f14doC": ["Slidev"],
"f1XQyZ": ["نقل الكتلة"],
+ "f3YhVJ": ["لا شيء مفتوح"],
"f65AOQ": ["البدء من"],
"f6suyZ": ["طُلبت تغييرات"],
"f8fH8W": ["التصميم"],
@@ -4557,6 +4562,7 @@
"fKsRVO": ["مهارات من ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["تعذّر حفظ إعداد التحديث التلقائي: ", ["0"]],
"fNr-MX": ["تعطيل البحث الدلالي"],
+ "fObclJ": ["العودة إلى المحرر"],
"fOzzSV": ["هدف الرابط \"", ["shown"], "\" لا يشير إلى ملف موجود."],
"fRVBiq": [
"يضيف بيانات القياس وحالة الخادم ومعلومات وقت التشغيل عند توفرها. تُزال بيانات الاعتماد دائمًا؛ وتظهر أسماء المستندات، إن أُدرجت، كنص صريح (غير مخفي)."
@@ -4660,7 +4666,6 @@
["descriptorLabel"],
"> (على الأرجح خاصية غير صالحة). انسخ المصدر لمعرفة الخطأ، أو احذف الكتلة."
],
- "g5V4_P": ["طي لوحة الوكيل"],
"g5w1sF": [
"اختر مجلدًا لدمجه في ",
["display"],
@@ -4903,21 +4908,6 @@
"i04BJx": ["موجودة خارج هذا المشروع — للقراءة فقط هنا."],
"i09An-": ["تمت استعادة نسخة سابقة (", ["0"], ")"],
"i1flq_": ["اقتراحات روابط الويكي"],
- "i25FHa": [
- "فتح لوحة الوكلاء — ",
- [
- "liveThreadCount",
- "plural",
- {
- "zero": ["#", " خيوط وكلاء نشطة"],
- "one": ["خيط وكيل نشط واحد"],
- "two": ["خيطا وكيل نشطَين"],
- "few": ["#", " خيوط وكلاء نشطة"],
- "many": ["#", " خيط وكيل نشطا"],
- "other": ["#", " خيط وكيل نشط"]
- }
- ]
- ],
"i3f2kh": ["لا توجد أوامر مطابقة."],
"i6o7XB": ["البحث عن اللغات"],
"i92eAT": ["سننشئ مستودعًا ونبدأ المزامنة — بلا حاجة إلى طرفية."],
@@ -5487,6 +5477,7 @@
],
"n7aopT": ["وضع المحرر"],
"n81AV0": [["owner"], "/", ["name"], " موجود بالفعل. اختر اسمًا آخر."],
+ "nBFK5w": ["تغيير حجم الطرفية"],
"nBHvPL": ["إلغاء التحرير"],
"nBgzKO": ["اجعل هذا هو المصدر — ينتقل مجلد المهارة الحقيقي إلى هنا"],
"nCzR-G": ["نسخ الرمز ", ["userCode"]],
@@ -5903,6 +5894,7 @@
"qyLmWw": ["لوحة بحث محرر المصدر"],
"qze9od": ["هذا المجلد يخص ", ["alsoAffects"], " أيضًا."],
"r-OJYm": ["أدخل اسم فرع صالحًا (بلا مسافات، وبلا نقطة في البداية، وبلا «..»)."],
+ "r-wzd8": ["التحديثات والملاحظات"],
"r2eKE3": ["سجّل الدخول إلى ", ["agentName"], " أولًا"],
"r3iaI0": ["لا توجد دردشات بعد."],
"r4R7AZ": ["خطأ في الشبكة أثناء التنظيف"],
@@ -6161,6 +6153,7 @@
"ten9en": ["مشروع حديث"],
"tfDRzk": ["حفظ"],
"tfi40B": ["فشل إنشاء الصفحة"],
+ "tgB_VT": ["فتح المحرر"],
"tgWuMB": ["معدَّل"],
"thnPBX": ["تنشيط التبويب التالي في المحرر."],
"ti6aF_": ["اسأل واجهة ", ["0"], " السطرية"],
@@ -6368,6 +6361,7 @@
"un-K1H": ["يبقى على هذا الجهاز. غير مُودَع في git."],
"un8kBM": ["يجري إنشاء الصفحة: ", ["linkTitle"], "."],
"uoJF_D": ["كان إعداده أو البدء به صعبًا جدًا"],
+ "uqgCZJ": ["إخفاء المحرر"],
"uqs8Gd": [
[
"others",
@@ -6734,6 +6728,7 @@
"xzAmL_": ["موافق عليه تلقائيًا"],
"xzktOa": ["تحرير رابط الويكي"],
"y-LQPF": ["تعذّر حل الصورة ", ["identity"], ". انتقل إلى المرجع."],
+ "y0_w13": ["إظهار المحرر"],
"y1eoq1": ["نسخ الرابط"],
"y1t8bQ": ["أقسام الإعدادات"],
"y3aU20": ["حفظ التغييرات"],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index b6315e863..cf0f05474 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -1674,6 +1674,7 @@ msgstr "نشط"
msgid "Active panel content for the selected tab shows here."
msgstr "يظهر هنا محتوى اللوحة النشطة للتبويب المحدد."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "النشاط"
@@ -1965,6 +1966,10 @@ msgstr "اتصالات الوكلاء"
msgid "Agent mode"
msgstr "وضع الوكيل"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "لوحة الوكيل"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "أُغلقت لوحة الوكيل لإبقاء Terminal سهل القراءة."
@@ -1987,6 +1992,7 @@ msgstr "نص جلسة الوكيل"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "الوكلاء"
@@ -2183,6 +2189,7 @@ msgstr "مثيل التطبيق: {label}، v{version}"
msgid "Append-only log of what changed."
msgstr "سجل للإلحاق فقط بما تغيّر."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "التطبيق"
@@ -2547,6 +2554,10 @@ msgstr "رجوع"
msgid "Back to document view"
msgstr "العودة إلى عرض المستند"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "العودة إلى المحرر"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "الروابط الخلفية"
@@ -3467,10 +3478,6 @@ msgstr "طيّ"
msgid "Collapse {keyName}"
msgstr "طيّ {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "طي لوحة الوكيل"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "طيّ «اسأل الذكاء الاصطناعي»"
msgid "Collapse graph"
msgstr "طيّ الرسم البياني"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "طي Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "كتلة محتوى قابلة للطي (تبديل بنمط Notion)."
@@ -3665,7 +3668,7 @@ msgstr "اضبط إعدادات المستخدم والمشروع والتكام
msgid "conflict"
msgstr "تعارض"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "تعارض"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "تعذّر تكرار «{0}»: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "تعذر العثور على ذلك المقطع — ربما تغير النص الذي كان عليه."
@@ -4669,6 +4673,10 @@ msgstr "تعذّر حفظ هذا الإعداد. حاول مرة أخرى."
msgid "Couldn't save your theme preference."
msgstr "تعذّر حفظ تفضيل السمة لديك."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "تعذر التمرير إلى ذلك المقطع. حاول مرة أخرى."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "تعذّر إرسال التقرير"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "وضع عرض الفروق"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "الفروق غير متاحة"
@@ -5410,6 +5419,10 @@ msgstr "المستند غير موجود"
msgid "Document outline"
msgstr "مخطط المستند"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "لوحة المستند"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "لوحات المستند"
@@ -5733,6 +5746,7 @@ msgstr "يجري تحرير {boldName} في مكانه. تُحفظ التغيي
msgid "Editing broken MDX source: {reason}"
msgstr "يجري تحرير مصدر MDX معطوب: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "المحرر"
@@ -5745,6 +5759,10 @@ msgstr "وضع المحرر"
msgid "editor pane"
msgstr "جزء المحرر"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "جزء المحرر"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "تحديد المحرر"
@@ -6691,6 +6709,7 @@ msgstr "الملف: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "اسم الملف"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "الملفات"
@@ -7353,11 +7372,17 @@ msgstr "إخفاء التفاصيل"
msgid "Hide document panel"
msgstr "إخفاء لوحة المستند"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "إخفاء المحرر"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "إخفاء عقد الروابط الخارجية"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "إخفاء الملفات"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "إخفاء الآخرين"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "إخفاء اللوحة"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "إخفاء اللوحة ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "عدّل وجهة الرابط والمرساة وتسمية العرض.
msgid "More"
msgstr "المزيد"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "مزيد من الإجراءات"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "مزيد من الإجراءات ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "لا شيء يتحرك حتى تطلب ذلك — اسحب وادفع م
msgid "Nothing moves until you ask."
msgstr "لا شيء يتحرك حتى تطلب ذلك."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "لا شيء مفتوح"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "لم يُضبط شيء بعد."
@@ -10111,7 +10141,7 @@ msgstr "معطّل — تعرض الروابط الخارجية رابطها ف
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "معطّل — يرتّب البحث بالكلمات المفتاحية فقط. لا يغادر أي محتوى هذا الجهاز."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "غير متصل"
@@ -10277,13 +10307,9 @@ msgstr "فتح لوحة النشاط لـ {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "فتح لوحة النشاط لـ {tooltipName}، يحرّر {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "فتح لوحة الوكلاء"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "فتح لوحة الوكلاء — {liveThreadCount, plural, zero {# خيوط وكلاء نشطة} one {خيط وكيل نشط واحد} two {خيطا وكيل نشطَين} few {# خيوط وكلاء نشطة} many {# خيط وكيل نشطا} other {# خيط وكيل نشط}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "فتح الوكلاء"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "افتح تأكيد الحذف لعناصر شجرة الملفات ال
msgid "Open documents tagged #{chip}"
msgstr "فتح المستندات الموسومة بـ #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "فتح المحرر"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "فتح مسودة البريد"
@@ -10501,7 +10531,7 @@ msgstr "فتح لوحة فحص المصدر"
msgid "Open source: {mirrorSrc}"
msgstr "فتح المصدر: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "فتح الطرفية"
@@ -11062,6 +11092,14 @@ msgstr "تحريك لأعلى"
msgid "pane {0}"
msgstr "الجزء {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "الجزء {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "اللوحات"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "فقرة"
@@ -11470,6 +11508,7 @@ msgstr "مشروع"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "المشروع"
@@ -11863,7 +11902,7 @@ msgstr "موصى به"
msgid "Recommended agent skill"
msgstr "مهارة الوكيل الموصى بها"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "إعادة الاتصال مطلوبة"
@@ -12452,10 +12491,19 @@ msgstr "إعادة تعيين مرشحات العرض"
msgid "Resize {handleKey}"
msgstr "تغيير حجم {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "تغيير حجم لوحة المستند"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "تغيير حجم لوحة المهارات"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "تغيير حجم الطرفية"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "حل التعارض في طرفيتك"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "التمرير إلى البداية"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "بحث"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "ابحث عن «{semanticSubmitQuery}» حسب المعنى"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "بحث ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "البحث في الوكلاء"
@@ -13549,6 +13592,11 @@ msgstr "إظهار المخطط"
msgid "Show document panel"
msgstr "إظهار لوحة المستند"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "إظهار المحرر"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "إظهار عقد الروابط الخارجية"
@@ -13557,7 +13605,7 @@ msgstr "إظهار عقد الروابط الخارجية"
msgid "Show fewer"
msgstr "إظهار أقل"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "إظهار الملفات"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "إظهار الأصل"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "إظهار اللوحة"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "إظهار اللوحة ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "وضع المزامنة"
msgid "Sync now"
msgstr "المزامنة الآن"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "المزامنة موقوفة مؤقتًا"
@@ -14616,6 +14664,7 @@ msgstr "قوالب متاحة"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "حدّث خصائص المجلد"
msgid "Updated to Version {version}"
msgstr "حُدِّث إلى الإصدار {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "التحديثات والملاحظات"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "تتدفق التحديثات إلى الداخل"
@@ -16989,10 +17042,6 @@ msgstr "مساحة العمل"
msgid "Workspace Command Palette"
msgstr "لوحة أوامر مساحة العمل"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "التنقل في مساحة العمل"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index fda86be29..65afc57d2 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -336,6 +336,7 @@
"3Fcb0I": ["গ্রাফ খুলুন"],
"3HAPpl": ["আপনার অনুসন্ধানের সঙ্গে কোনো স্কিমা মেলে না।"],
"3HNlwb": ["ওহে, বিশ্ব!"],
+ "3HOAcR": ["এজেন্ট প্যানেল"],
"3Ib6FN": ["নিচে সরান"],
"3J7d2N": ["বড় বিভাগ শিরোনাম।"],
"3JYy1p": ["ব্রাঞ্চ ", ["0"], " আর নেই। ডিফল্ট ব্রাঞ্চে ক্লোন করা হয়েছে।"],
@@ -516,6 +517,7 @@
],
"5OTgC7": ["নিচের Ask AI প্রম্পট রচনাপট খুলুন ও তাতে ফোকাস করুন।"],
"5OqaJi": ["একটি প্রকল্পের নাম দিন"],
+ "5Q9-G-": ["নথি প্যানেল"],
"5QGTaA": ["আপেক্ষিক পথ কপি করা যায়নি"],
"5RiC8D": [
"ডিসকভারি স্কিলগুলো সব AI টুলের জন্য একসঙ্গে পরিচালিত হয়। সেটিং → স্কিল স্টুডিও থেকে এটি ইনস্টল করুন।"
@@ -738,6 +740,7 @@
"7cAW1G": ["এই এন্ডপয়েন্টের জন্য কোনো API কী নির্ধারিত নেই। উপরে একটি যোগ করুন।"],
"7czmD1": ["OpenKnowledge লেখার প্যালেট দেখেছে"],
"7d1a0d": ["সর্বজনীন"],
+ "7dDoQu": ["সম্পাদক প্যান"],
"7dZnmw": ["প্রাসঙ্গিকতা"],
"7hctf2": ["আপনি যে প্রকল্পটি তৈরি করতে চান তার বর্ণনা দিন"],
"7idx48": ["OKF এজেন্ট দক্ষতা ইনস্টল করা হয়েছে"],
@@ -1222,7 +1225,6 @@
"DWJtEo": ["এরপর কী হয়"],
"DXd9LM": ["নতুন ওয়ার্কট্রি"],
"D_WKe_": ["কোনো এজেন্টের সেশন দেখতে উপস্থিতি বারে তার অবতারে ক্লিক করুন।"],
- "DbCfXV": ["খুঁজুন (", ["searchShortcutLabel"], ")"],
"DbILZA": ["কোনো মিল নেই। কিছু ফাইল অনুসন্ধান থেকে বাদ দেওয়া (লুকানো বা উপেক্ষিত ফাইল)।"],
"DcFr-y": ["OpenKnowledge একটি নথি মুছে ফেলেছে"],
"DcH8-w": [["0"], "টি স্কিল প্রকল্পে সরান"],
@@ -1437,6 +1439,7 @@
") সঙ্গে মেলে না।"
],
"FWSjnp": ["সোর্স প্যানেল ও কোড প্রপার্টি ফিল্ড সম্পাদনা করুন"],
+ "FYy2EN": ["নথি প্যানেলের আকার পরিবর্তন করুন"],
"FZtBeR": [["0"], " চালু করুন"],
"FeXcUS": [
["display"],
@@ -1493,6 +1496,7 @@
" উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
],
"GBQjiV": ["স্কিল যোগ করুন"],
+ "GCrhIF": ["প্যানেলসমূহ"],
"GDvlUT": ["ভূমিকা"],
"GEyl32": ["টার্মিনাল চালু হচ্ছে…"],
"GGsM4y": ["গ্রাফে নির্বাচিত"],
@@ -2012,7 +2016,6 @@
"সিমলিংক নিজের একটি ফোল্ডার না হয়ে বরং উৎস ফোল্ডারের দিকে একটি নির্দেশক। প্রতিটি জায়গা ঠিক একই বাইট পড়ে, তাই কিছুই আলাদা হয়ে যেতে পারে না, আর উৎস মুছে ফেললে সেই জায়গাটি কাজ করা বন্ধ করে দেয়।"
],
"MTs6g3": ["সার্ভার পুনরায় চালুর পর আবার যুক্ত হওয়া যায়নি"],
- "MU_NVW": ["Terminal সংকুচিত করুন"],
"MUrVEo": ["কোনো সাম্প্রতিক প্রকল্প নেই।"],
"MV-Dkb": [["countDisplay"], "টি markdown ফাইল পাওয়া গেছে"],
"MVxpbf": ["খুঁজুন ও বদলান"],
@@ -2772,13 +2775,13 @@
"</0> স্থানীয়ভাবে মুছে ফেলেছেন, কিন্তু সেটি আপস্ট্রিমে বদলানো হয়েছিল।"
],
"V4JHny": ["শেয়ারিং শুধু GitHub রিমোট সমর্থন করে।"],
- "V6AIOn": ["ওয়ার্কস্পেস নেভিগেশন"],
"V6e25h": ["থিমের প্রাকদর্শন"],
"V7QxyT": ["সংযোগ বিচ্ছিন্ন হয়েছে"],
"VAHWL_": ["<0>@", ["signedInLogin"], "</0> হিসেবে যুক্ত"],
"VBE2dw": [
"আপনার গল্পের পেছনের জগৎ গড়ুন এবং তার হিসাব রাখুন। আপনার চরিত্র, স্থান, গোষ্ঠী এবং তাদের যুক্ত করা কাহিনির একটি ঘর, যাতে লেখার সময় খুঁটিনাটি সামঞ্জস্যপূর্ণ থাকে।"
],
+ "VBtCdv": ["সেই অংশে স্ক্রল করা যায়নি। আবার চেষ্টা করুন।"],
"VFQXPl": [
"আপনি কোনো লিংকের উপর মাউস নিলে বাইরের লিংকের প্রাকদর্শন সাইটের নাম, পাতার শিরোনাম ও বিবরণসহ একটি কার্ড দেখায়।"
],
@@ -2912,7 +2915,6 @@
"X2zUS5": ["এই মন্তব্যটি মুছুন"],
"X3MMeA": ["এই সমস্যাগুলোর কোনোটিরই স্বয়ংক্রিয় সমাধান নেই।"],
"X59Fx2": ["এই নথিটি Slidev-এ খোলা যায়নি।"],
- "X7ShnN": ["এজেন্ট প্যানেল খুলুন"],
"X8kjQX": ["GitHub-এর সঙ্গে আবার প্রমাণীকরণ করুন"],
"X9VpsP": ["ফোল্ডারের বিষয়বস্তু লোড হচ্ছে"],
"XA9uvc": ["OpenKnowledge পটভূমিতে হালনাগাদ খোঁজে এবং ডাউনলোড করে।"],
@@ -3057,6 +3059,7 @@
"YS9mSt": ["\"", ["name"], "\" ", ["0"], " থেকে হালনাগাদ হয়েছে"],
"YSFv5w": ["কোনো git রিপোজিটরি নেই — কনফিগ ভাগাভাগি এখানে প্রযোজ্য নয়।"],
"YScUUO": ["একটি ওয়েব পেজ আনে"],
+ "YStFYH": ["এজেন্ট খুলুন"],
"YTLmTM": ["মূল <0>.git</0> ফোল্ডারটি সরান"],
"YW7Q86": ["অনুসন্ধানের সেটিং এখনও লোড হয়নি — একটু পরে আবার চেষ্টা করুন"],
"YWK2zy": [["fileName"], "-এর কনফ্লিক্ট ডিফ"],
@@ -3326,6 +3329,7 @@
"এখনও কোনো AI টুল পাওয়া যায়নি। একটি ইনস্টল করার পর Settings > This project থেকে সেটি যুক্ত করুন।"
],
"aTDVi6": ["আপনার বিষয়বস্তু রাখা হয়েছে"],
+ "aV2vel": ["প্যান ", ["number"]],
"aWlJai": ["সাইন-ইন প্রক্রিয়া শুরু করা হচ্ছে"],
"aXkLuE": ["অ্যাপ্লাই প্রতিক্রিয়ার গঠন ত্রুটিপূর্ণ"],
"a_u4ck": ["ট্যাগ লোড হচ্ছে"],
@@ -3789,6 +3793,7 @@
"f1-q9m": ["স্কিলগুলো রেখে দেয়"],
"f14doC": ["Slidev"],
"f1XQyZ": ["ব্লক সরান"],
+ "f3YhVJ": ["কিছুই খোলা নেই"],
"f65AOQ": ["এখান থেকে শুরু"],
"f6suyZ": ["পরিবর্তন চাওয়া হয়েছে"],
"f8fH8W": ["নকশা"],
@@ -3806,6 +3811,7 @@
"fKsRVO": [["0"], "/", ["1"], " থেকে স্কিল।"],
"fMsFdZ": ["স্বয়ংক্রিয় হালনাগাদের সেটিং সংরক্ষণ করা যায়নি: ", ["0"]],
"fNr-MX": ["অর্থভিত্তিক অনুসন্ধান নিষ্ক্রিয় করুন"],
+ "fObclJ": ["সম্পাদকে ফিরুন"],
"fOzzSV": ["লিংকের লক্ষ্য \"", ["shown"], "\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"],
"fRVBiq": [
"পাওয়া গেলে টেলিমেট্রি, সার্ভারের অবস্থা ও রানটাইম তথ্য যোগ করে। ক্রেডেনশিয়াল সবসময় সরিয়ে ফেলা হয়; নথির নাম, যদি অন্তর্ভুক্ত থাকে, সাদা লেখায় দেখা যায় (সরানো হয় না)।"
@@ -3882,7 +3888,6 @@
["descriptorLabel"],
"> রেন্ডার করা যায়নি (সম্ভবত একটি ভুল প্রপ)। কী ভুল হয়েছে দেখতে সোর্স কপি করুন, নয়তো ব্লকটি মুছে দিন।"
],
- "g5V4_P": ["এজেন্ট প্যানেল সংকুচিত করুন"],
"g5w1sF": [
["display"],
"-এর মধ্যে মেলানোর জন্য একটি ফোল্ডার বাছুন। ওই ফোল্ডারটি এটির সিমলিংক হয়ে যায়, তাই তার এজেন্ট এখানে রাখা সবকিছু পড়ে। এই ফোল্ডারটি সত্যিকারের থেকে যায়। দ্বন্দ্বপূর্ণ স্কিল মার্জ বাতিল করে দেয়।"
@@ -4107,14 +4112,6 @@
"i04BJx": ["এই প্রকল্পের বাইরে অবস্থিত — এখানে শুধুমাত্র-পঠনযোগ্য।"],
"i09An-": ["একটি পুরোনো সংস্করণ ফিরিয়ে আনা হয়েছে (", ["0"], ")"],
"i1flq_": ["উইকি লিংকের পরামর্শ"],
- "i25FHa": [
- "এজেন্ট প্যানেল খুলুন — ",
- [
- "liveThreadCount",
- "plural",
- { "one": ["#", " সক্রিয় এজেন্ট থ্রেড"], "other": ["#", " সক্রিয় এজেন্ট থ্রেড"] }
- ]
- ],
"i3f2kh": ["মিলে যাওয়া কোনো কমান্ড নেই।"],
"i6o7XB": ["ভাষা খুঁজুন"],
"i92eAT": ["আমরা একটি রিপোজিটরি তৈরি করে সিঙ্ক শুরু করব — কোনো টার্মিনাল লাগবে না।"],
@@ -4632,6 +4629,7 @@
],
"n7aopT": ["সম্পাদক মোড"],
"n81AV0": [["owner"], "/", ["name"], " আগে থেকেই আছে। অন্য একটি নাম বেছে নিন।"],
+ "nBFK5w": ["টার্মিনালের আকার পরিবর্তন করুন"],
"nBHvPL": ["সম্পাদনা বাতিল করুন"],
"nBgzKO": ["এটিকে উৎস বানান — স্কিলের আসল ফোল্ডার এখানে সরে আসে"],
"nCzR-G": ["কোড ", ["userCode"], " কপি করুন"],
@@ -4973,6 +4971,7 @@
"qyLmWw": ["সোর্স সম্পাদকের অনুসন্ধান প্যানেল"],
"qze9od": ["এই ফোল্ডারটি ", ["alsoAffects"], "-এরও।"],
"r-OJYm": ["একটি বৈধ ব্রাঞ্চ নাম দিন (ফাঁকা জায়গা নয়, শুরুতে বিন্দু নয়, \"..\" নয়)।"],
+ "r-wzd8": ["হালনাগাদ ও মতামত"],
"r2eKE3": ["আগে ", ["agentName"], "-এ সাইন ইন করুন"],
"r3iaI0": ["এখনও কোনো চ্যাট নেই।"],
"r4R7AZ": ["পরিষ্কারের সময় নেটওয়ার্ক ত্রুটি"],
@@ -5210,6 +5209,7 @@
"ten9en": ["সাম্প্রতিক প্রকল্প"],
"tfDRzk": ["সংরক্ষণ করুন"],
"tfi40B": ["পাতা তৈরি করতে ব্যর্থ"],
+ "tgB_VT": ["সম্পাদক খুলুন"],
"tgWuMB": ["পরিবর্তিত"],
"thnPBX": ["পরবর্তী সম্পাদক ট্যাব সক্রিয় করুন।"],
"ti6aF_": [["0"], " CLI-কে জিজ্ঞেস করুন"],
@@ -5384,6 +5384,7 @@
"un-K1H": ["এই কম্পিউটারেই থাকে। git-এ কমিট হয় না।"],
"un8kBM": ["পাতা তৈরি করা হচ্ছে: ", ["linkTitle"], "।"],
"uoJF_D": ["এটি সেট আপ করা বা শুরু করা খুব কঠিন ছিল"],
+ "uqgCZJ": ["সম্পাদক লুকান"],
"uqs8Gd": [["others", "plural", { "one": ["আরও ", "#", "টি"], "other": ["আরও ", "#", "টি"] }]],
"ur2XSb": ["দৃশ্য সম্পাদক"],
"uraHF0": ["GitLab"],
@@ -5676,6 +5677,7 @@
"xzAmL_": ["স্বয়ংক্রিয়ভাবে অনুমোদিত"],
"xzktOa": ["উইকি লিংক সম্পাদনা করুন"],
"y-LQPF": ["সমাধান করা যায় না এমন ছবি ", ["identity"], "। রেফারেন্সে যান।"],
+ "y0_w13": ["সম্পাদক দেখান"],
"y1eoq1": ["লিংক কপি করুন"],
"y1t8bQ": ["সেটিং-এর বিভাগ"],
"y3aU20": ["পরিবর্তন সংরক্ষণ করুন"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index de20047da..fe6c25ef5 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -1670,6 +1670,7 @@ msgstr "সক্রিয়"
msgid "Active panel content for the selected tab shows here."
msgstr "নির্বাচিত ট্যাবের সক্রিয় প্যানেলের বিষয়বস্তু এখানে দেখা যায়।"
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "কার্যকলাপ"
@@ -1961,6 +1962,10 @@ msgstr "এজেন্ট সংযোগ"
msgid "Agent mode"
msgstr "এজেন্ট মোড"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "এজেন্ট প্যানেল"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Terminal পাঠযোগ্য রাখতে এজেন্ট প্যানেল বন্ধ করা হয়েছে।"
@@ -1983,6 +1988,7 @@ msgstr "এজেন্ট প্রতিলিপি"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "এজেন্ট"
@@ -2179,6 +2185,7 @@ msgstr "অ্যাপ ইনস্ট্যান্স: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "কী বদলেছে তার শুধু-যোগ-হওয়া লগ।"
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "অ্যাপ্লিকেশন"
@@ -2543,6 +2550,10 @@ msgstr "ফিরে যান"
msgid "Back to document view"
msgstr "নথি দৃশ্যে ফিরুন"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "সম্পাদকে ফিরুন"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "ব্যাকলিংক"
@@ -3463,10 +3474,6 @@ msgstr "গুটিয়ে নিন"
msgid "Collapse {keyName}"
msgstr "{keyName} গুটিয়ে নিন"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "এজেন্ট প্যানেল সংকুচিত করুন"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3490,10 +3497,6 @@ msgstr "Ask AI গুটিয়ে নিন"
msgid "Collapse graph"
msgstr "গ্রাফ গুটিয়ে নিন"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Terminal সংকুচিত করুন"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "সংকোচনযোগ্য কনটেন্ট ব্লক (Notion-ধাঁচের টগল)।"
@@ -3661,7 +3664,7 @@ msgstr "ব্যবহারকারী, প্রকল্প ও সংয
msgid "conflict"
msgstr "দ্বন্দ্ব"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "দ্বন্দ্ব"
@@ -4300,6 +4303,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "\"{0}\"-এর প্রতিলিপি বানানো যায়নি: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "সেই অংশটি খুঁজে পাওয়া যায়নি — এটি যে লেখায় ছিল তা পরিবর্তিত হয়ে থাকতে পারে।"
@@ -4665,6 +4669,10 @@ msgstr "এই সেটিংটি সংরক্ষণ করা যায
msgid "Couldn't save your theme preference."
msgstr "আপনার থিম পছন্দ সংরক্ষণ করা যায়নি।"
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "সেই অংশে স্ক্রল করা যায়নি। আবার চেষ্টা করুন।"
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "রিপোর্ট পাঠানো যায়নি"
@@ -5285,6 +5293,7 @@ msgid "Diff render mode"
msgstr "পার্থক্য রেন্ডার মোড"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "পার্থক্য অনুপলব্ধ"
@@ -5406,6 +5415,10 @@ msgstr "নথি পাওয়া যায়নি"
msgid "Document outline"
msgstr "নথির রূপরেখা"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "নথি প্যানেল"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "নথি প্যানেল"
@@ -5729,6 +5742,7 @@ msgstr "{boldName} সেখানেই সম্পাদনা করা হ
msgid "Editing broken MDX source: {reason}"
msgstr "ভাঙা MDX সোর্স সম্পাদনা করা হচ্ছে: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "সম্পাদক"
@@ -5741,6 +5755,10 @@ msgstr "সম্পাদক মোড"
msgid "editor pane"
msgstr "এডিটর প্যান"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "সম্পাদক প্যান"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "সম্পাদকের নির্বাচন"
@@ -6687,6 +6705,7 @@ msgstr "ফাইল: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "ফাইলের নাম"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "ফাইল"
@@ -7349,11 +7368,17 @@ msgstr "বিবরণ লুকান"
msgid "Hide document panel"
msgstr "নথি প্যানেল লুকান"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "সম্পাদক লুকান"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "বাইরের URL নোড লুকান"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Files লুকান"
@@ -7384,12 +7409,13 @@ msgid "Hide Others"
msgstr "অন্যগুলি লুকান"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "প্যানেল লুকান"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "প্যানেল লুকান ({panelShortcutLabel})"
@@ -9004,11 +9030,11 @@ msgstr "লিংকের লক্ষ্য, অ্যাংকর ও প্
msgid "More"
msgstr "আরও"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "আরও ক্রিয়া"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "আরও ক্রিয়া ({syncAttentionLabel})"
@@ -10058,6 +10084,10 @@ msgstr "আপনি না বলা পর্যন্ত কিছুই স
msgid "Nothing moves until you ask."
msgstr "আপনি না বলা পর্যন্ত কিছুই সরবে না।"
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "কিছুই খোলা নেই"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "এখনও কিছুই নির্ধারিত হয়নি।"
@@ -10107,7 +10137,7 @@ msgstr "বন্ধ — বাইরের লিংক কেবল তাদ
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "বন্ধ — অনুসন্ধান কেবল কীওয়ার্ড দিয়ে ক্রম করে। কোনো বিষয়বস্তু এই কম্পিউটার ছেড়ে যায় না।"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "অফলাইন"
@@ -10273,13 +10303,9 @@ msgstr "{tooltipName}-এর জন্য কার্যকলাপ প্য
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "{tooltipName}-এর জন্য কার্যকলাপ প্যানেল খুলুন, {realCurrentDoc} সম্পাদনা করা হচ্ছে"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "এজেন্ট প্যানেল খুলুন"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "এজেন্ট প্যানেল খুলুন — {liveThreadCount, plural, one {# সক্রিয় এজেন্ট থ্রেড} other {# সক্রিয় এজেন্ট থ্রেড}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "এজেন্ট খুলুন"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10326,6 +10352,10 @@ msgstr "নির্বাচিত ফাইল-ট্রি আইটেমগ
msgid "Open documents tagged #{chip}"
msgstr "#{chip} ট্যাগযুক্ত নথি খুলুন"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "সম্পাদক খুলুন"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "ইমেইলের খসড়া খুলুন"
@@ -10497,7 +10527,7 @@ msgstr "সোর্স lint প্যানেল খুলুন"
msgid "Open source: {mirrorSrc}"
msgstr "উৎস খুলুন: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "টার্মিনাল খুলুন"
@@ -11058,6 +11088,14 @@ msgstr "উপরে সরান"
msgid "pane {0}"
msgstr "প্যান {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "প্যান {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "প্যানেলসমূহ"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "অনুচ্ছেদ"
@@ -11466,6 +11504,7 @@ msgstr "প্রকল্প"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "প্রকল্প"
@@ -11859,7 +11898,7 @@ msgstr "প্রস্তাবিত"
msgid "Recommended agent skill"
msgstr "প্রস্তাবিত এজেন্ট দক্ষতা"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "পুনরায় যুক্ত হওয়া দরকার"
@@ -12448,10 +12487,19 @@ msgstr "দৃশ্যের ছাঁকনি রিসেট করুন"
msgid "Resize {handleKey}"
msgstr "{handleKey}-এর আকার বদলান"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "নথি প্যানেলের আকার পরিবর্তন করুন"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "স্কিল প্যানেলের আকার পরিবর্তন করুন"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "টার্মিনালের আকার পরিবর্তন করুন"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "আপনার টার্মিনালে দ্বন্দ্ব মীমাংসা করুন"
@@ -12864,9 +12912,8 @@ msgid "Scroll to start"
msgstr "শুরুতে স্ক্রল করুন"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12876,10 +12923,6 @@ msgstr "খুঁজুন"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "অর্থের ভিত্তিতে \"{semanticSubmitQuery}\" খুঁজুন"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "খুঁজুন ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "এজেন্ট খুঁজুন"
@@ -13545,6 +13588,11 @@ msgstr "চিত্র দেখান"
msgid "Show document panel"
msgstr "নথি প্যানেল দেখান"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "সম্পাদক দেখান"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "বাইরের URL নোড দেখান"
@@ -13553,7 +13601,7 @@ msgstr "বাইরের URL নোড দেখান"
msgid "Show fewer"
msgstr "কম দেখান"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Files দেখান"
@@ -13610,12 +13658,12 @@ msgid "Show original"
msgstr "মূল সংস্করণ দেখান"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "প্যানেল দেখান"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "প্যানেল দেখান ({panelShortcutLabel})"
@@ -14434,7 +14482,7 @@ msgstr "সিঙ্ক মোড"
msgid "Sync now"
msgstr "এখনই সিঙ্ক করুন"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "সিঙ্ক থেমে আছে"
@@ -14612,6 +14660,7 @@ msgstr "উপলব্ধ টেমপ্লেট"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16412,6 +16461,10 @@ msgstr "ফোল্ডার প্রপার্টি হালনাগা
msgid "Updated to Version {version}"
msgstr "সংস্করণ {version}-এ হালনাগাদ হয়েছে"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "হালনাগাদ ও মতামত"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "হালনাগাদ আসতে থাকে"
@@ -16985,10 +17038,6 @@ msgstr "ওয়ার্কস্পেস"
msgid "Workspace Command Palette"
msgstr "ওয়ার্কস্পেস কমান্ড প্যালেট"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "ওয়ার্কস্পেস নেভিগেশন"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 2482c58cb..92743449d 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -347,6 +347,7 @@
"3Fcb0I": ["Open graph"],
"3HAPpl": ["No schemas match your search."],
"3HNlwb": ["Hello, world!"],
+ "3HOAcR": ["Agent panel"],
"3Ib6FN": ["Move down"],
"3J7d2N": ["Big section heading."],
"3JYy1p": ["Branch ", ["0"], " no longer exists. Cloned to default branch."],
@@ -533,6 +534,7 @@
],
"5OTgC7": ["Open and focus the bottom Ask AI prompt composer."],
"5OqaJi": ["Enter a project name"],
+ "5Q9-G-": ["Document panel"],
"5QGTaA": ["Could not copy relative path"],
"5RiC8D": [
"Discovery skills are managed for all AI tools together. Install this one from Settings → Skills Studio."
@@ -762,6 +764,7 @@
"7cAW1G": ["No API key is set for this endpoint. Add one above."],
"7czmD1": ["OpenKnowledge looked up the authoring palette"],
"7d1a0d": ["Public"],
+ "7dDoQu": ["Editor pane"],
"7dZnmw": ["Relevance"],
"7hctf2": ["Describe the project you want to create"],
"7idx48": ["OKF agent skill installed"],
@@ -1268,7 +1271,6 @@
"DWJtEo": ["What happens next"],
"DXd9LM": ["New worktree"],
"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],
- "DbCfXV": ["Search (", ["searchShortcutLabel"], ")"],
"DbILZA": ["No matches. Some files are excluded from search (hidden or ignored files)."],
"DcFr-y": ["OpenKnowledge deleted a document"],
"DcH8-w": ["Move ", ["0"], " to Project"],
@@ -1481,6 +1483,7 @@
")."
],
"FWSjnp": ["Edit source pane and code property fields"],
+ "FYy2EN": ["Resize document panel"],
"FZtBeR": ["Enable ", ["0"]],
"FeXcUS": [
["display"],
@@ -1538,6 +1541,7 @@
", but that account's credentials couldn't be used."
],
"GBQjiV": ["Add skill"],
+ "GCrhIF": ["Panels"],
"GDvlUT": ["Role"],
"GEyl32": ["Starting terminal…"],
"GGsM4y": ["Selected in graph"],
@@ -2088,7 +2092,6 @@
"A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted."
],
"MTs6g3": ["Couldn't reconnect after server restart"],
- "MU_NVW": ["Collapse Terminal"],
"MUrVEo": ["No recent projects."],
"MV-Dkb": ["Found ", ["countDisplay"], " markdown files"],
"MVxpbf": ["Find and replace"],
@@ -2862,13 +2865,13 @@
],
"V48OUT": ["You deleted <0>", ["filePath"], "</0> locally, but it was modified upstream."],
"V4JHny": ["Sharing supports GitHub remotes only."],
- "V6AIOn": ["Workspace navigation"],
"V6e25h": ["Theme preview"],
"V7QxyT": ["Connection dropped"],
"VAHWL_": ["Connected as <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"Build and keep track of the world behind your story. A home for your characters, places, factions, and the lore that ties them together, so details stay consistent as you write."
],
+ "VBtCdv": ["Couldn't scroll to that passage. Try again."],
"VFQXPl": [
"External link previews show a card with the site name, page title, and description when you hover a link."
],
@@ -3004,7 +3007,6 @@
"X2zUS5": ["Delete this comment"],
"X3MMeA": ["None of these problems have an automatic fix."],
"X59Fx2": ["Couldn't open this document in Slidev."],
- "X7ShnN": ["Open agents panel"],
"X8kjQX": ["Re-authenticate with GitHub"],
"X9VpsP": ["Loading folder contents"],
"XA9uvc": ["OpenKnowledge checks for and downloads updates in the background."],
@@ -3149,6 +3151,7 @@
"YS9mSt": ["Updated \"", ["name"], "\" from ", ["0"]],
"YSFv5w": ["No git repository — config sharing does not apply here."],
"YScUUO": ["Fetches a web page"],
+ "YStFYH": ["Open agents"],
"YTLmTM": ["Remove the parent <0>.git</0> folder"],
"YW7Q86": ["Search settings not yet loaded — try again in a moment"],
"YWK2zy": ["Conflict diff for ", ["fileName"]],
@@ -3425,6 +3428,7 @@
"No AI tools detected yet. Once you install one, connect it from Settings > This project."
],
"aTDVi6": ["Kept your content"],
+ "aV2vel": ["Pane ", ["number"]],
"aWlJai": ["Starting sign-in flow"],
"aXkLuE": ["Malformed apply response"],
"a_u4ck": ["Loading tags"],
@@ -3910,6 +3914,7 @@
"f1-q9m": ["keeps the skills"],
"f14doC": ["Slidev"],
"f1XQyZ": ["Move block"],
+ "f3YhVJ": ["Nothing open"],
"f65AOQ": ["Start from"],
"f6suyZ": ["Changes requested"],
"f8fH8W": ["Design"],
@@ -3927,6 +3932,7 @@
"fKsRVO": ["Skills from ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["Couldn't save the auto-update setting: ", ["0"]],
"fNr-MX": ["Disable semantic search"],
+ "fObclJ": ["Back to editor"],
"fOzzSV": ["Link target \"", ["shown"], "\" does not resolve to an existing file."],
"fRVBiq": [
"Adds telemetry, server state, and runtime info when available. Credentials are always removed; document names, if included, appear in cleartext (not redacted)."
@@ -4013,7 +4019,6 @@
["descriptorLabel"],
"> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
],
- "g5V4_P": ["Collapse agent panel"],
"g5w1sF": [
"Pick a folder to merge INTO ",
["display"],
@@ -4252,14 +4257,6 @@
"i04BJx": ["Lives outside this project — read-only here."],
"i09An-": ["Restored an earlier version (", ["0"], ")"],
"i1flq_": ["Wiki link suggestions"],
- "i25FHa": [
- "Open agents panel — ",
- [
- "liveThreadCount",
- "plural",
- { "one": ["#", " live agent thread"], "other": ["#", " live agent threads"] }
- ]
- ],
"i3f2kh": ["No matching commands."],
"i6o7XB": ["Search languages"],
"i92eAT": ["We'll create a repository and start syncing — no terminal needed."],
@@ -4796,6 +4793,7 @@
],
"n7aopT": ["Editor mode"],
"n81AV0": [["owner"], "/", ["name"], " already exists. Pick a different name."],
+ "nBFK5w": ["Resize terminal"],
"nBHvPL": ["Cancel editing"],
"nBgzKO": ["Make this the source — the skill's real folder moves here"],
"nCzR-G": ["Copy code ", ["userCode"]],
@@ -5150,6 +5148,7 @@
"qyLmWw": ["Source editor search panel"],
"qze9od": ["This folder is also ", ["alsoAffects"], "'s."],
"r-OJYm": ["Enter a valid branch name (no spaces, no leading dot, no \"..\")."],
+ "r-wzd8": ["Updates and feedback"],
"r2eKE3": ["Sign in to ", ["agentName"], " first"],
"r3iaI0": ["No chats yet."],
"r4R7AZ": ["Network error during cleanup"],
@@ -5401,6 +5400,7 @@
"ten9en": ["Recent project"],
"tfDRzk": ["Save"],
"tfi40B": ["Failed to create page"],
+ "tgB_VT": ["Open editor"],
"tgWuMB": ["Modified"],
"thnPBX": ["Activate the next editor tab."],
"ti6aF_": ["Ask ", ["0"], " CLI"],
@@ -5585,6 +5585,7 @@
"un-K1H": ["Stays on this computer. Not committed to git."],
"un8kBM": ["Creating page: ", ["linkTitle"], "."],
"uoJF_D": ["It was too hard to set up or get started"],
+ "uqgCZJ": ["Hide Editor"],
"uqs8Gd": [["others", "plural", { "one": ["#", " other"], "other": ["#", " others"] }]],
"ur2XSb": ["Visual editor"],
"uraHF0": ["GitLab"],
@@ -5890,6 +5891,7 @@
"xzAmL_": ["Auto-approved"],
"xzktOa": ["Edit wiki link"],
"y-LQPF": ["Unresolvable image ", ["identity"], ". Go to reference."],
+ "y0_w13": ["Show Editor"],
"y1eoq1": ["Copy link"],
"y1t8bQ": ["Settings sections"],
"y3aU20": ["Save changes"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 1ca361a4d..3aea470b2 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1674,6 +1674,7 @@ msgstr "Active"
msgid "Active panel content for the selected tab shows here."
msgstr "Active panel content for the selected tab shows here."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "Activity"
@@ -1965,6 +1966,10 @@ msgstr "Agent connections"
msgid "Agent mode"
msgstr "Agent mode"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "Agent panel"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Agent panel closed to keep Terminal readable."
@@ -1987,6 +1992,7 @@ msgstr "Agent transcript"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "Agents"
@@ -2183,6 +2189,7 @@ msgstr "App instance: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "Append-only log of what changed."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "Application"
@@ -2547,6 +2554,10 @@ msgstr "Back"
msgid "Back to document view"
msgstr "Back to document view"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "Back to editor"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "Backlinks"
@@ -3467,10 +3478,6 @@ msgstr "Collapse"
msgid "Collapse {keyName}"
msgstr "Collapse {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "Collapse agent panel"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "Collapse Ask AI"
msgid "Collapse graph"
msgstr "Collapse graph"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Collapse Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "Collapsible content block (Notion-style toggle)."
@@ -3665,7 +3668,7 @@ msgstr "Configure user, project, and integration settings."
msgid "conflict"
msgstr "conflict"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Conflict"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "Couldn't duplicate \"{0}\": {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "Couldn't find that passage — the text it was on may have changed."
@@ -4669,6 +4673,10 @@ msgstr "Couldn't save this setting. Try again."
msgid "Couldn't save your theme preference."
msgstr "Couldn't save your theme preference."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "Couldn't scroll to that passage. Try again."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "Couldn't send the report"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "Diff render mode"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Diff unavailable"
@@ -5410,6 +5419,10 @@ msgstr "Document not found"
msgid "Document outline"
msgstr "Document outline"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "Document panel"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "Document panels"
@@ -5733,6 +5746,7 @@ msgstr "Editing {boldName} in place. Changes save straight to your editor's copy
msgid "Editing broken MDX source: {reason}"
msgstr "Editing broken MDX source: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "Editor"
@@ -5745,6 +5759,10 @@ msgstr "Editor mode"
msgid "editor pane"
msgstr "editor pane"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "Editor pane"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Editor selection"
@@ -6691,6 +6709,7 @@ msgstr "File: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "Filename"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "Files"
@@ -7353,11 +7372,17 @@ msgstr "Hide details"
msgid "Hide document panel"
msgstr "Hide document panel"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "Hide Editor"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "Hide external URL nodes"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Hide Files"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "Hide Others"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "Hide panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "Hide panel ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "Modify the link target, anchor, and display label."
msgid "More"
msgstr "More"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "More actions"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "More actions ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "Nothing moves until you ask — pull and push from the sync menu."
msgid "Nothing moves until you ask."
msgstr "Nothing moves until you ask."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "Nothing open"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Nothing set yet."
@@ -10111,7 +10141,7 @@ msgstr "Off — external links show only their URL. No requests leave this compu
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Off — search ranks by keyword only. No content leaves this computer."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "Offline"
@@ -10277,13 +10307,9 @@ msgstr "Open activity panel for {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "Open agents panel"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "Open agents"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "Open delete confirmation for the selected file-tree items."
msgid "Open documents tagged #{chip}"
msgstr "Open documents tagged #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "Open editor"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "Open email draft"
@@ -10501,7 +10531,7 @@ msgstr "Open source lint panel"
msgid "Open source: {mirrorSrc}"
msgstr "Open source: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "Open terminal"
@@ -11062,6 +11092,14 @@ msgstr "Pan up"
msgid "pane {0}"
msgstr "pane {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "Pane {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "Panels"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Paragraph"
@@ -11470,6 +11508,7 @@ msgstr "project"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Project"
@@ -11863,7 +11902,7 @@ msgstr "Recommended"
msgid "Recommended agent skill"
msgstr "Recommended agent skill"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "Reconnect required"
@@ -12452,10 +12491,19 @@ msgstr "Reset view filters"
msgid "Resize {handleKey}"
msgstr "Resize {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "Resize document panel"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "Resize skills panel"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "Resize terminal"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Resolve conflict in your terminal"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "Scroll to start"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "Search"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "Search \"{semanticSubmitQuery}\" by meaning"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "Search ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "Search agents"
@@ -13549,6 +13592,11 @@ msgstr "Show diagram"
msgid "Show document panel"
msgstr "Show document panel"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "Show Editor"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "Show external URL nodes"
@@ -13557,7 +13605,7 @@ msgstr "Show external URL nodes"
msgid "Show fewer"
msgstr "Show fewer"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Show Files"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "Show original"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "Show panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "Show panel ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "Sync mode"
msgid "Sync now"
msgstr "Sync now"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "Sync paused"
@@ -14616,6 +14664,7 @@ msgstr "Templates available"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "updated folder properties"
msgid "Updated to Version {version}"
msgstr "Updated to Version {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "Updates and feedback"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "Updates flow in"
@@ -16989,10 +17042,6 @@ msgstr "Workspace"
msgid "Workspace Command Palette"
msgstr "Workspace Command Palette"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "Workspace navigation"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index 5f0b463bd..49db8f26f 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -393,6 +393,7 @@
"3Fcb0I": ["Abrir el grafo"],
"3HAPpl": ["Ningún esquema coincide con tu búsqueda."],
"3HNlwb": ["¡Hola, mundo!"],
+ "3HOAcR": ["Panel de agentes"],
"3Ib6FN": ["Bajar"],
"3J7d2N": ["Encabezado de sección grande."],
"3JYy1p": ["La rama ", ["0"], " ya no existe. Se clonó en la rama por defecto."],
@@ -618,6 +619,7 @@
],
"5OTgC7": ["Abre y enfoca el compositor de prompts de Preguntar a la IA de abajo."],
"5OqaJi": ["Escribe un nombre de proyecto"],
+ "5Q9-G-": ["Panel del documento"],
"5QGTaA": ["No se pudo copiar la ruta relativa"],
"5RiC8D": [
"Las habilidades de descubrimiento se administran juntas para todas las herramientas de IA. Instala esta desde Ajustes → Estudio de habilidades."
@@ -890,6 +892,7 @@
"7cAW1G": ["No hay ninguna clave de API definida para este endpoint. Añade una arriba."],
"7czmD1": ["OpenKnowledge consultó la paleta de edición"],
"7d1a0d": ["Público"],
+ "7dDoQu": ["Panel del editor"],
"7dZnmw": ["Relevancia"],
"7hctf2": ["Describe el proyecto que quieres crear"],
"7idx48": ["Habilidad de agente OKF instalada"],
@@ -1477,7 +1480,6 @@
"DWJtEo": ["Qué pasa después"],
"DXd9LM": ["Worktree nuevo"],
"D_WKe_": ["Haz clic en el avatar de un agente en la barra de presencia para ver su sesión."],
- "DbCfXV": ["Buscar (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"Sin coincidencias. Algunos archivos quedan fuera de la búsqueda (archivos ocultos o ignorados)."
],
@@ -1709,6 +1711,7 @@
")."
],
"FWSjnp": ["Panel de edición de código y campos de propiedad de tipo código"],
+ "FYy2EN": ["Redimensionar el panel del documento"],
"FZtBeR": ["Activar ", ["0"]],
"FeXcUS": [
["display"],
@@ -1780,6 +1783,7 @@
", pero no se pudieron usar las credenciales de esa cuenta."
],
"GBQjiV": ["Añadir habilidad"],
+ "GCrhIF": ["Paneles"],
"GDvlUT": ["Función"],
"GEyl32": ["Iniciando terminal…"],
"GGsM4y": ["Seleccionado en el grafo"],
@@ -2425,7 +2429,6 @@
"Un enlace simbólico apunta a la carpeta de origen en lugar de ser una carpeta propia. Todas las ubicaciones leen exactamente los mismos bytes, así que nada se desvía, y una ubicación deja de funcionar si se elimina el origen."
],
"MTs6g3": ["No se pudo reconectar tras el reinicio del servidor"],
- "MU_NVW": ["Contraer Terminal"],
"MUrVEo": ["No hay proyectos recientes."],
"MV-Dkb": ["Se encontraron ", ["countDisplay"], " archivos markdown"],
"MVxpbf": ["Buscar y reemplazar"],
@@ -3286,13 +3289,13 @@
],
"V48OUT": ["Eliminaste <0>", ["filePath"], "</0> en local, pero se modificó en el remoto."],
"V4JHny": ["Solo se admite compartir con remotos de GitHub."],
- "V6AIOn": ["Navegación del espacio de trabajo"],
"V6e25h": ["Vista previa del tema"],
"V7QxyT": ["Se perdió la conexión"],
"VAHWL_": ["Conectado como <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"Construye y ordena el mundo que hay detrás de tu historia. Un sitio para tus personajes, lugares, facciones y la mitología que los une, para que los detalles no se contradigan mientras escribes."
],
+ "VBtCdv": ["No se pudo desplazar hasta ese pasaje. Vuelve a intentarlo."],
"VFQXPl": [
"La vista previa de enlaces externos muestra una tarjeta con el nombre del sitio, el título de la página y la descripción al pasar el cursor por un enlace."
],
@@ -3475,7 +3478,6 @@
"X2zUS5": ["Eliminar este comentario"],
"X3MMeA": ["Ninguno de estos problemas tiene arreglo automático."],
"X59Fx2": ["No se pudo abrir este documento en Slidev."],
- "X7ShnN": ["Abrir el panel de agentes"],
"X8kjQX": ["Volver a autenticarse con GitHub"],
"X9VpsP": ["Cargando el contenido de la carpeta"],
"XA9uvc": ["OpenKnowledge busca y descarga actualizaciones en segundo plano."],
@@ -3646,6 +3648,7 @@
"YS9mSt": ["Se actualizó \"", ["name"], "\" desde ", ["0"]],
"YSFv5w": ["No hay repositorio de git: compartir configuración no aplica aquí."],
"YScUUO": ["Obtiene una página web"],
+ "YStFYH": ["Abrir agentes"],
"YTLmTM": ["Eliminar la carpeta <0>.git</0> superior"],
"YW7Q86": ["Los ajustes de búsqueda aún no se han cargado; inténtalo de nuevo en un momento"],
"YWK2zy": ["Diferencias del conflicto en ", ["fileName"]],
@@ -3940,6 +3943,7 @@
"Todavía no se ha detectado ninguna herramienta de IA. Cuando instales una, conéctala desde Ajustes > Este proyecto."
],
"aTDVi6": ["Tu contenido se conservó"],
+ "aV2vel": ["Panel ", ["number"]],
"aWlJai": ["Iniciando el flujo de inicio de sesión"],
"aXkLuE": ["Respuesta de aplicación con formato incorrecto"],
"a_u4ck": ["Cargando etiquetas"],
@@ -4454,7 +4458,7 @@
"eQkgKV": ["Instalado"],
"eQn7nI": ["Cargando uso compartido de la configuración"],
"eQxm13": ["No se pudo actualizar la ubicación de los adjuntos — ", ["detail"]],
- "eRSPr9": ["Abrir la terminal"],
+ "eRSPr9": ["Abrir terminal"],
"eTL5y9": ["Mostrar la vista previa de la selección"],
"eTsJYJ": ["descripción"],
"eUFXS1": ["Ordenar las habilidades"],
@@ -4534,6 +4538,7 @@
"f1-q9m": ["conserva las habilidades"],
"f14doC": ["Slidev"],
"f1XQyZ": ["Mover el bloque"],
+ "f3YhVJ": ["Nada abierto"],
"f65AOQ": ["Empezar desde"],
"f6suyZ": ["Cambios solicitados"],
"f8fH8W": ["Diseño"],
@@ -4553,6 +4558,7 @@
"fKsRVO": ["Habilidades de ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["No se pudo guardar el ajuste de actualización automática: ", ["0"]],
"fNr-MX": ["Desactivar la búsqueda semántica"],
+ "fObclJ": ["Volver al editor"],
"fOzzSV": ["El destino del enlace «", ["shown"], "» no corresponde a un archivo existente."],
"fRVBiq": [
"Añade telemetría, estado del servidor e información de ejecución cuando está disponible. Las credenciales siempre se eliminan; los nombres de documento, si se incluyen, aparecen en texto plano (sin ocultar)."
@@ -4662,7 +4668,6 @@
["descriptorLabel"],
"> (probablemente por una propiedad incorrecta). Copia el código para ver qué falló o elimina el bloque."
],
- "g5V4_P": ["Contraer el panel de agentes"],
"g5w1sF": [
"Elige una carpeta para fusionarla DENTRO de ",
["display"],
@@ -4928,18 +4933,6 @@
"i04BJx": ["Vive fuera de este proyecto — aquí es de solo lectura."],
"i09An-": ["Se restauró una versión anterior (", ["0"], ")"],
"i1flq_": ["Sugerencias de enlaces wiki"],
- "i25FHa": [
- "Abrir el panel de agentes — ",
- [
- "liveThreadCount",
- "plural",
- {
- "one": ["#", " hilo de agente activo"],
- "many": ["#", " hilos de agente activos"],
- "other": ["#", " hilos de agente activos"]
- }
- ]
- ],
"i3f2kh": ["Ningún comando coincide."],
"i6o7XB": ["Buscar idiomas"],
"i92eAT": ["Crearemos un repositorio y empezaremos a sincronizar; no hace falta terminal."],
@@ -5530,6 +5523,7 @@
],
"n7aopT": ["Modo del editor"],
"n81AV0": [["owner"], "/", ["name"], " ya existe. Elige otro nombre."],
+ "nBFK5w": ["Redimensionar la terminal"],
"nBHvPL": ["Cancelar edición"],
"nBgzKO": ["Convertir esto en el origen: la carpeta real de la habilidad se traslada aquí"],
"nCzR-G": ["Copiar el código ", ["userCode"]],
@@ -5934,6 +5928,7 @@
"qyLmWw": ["Panel de búsqueda del editor de código"],
"qze9od": ["Esta carpeta también es de ", ["alsoAffects"], "."],
"r-OJYm": ["Escribe un nombre de rama válido (sin espacios, sin punto inicial, sin \"..\")."],
+ "r-wzd8": ["Actualizaciones y comentarios"],
"r2eKE3": ["Inicia sesión primero en ", ["agentName"]],
"r3iaI0": ["Aún no hay chats."],
"r4R7AZ": ["Error de red durante la limpieza"],
@@ -6206,6 +6201,7 @@
"ten9en": ["Proyecto reciente"],
"tfDRzk": ["Guardar"],
"tfi40B": ["No se pudo crear la página"],
+ "tgB_VT": ["Abrir editor"],
"tgWuMB": ["Modificado"],
"thnPBX": ["Activa la siguiente pestaña del editor."],
"ti6aF_": ["Preguntar a la CLI de ", ["0"]],
@@ -6404,6 +6400,7 @@
"un-K1H": ["Se queda en este equipo. No se guarda en git."],
"un8kBM": ["Creando la página: ", ["linkTitle"], "."],
"uoJF_D": ["Era demasiado difícil de configurar o de empezar a usar"],
+ "uqgCZJ": ["Ocultar Editor"],
"uqs8Gd": [
["others", "plural", { "one": ["#", " más"], "many": ["#", " más"], "other": ["#", " más"] }]
],
@@ -6756,6 +6753,7 @@
"xzAmL_": ["Aprobado automáticamente"],
"xzktOa": ["Editar el enlace wiki"],
"y-LQPF": ["No se puede resolver la imagen ", ["identity"], ". Ir a la referencia."],
+ "y0_w13": ["Mostrar Editor"],
"y1eoq1": ["Copiar enlace"],
"y1t8bQ": ["Secciones de ajustes"],
"y3aU20": ["Guardar los cambios"],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 964aebc8f..97c53495c 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -1674,6 +1674,7 @@ msgstr "Activo"
msgid "Active panel content for the selected tab shows here."
msgstr "Aquí se muestra el contenido del panel activo de la pestaña seleccionada."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "Actividad"
@@ -1965,6 +1966,10 @@ msgstr "Conexiones de agentes"
msgid "Agent mode"
msgstr "Modo agente"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "Panel de agentes"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Se cerró el panel de agentes para mantener Terminal legible."
@@ -1987,6 +1992,7 @@ msgstr "Transcripción del agente"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "Agentes"
@@ -2183,6 +2189,7 @@ msgstr "Instancia de la aplicación: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "Registro de solo anexado con lo que ha cambiado."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "Aplicación"
@@ -2547,6 +2554,10 @@ msgstr "Atrás"
msgid "Back to document view"
msgstr "Volver a la vista de documento"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "Volver al editor"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "Retroenlaces"
@@ -3467,10 +3478,6 @@ msgstr "Contraer"
msgid "Collapse {keyName}"
msgstr "Contraer {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "Contraer el panel de agentes"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "Contraer Preguntar a la IA"
msgid "Collapse graph"
msgstr "Contraer el grafo"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Contraer Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "Bloque de contenido plegable (alternador estilo Notion)."
@@ -3665,7 +3668,7 @@ msgstr "Configura los ajustes de usuario, de proyecto y de integraciones."
msgid "conflict"
msgstr "conflicto"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Conflicto"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "No se pudo duplicar \"{0}\": {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "No se pudo encontrar ese pasaje — puede que el texto en el que estaba haya cambiado."
@@ -4669,6 +4673,10 @@ msgstr "No se pudo guardar este ajuste. Inténtalo de nuevo."
msgid "Couldn't save your theme preference."
msgstr "No se pudo guardar tu preferencia de tema."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "No se pudo desplazar hasta ese pasaje. Vuelve a intentarlo."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "No se pudo enviar el informe"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "Modo de renderizado de diferencias"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "No hay diferencias disponibles"
@@ -5410,6 +5419,10 @@ msgstr "No se encontró el documento"
msgid "Document outline"
msgstr "Esquema del documento"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "Panel del documento"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "Paneles del documento"
@@ -5733,6 +5746,7 @@ msgstr "Editando {boldName} en su sitio. Los cambios se guardan directamente en
msgid "Editing broken MDX source: {reason}"
msgstr "Editando código MDX defectuoso: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "Editor"
@@ -5745,6 +5759,10 @@ msgstr "Modo del editor"
msgid "editor pane"
msgstr "panel del editor"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "Panel del editor"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Selección del editor"
@@ -6691,6 +6709,7 @@ msgstr "Archivo: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "Nombre del archivo"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "Archivos"
@@ -7353,11 +7372,17 @@ msgstr "Ocultar detalles"
msgid "Hide document panel"
msgstr "Ocultar el panel del documento"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "Ocultar Editor"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "Ocultar los nodos de URL externas"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Ocultar Archivos"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "Ocultar los demás"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "Ocultar el panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "Ocultar el panel ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "Modifica el destino del enlace, el ancla y el texto mostrado."
msgid "More"
msgstr "Más"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "Más acciones"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "Más acciones ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "Nada se mueve hasta que lo pidas: usa Pull y Push desde el menú de sinc
msgid "Nothing moves until you ask."
msgstr "Nada se mueve hasta que lo pidas."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "Nada abierto"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Todavía no hay nada definido."
@@ -10111,7 +10141,7 @@ msgstr "Desactivado: los enlaces externos solo muestran su URL. No sale ninguna
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Desactivada: la búsqueda ordena solo por palabras clave. No sale ningún contenido de este equipo."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "Sin conexión"
@@ -10277,13 +10307,9 @@ msgstr "Abrir el panel de actividad de {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "Abrir el panel de actividad de {tooltipName}, que está editando {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "Abrir el panel de agentes"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "Abrir el panel de agentes — {liveThreadCount, plural, one {# hilo de agente activo} many {# hilos de agente activos} other {# hilos de agente activos}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "Abrir agentes"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "Abre la confirmación de eliminación de los elementos seleccionados del
msgid "Open documents tagged #{chip}"
msgstr "Abrir los documentos etiquetados con #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "Abrir editor"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "Abrir el borrador de correo"
@@ -10501,9 +10531,9 @@ msgstr "Abrir el panel de análisis del código"
msgid "Open source: {mirrorSrc}"
msgstr "Abrir el origen: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
-msgstr "Abrir la terminal"
+msgstr "Abrir terminal"
#: src/components/acp/thread-auth-offer.ts
msgid "Open terminal to sign in"
@@ -11062,6 +11092,14 @@ msgstr "Desplazar hacia arriba"
msgid "pane {0}"
msgstr "panel {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "Panel {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "Paneles"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Párrafo"
@@ -11470,6 +11508,7 @@ msgstr "proyecto"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Proyecto"
@@ -11863,7 +11902,7 @@ msgstr "Recomendado"
msgid "Recommended agent skill"
msgstr "Habilidad de agente recomendada"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "Hay que reconectar"
@@ -12452,10 +12491,19 @@ msgstr "Restablecer los filtros de vista"
msgid "Resize {handleKey}"
msgstr "Redimensionar {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "Redimensionar el panel del documento"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "Redimensionar el panel de Habilidades"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "Redimensionar la terminal"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Resuelve el conflicto en tu terminal"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "Desplazar hasta el principio"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "Buscar"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "Buscar \"{semanticSubmitQuery}\" por significado"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "Buscar ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "Buscar agentes"
@@ -13549,6 +13592,11 @@ msgstr "Mostrar el diagrama"
msgid "Show document panel"
msgstr "Mostrar el panel del documento"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "Mostrar Editor"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "Mostrar los nodos de URL externas"
@@ -13557,7 +13605,7 @@ msgstr "Mostrar los nodos de URL externas"
msgid "Show fewer"
msgstr "Mostrar menos"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Mostrar Archivos"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "Mostrar original"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "Mostrar el panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "Mostrar el panel ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "Modo de sincronización"
msgid "Sync now"
msgstr "Sincronizar ahora"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "Sincronización en pausa"
@@ -14616,6 +14664,7 @@ msgstr "Plantillas disponibles"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "se actualizaron las propiedades de la carpeta"
msgid "Updated to Version {version}"
msgstr "Actualizado a la versión {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "Actualizaciones y comentarios"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "Las actualizaciones llegan solas"
@@ -16989,10 +17042,6 @@ msgstr "Espacio de trabajo"
msgid "Workspace Command Palette"
msgstr "Paleta de comandos del espacio de trabajo"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "Navegación del espacio de trabajo"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 47aaa090c..6101993df 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -411,6 +411,7 @@
"3Fcb0I": ["Ouvrir le graphe"],
"3HAPpl": ["Aucun schéma ne correspond à votre recherche."],
"3HNlwb": ["Bonjour, tout le monde !"],
+ "3HOAcR": ["Panneau des agents"],
"3Ib6FN": ["Descendre"],
"3J7d2N": ["Grand titre de section."],
"3JYy1p": ["La branche ", ["0"], " n'existe plus. Clonage effectué sur la branche par défaut."],
@@ -645,6 +646,7 @@
],
"5OTgC7": ["Ouvre et met le focus sur la zone d'invite Demander à l'IA en bas."],
"5OqaJi": ["Saisissez un nom de projet"],
+ "5Q9-G-": ["Panneau du document"],
"5QGTaA": ["Impossible de copier le chemin relatif"],
"5RiC8D": [
"Les compétences de découverte sont gérées ensemble pour tous les outils d’IA. Installez celle-ci depuis Paramètres → Studio de compétences."
@@ -925,6 +927,7 @@
],
"7czmD1": ["OpenKnowledge a consulté la palette de rédaction"],
"7d1a0d": ["Public"],
+ "7dDoQu": ["Volet de l'éditeur"],
"7dZnmw": ["Pertinence"],
"7hctf2": ["Décrivez le projet que vous voulez créer"],
"7idx48": ["Compétence d'agent OKF installée"],
@@ -1514,7 +1517,6 @@
"DWJtEo": ["Ce qui se passe ensuite"],
"DXd9LM": ["Nouveau worktree"],
"D_WKe_": ["Cliquez sur l'avatar d'un agent dans la barre de présence pour voir sa session."],
- "DbCfXV": ["Rechercher (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"Aucune correspondance. Certains fichiers sont exclus de la recherche (fichiers masqués ou ignorés)."
],
@@ -1749,6 +1751,7 @@
")."
],
"FWSjnp": ["Volet Modifier la source et champs de propriétés de type code"],
+ "FYy2EN": ["Redimensionner le panneau du document"],
"FZtBeR": ["Activer ", ["0"]],
"FeXcUS": [
["display"],
@@ -1822,6 +1825,7 @@
", mais les identifiants de ce compte n'ont pas pu être utilisés."
],
"GBQjiV": ["Ajouter une compétence"],
+ "GCrhIF": ["Panneaux"],
"GDvlUT": ["Rôle"],
"GEyl32": ["Démarrage du terminal…"],
"GGsM4y": ["Sélectionné dans le graphe"],
@@ -2473,7 +2477,6 @@
"Un lien symbolique pointe vers le dossier source au lieu d'être un dossier à part entière. Chaque emplacement lit exactement les mêmes octets, donc rien ne peut diverger, et un emplacement cesse de fonctionner si la source est supprimée."
],
"MTs6g3": ["Impossible de se reconnecter après le redémarrage du serveur"],
- "MU_NVW": ["Réduire Terminal"],
"MUrVEo": ["Aucun projet récent."],
"MV-Dkb": [["countDisplay"], " fichiers markdown trouvés"],
"MVxpbf": ["Rechercher et remplacer"],
@@ -3340,13 +3343,13 @@
"</0> en local, mais il a été modifié en amont."
],
"V4JHny": ["Le partage ne prend en charge que les dépôts distants GitHub."],
- "V6AIOn": ["Navigation dans l'espace de travail"],
"V6e25h": ["Aperçu du thème"],
"V7QxyT": ["Connexion interrompue"],
"VAHWL_": ["Connecté en tant que <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"Construisez et gardez la trace du monde qui se cache derrière votre histoire. Un espace pour vos personnages, vos lieux, vos factions et la mythologie qui les relie, afin que les détails restent cohérents pendant que vous écrivez."
],
+ "VBtCdv": ["Impossible de faire défiler jusqu’à ce passage. Réessayez."],
"VFQXPl": [
"Les aperçus de liens externes affichent une carte avec le nom du site, le titre de la page et sa description au survol d'un lien."
],
@@ -3531,7 +3534,6 @@
"X2zUS5": ["Supprimer ce commentaire"],
"X3MMeA": ["Aucun de ces problèmes n'a de correction automatique."],
"X59Fx2": ["Impossible d'ouvrir ce document dans Slidev."],
- "X7ShnN": ["Ouvrir le panneau des agents"],
"X8kjQX": ["Se réauthentifier auprès de GitHub"],
"X9VpsP": ["Chargement du contenu du dossier"],
"XA9uvc": ["OpenKnowledge recherche et télécharge les mises à jour en arrière-plan."],
@@ -3697,6 +3699,7 @@
"YS9mSt": ["« ", ["name"], " » mis à jour depuis ", ["0"]],
"YSFv5w": ["Aucun dépôt git — le partage de configuration ne s'applique pas ici."],
"YScUUO": ["Récupère une page web"],
+ "YStFYH": ["Ouvrir les agents"],
"YTLmTM": ["Supprimer le dossier <0>.git</0> parent"],
"YW7Q86": [
"Les paramètres de recherche ne sont pas encore chargés — réessayez dans un instant"
@@ -3997,6 +4000,7 @@
"Aucun outil IA détecté pour l'instant. Une fois que vous en installez un, connectez-le depuis Paramètres > Ce projet."
],
"aTDVi6": ["Votre contenu a été conservé"],
+ "aV2vel": ["Volet ", ["number"]],
"aWlJai": ["Démarrage du processus de connexion"],
"aXkLuE": ["Réponse d'application mal formée"],
"a_u4ck": ["Chargement des étiquettes"],
@@ -4583,6 +4587,7 @@
"f1-q9m": ["conserve les compétences"],
"f14doC": ["Slidev"],
"f1XQyZ": ["Déplacer le bloc"],
+ "f3YhVJ": ["Rien d’ouvert"],
"f65AOQ": ["Partir de"],
"f6suyZ": ["Modifications demandées"],
"f8fH8W": ["Conception"],
@@ -4602,6 +4607,7 @@
"fKsRVO": ["Compétences de ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["Impossible d'enregistrer le réglage de mise à jour automatique : ", ["0"]],
"fNr-MX": ["Désactiver la recherche sémantique"],
+ "fObclJ": ["Retour à l'éditeur"],
"fOzzSV": ["La cible du lien « ", ["shown"], " » ne correspond à aucun fichier existant."],
"fRVBiq": [
"Ajoute la télémétrie, l'état du serveur et les informations d'exécution lorsqu'elles sont disponibles. Les identifiants sont toujours supprimés ; les noms de documents, s'ils sont inclus, apparaissent en clair (non masqués)."
@@ -4707,7 +4713,6 @@
["descriptorLabel"],
"> a échoué (probablement une propriété incorrecte). Copiez la source pour voir ce qui ne va pas, ou supprimez le bloc."
],
- "g5V4_P": ["Réduire le panneau des agents"],
"g5w1sF": [
"Choisissez un dossier à fusionner DANS ",
["display"],
@@ -4971,18 +4976,6 @@
"i04BJx": ["Vit hors de ce projet — lecture seule ici."],
"i09An-": ["Version antérieure restaurée (", ["0"], ")"],
"i1flq_": ["Suggestions de liens wiki"],
- "i25FHa": [
- "Ouvrir le panneau des agents — ",
- [
- "liveThreadCount",
- "plural",
- {
- "one": ["#", " fil d'agent actif"],
- "many": ["#", " fils d'agents actifs"],
- "other": ["#", " fils d'agents actifs"]
- }
- ]
- ],
"i3f2kh": ["Aucune commande correspondante."],
"i6o7XB": ["Rechercher des langues"],
"i92eAT": [
@@ -5581,6 +5574,7 @@
],
"n7aopT": ["Mode de l'éditeur"],
"n81AV0": [["owner"], "/", ["name"], " existe déjà. Choisissez un autre nom."],
+ "nBFK5w": ["Redimensionner le terminal"],
"nBHvPL": ["Annuler la modification"],
"nBgzKO": ["En faire la source — le vrai dossier de la compétence est déplacé ici"],
"nCzR-G": ["Copier le code ", ["userCode"]],
@@ -6005,6 +5999,7 @@
"r-OJYm": [
"Saisissez un nom de branche valide (pas d'espaces, pas de point initial, pas de « .. »)."
],
+ "r-wzd8": ["Mises à jour et avis"],
"r2eKE3": ["Connectez-vous d'abord à ", ["agentName"]],
"r3iaI0": ["Aucune discussion pour le moment."],
"r4R7AZ": ["Erreur réseau pendant le nettoyage"],
@@ -6280,6 +6275,7 @@
"ten9en": ["Projet récent"],
"tfDRzk": ["Enregistrer"],
"tfi40B": ["Échec de la création de la page"],
+ "tgB_VT": ["Ouvrir l’éditeur"],
"tgWuMB": ["Modifié"],
"thnPBX": ["Active l'onglet suivant de l'éditeur."],
"ti6aF_": ["Demander à la CLI ", ["0"]],
@@ -6480,6 +6476,7 @@
"un-K1H": ["Reste sur cet ordinateur. Non validé dans git."],
"un8kBM": ["Création de la page : ", ["linkTitle"], "."],
"uoJF_D": ["C'était trop compliqué à installer ou à prendre en main"],
+ "uqgCZJ": ["Masquer l’éditeur"],
"uqs8Gd": [
[
"others",
@@ -6842,6 +6839,7 @@
"xzAmL_": ["Approuvé automatiquement"],
"xzktOa": ["Modifier le lien wiki"],
"y-LQPF": ["Image ", ["identity"], " impossible à résoudre. Accéder à la référence."],
+ "y0_w13": ["Afficher l’éditeur"],
"y1eoq1": ["Copier le lien"],
"y1t8bQ": ["Sections des paramètres"],
"y3aU20": ["Enregistrer les modifications"],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 340ccbe77..4f2303160 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -1674,6 +1674,7 @@ msgstr "Actif"
msgid "Active panel content for the selected tab shows here."
msgstr "Le contenu du panneau actif de l'onglet sélectionné s'affiche ici."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "Activité"
@@ -1965,6 +1966,10 @@ msgstr "Connexions des agents"
msgid "Agent mode"
msgstr "Mode agent"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "Panneau des agents"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Le panneau des agents a été fermé pour que Terminal reste lisible."
@@ -1987,6 +1992,7 @@ msgstr "Transcription de l'agent"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "Agents"
@@ -2183,6 +2189,7 @@ msgstr "Instance de l’application : {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "Journal en ajout seul de ce qui a changé."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "Application"
@@ -2547,6 +2554,10 @@ msgstr "Retour"
msgid "Back to document view"
msgstr "Retour à la vue document"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "Retour à l'éditeur"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "Rétroliens"
@@ -3467,10 +3478,6 @@ msgstr "Réduire"
msgid "Collapse {keyName}"
msgstr "Réduire {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "Réduire le panneau des agents"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "Réduire Demander à l'IA"
msgid "Collapse graph"
msgstr "Réduire le graphe"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Réduire Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "Bloc de contenu repliable (bascule de type Notion)."
@@ -3665,7 +3668,7 @@ msgstr "Configurez les paramètres utilisateur, projet et intégrations."
msgid "conflict"
msgstr "conflit"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Conflit"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "Impossible de dupliquer « {0} » : {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "Impossible de trouver ce passage — le texte auquel il était rattaché a peut-être changé."
@@ -4669,6 +4673,10 @@ msgstr "Impossible d'enregistrer ce paramètre. Réessayez."
msgid "Couldn't save your theme preference."
msgstr "Impossible d'enregistrer votre préférence de thème."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "Impossible de faire défiler jusqu’à ce passage. Réessayez."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "Impossible d'envoyer le rapport"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "Mode de rendu des différences"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Différences indisponibles"
@@ -5410,6 +5419,10 @@ msgstr "Document introuvable"
msgid "Document outline"
msgstr "Plan du document"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "Panneau du document"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "Panneaux du document"
@@ -5733,6 +5746,7 @@ msgstr "Modification de {boldName} sur place. Les changements sont enregistrés
msgid "Editing broken MDX source: {reason}"
msgstr "Modification d'une source MDX cassée : {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "Éditeur"
@@ -5745,6 +5759,10 @@ msgstr "Mode de l'éditeur"
msgid "editor pane"
msgstr "volet de l’éditeur"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "Volet de l'éditeur"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Sélection de l'éditeur"
@@ -6691,6 +6709,7 @@ msgstr "Fichier : <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "Nom de fichier"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "Fichiers"
@@ -7353,11 +7372,17 @@ msgstr "Masquer les détails"
msgid "Hide document panel"
msgstr "Masquer le panneau du document"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "Masquer l’éditeur"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "Masquer les nœuds d'URL externes"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Masquer les fichiers"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "Masquer les autres"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "Masquer le panneau"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "Masquer le panneau ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "Modifiez la cible du lien, l'ancre et le libellé affiché."
msgid "More"
msgstr "Plus"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "Plus d'actions"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "Plus d'actions ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "Rien ne bouge tant que vous ne le demandez pas — tirez et poussez depu
msgid "Nothing moves until you ask."
msgstr "Rien ne bouge tant que vous ne le demandez pas."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "Rien d’ouvert"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Rien de défini pour l'instant."
@@ -10111,7 +10141,7 @@ msgstr "Désactivé — les liens externes n'affichent que leur URL. Aucune requ
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Désactivé — la recherche classe uniquement par mots-clés. Aucun contenu ne quitte cet ordinateur."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "Hors ligne"
@@ -10277,13 +10307,9 @@ msgstr "Ouvrir le panneau d'activité de {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "Ouvrir le panneau d'activité de {tooltipName}, qui modifie {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "Ouvrir le panneau des agents"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "Ouvrir le panneau des agents — {liveThreadCount, plural, one {# fil d'agent actif} many {# fils d'agents actifs} other {# fils d'agents actifs}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "Ouvrir les agents"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "Ouvre la confirmation de suppression pour les éléments sélectionnés
msgid "Open documents tagged #{chip}"
msgstr "Ouvrir les documents étiquetés #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "Ouvrir l’éditeur"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "Ouvrir le brouillon d'e-mail"
@@ -10501,7 +10531,7 @@ msgstr "Ouvrir le panneau de vérification de la source"
msgid "Open source: {mirrorSrc}"
msgstr "Source : {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "Ouvrir le terminal"
@@ -11062,6 +11092,14 @@ msgstr "Faire défiler vers le haut"
msgid "pane {0}"
msgstr "volet {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "Volet {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "Panneaux"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Paragraphe"
@@ -11470,6 +11508,7 @@ msgstr "projet"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Projet"
@@ -11863,7 +11902,7 @@ msgstr "Recommandé"
msgid "Recommended agent skill"
msgstr "Compétence d'agent recommandée"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "Reconnexion nécessaire"
@@ -12452,10 +12491,19 @@ msgstr "Réinitialiser les filtres d'affichage"
msgid "Resize {handleKey}"
msgstr "Redimensionner {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "Redimensionner le panneau du document"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "Redimensionner le panneau Compétences"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "Redimensionner le terminal"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Résoudre le conflit dans votre terminal"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "Défiler jusqu'au début"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "Rechercher"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "Rechercher « {semanticSubmitQuery} » par le sens"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "Rechercher ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "Rechercher des agents"
@@ -13549,6 +13592,11 @@ msgstr "Afficher le diagramme"
msgid "Show document panel"
msgstr "Afficher le panneau du document"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "Afficher l’éditeur"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "Afficher les nœuds d'URL externes"
@@ -13557,7 +13605,7 @@ msgstr "Afficher les nœuds d'URL externes"
msgid "Show fewer"
msgstr "Afficher moins"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Afficher les fichiers"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "Afficher l’original"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "Afficher le panneau"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "Afficher le panneau ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "Mode de synchronisation"
msgid "Sync now"
msgstr "Synchroniser maintenant"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "Synchronisation en pause"
@@ -14616,6 +14664,7 @@ msgstr "Modèles disponibles"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "propriétés du dossier mises à jour"
msgid "Updated to Version {version}"
msgstr "Mis à jour vers la version {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "Mises à jour et avis"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "Les mises à jour arrivent"
@@ -16989,10 +17042,6 @@ msgstr "Espace de travail"
msgid "Workspace Command Palette"
msgstr "Palette de commandes de l'espace de travail"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "Navigation dans l'espace de travail"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 76a3b642c..b5317b01e 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -336,6 +336,7 @@
"3Fcb0I": ["ग्राफ़ खोलें"],
"3HAPpl": ["आपकी खोज से कोई स्कीमा मेल नहीं खाती।"],
"3HNlwb": ["नमस्ते, दुनिया!"],
+ "3HOAcR": ["एजेंट पैनल"],
"3Ib6FN": ["नीचे ले जाएँ"],
"3J7d2N": ["बड़ा अनुभाग शीर्षक।"],
"3JYy1p": ["ब्रांच ", ["0"], " अब मौजूद नहीं है। डिफ़ॉल्ट ब्रांच पर क्लोन किया गया।"],
@@ -518,6 +519,7 @@
],
"5OTgC7": ["नीचे वाली Ask AI प्रॉम्प्ट लेखन-पट्टी खोलें और उस पर फ़ोकस करें।"],
"5OqaJi": ["एक प्रोजेक्ट नाम डालें"],
+ "5Q9-G-": ["दस्तावेज़ पैनल"],
"5QGTaA": ["सापेक्ष पथ कॉपी नहीं किया जा सका"],
"5RiC8D": [
"डिस्कवरी स्किल सभी AI टूल के लिए एक साथ प्रबंधित किए जाते हैं। इसे सेटिंग → स्किल स्टूडियो से इंस्टॉल करें।"
@@ -743,6 +745,7 @@
"7cAW1G": ["इस एंडपॉइंट के लिए कोई API कुंजी सेट नहीं है। ऊपर एक जोड़ें।"],
"7czmD1": ["OpenKnowledge ने लेखन पैलेट देखा"],
"7d1a0d": ["सार्वजनिक"],
+ "7dDoQu": ["संपादक फलक"],
"7dZnmw": ["प्रासंगिकता"],
"7hctf2": ["जो प्रोजेक्ट आप बनाना चाहते हैं उसका वर्णन करें"],
"7idx48": ["OKF एजेंट कौशल स्थापित"],
@@ -1235,7 +1238,6 @@
"DWJtEo": ["आगे क्या होता है"],
"DXd9LM": ["नया वर्कट्री"],
"D_WKe_": ["किसी एजेंट का सत्र देखने के लिए उपस्थिति पट्टी में उसके अवतार पर क्लिक करें।"],
- "DbCfXV": ["खोजें (", ["searchShortcutLabel"], ")"],
"DbILZA": ["कोई मेल नहीं। कुछ फ़ाइलें खोज से बाहर रखी गई हैं (छिपी या अनदेखी की गई फ़ाइलें)।"],
"DcFr-y": ["OpenKnowledge ने एक दस्तावेज़ हटाया"],
"DcH8-w": [["0"], " स्किलें प्रोजेक्ट में ले जाएँ"],
@@ -1444,6 +1446,7 @@
") से मेल नहीं खाता।"
],
"FWSjnp": ["स्रोत पैनल और कोड प्रॉपर्टी फ़ील्ड संपादित करें"],
+ "FYy2EN": ["दस्तावेज़ पैनल का आकार बदलें"],
"FZtBeR": [["0"], " सक्षम करें"],
"FeXcUS": [
["display"],
@@ -1496,6 +1499,7 @@
" नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
],
"GBQjiV": ["स्किल जोड़ें"],
+ "GCrhIF": ["पैनल"],
"GDvlUT": ["भूमिका"],
"GEyl32": ["टर्मिनल शुरू हो रहा है…"],
"GGsM4y": ["ग्राफ़ में चयनित"],
@@ -2024,7 +2028,6 @@
"सिमलिंक अपने आप में एक फ़ोल्डर होने के बजाय स्रोत फ़ोल्डर की ओर एक संकेतक है। हर स्थान बिल्कुल वही बाइट पढ़ता है, इसलिए कुछ भी अलग नहीं हो सकता, और स्रोत हटने पर वह स्थान काम करना बंद कर देता है।"
],
"MTs6g3": ["सर्वर पुनः आरंभ होने के बाद फिर से नहीं जुड़ा जा सका"],
- "MU_NVW": ["Terminal संक्षिप्त करें"],
"MUrVEo": ["कोई हाल का प्रोजेक्ट नहीं।"],
"MV-Dkb": [["countDisplay"], " markdown फ़ाइलें मिलीं"],
"MVxpbf": ["खोजें और बदलें"],
@@ -2772,13 +2775,13 @@
],
"V48OUT": ["आपने <0>", ["filePath"], "</0> स्थानीय रूप से हटाई, पर उसे अपस्ट्रीम में बदला गया था।"],
"V4JHny": ["साझाकरण केवल GitHub रिमोट के साथ काम करता है।"],
- "V6AIOn": ["कार्यक्षेत्र नेविगेशन"],
"V6e25h": ["थीम पूर्वावलोकन"],
"V7QxyT": ["कनेक्शन टूट गया"],
"VAHWL_": ["<0>@", ["signedInLogin"], "</0> के रूप में जुड़े"],
"VBE2dw": [
"अपनी कहानी के पीछे की दुनिया बनाएँ और उस पर नज़र रखें। आपके पात्रों, स्थानों, गुटों और उन्हें जोड़ने वाली दंतकथाओं का एक घर, ताकि लिखते समय ब्यौरे एक जैसे बने रहें।"
],
+ "VBtCdv": ["उस अंश तक स्क्रॉल नहीं किया जा सका। फिर से कोशिश करें।"],
"VFQXPl": [
"जब आप किसी लिंक पर माउस ले जाते हैं तो बाहरी लिंक पूर्वावलोकन साइट का नाम, पेज शीर्षक और विवरण वाला एक कार्ड दिखाता है।"
],
@@ -2915,7 +2918,6 @@
"X2zUS5": ["यह टिप्पणी हटाएँ"],
"X3MMeA": ["इनमें से किसी भी समस्या का कोई स्वचालित समाधान नहीं है।"],
"X59Fx2": ["इस दस्तावेज़ को Slidev में नहीं खोला जा सका।"],
- "X7ShnN": ["एजेंट पैनल खोलें"],
"X8kjQX": ["GitHub के साथ फिर से प्रमाणित करें"],
"X9VpsP": ["फ़ोल्डर की सामग्री लोड हो रही है"],
"XA9uvc": ["OpenKnowledge पृष्ठभूमि में अपडेट देखता और डाउनलोड करता है।"],
@@ -3060,6 +3062,7 @@
"YS9mSt": ["\"", ["name"], "\" को ", ["0"], " से अपडेट किया गया"],
"YSFv5w": ["कोई git रिपॉज़िटरी नहीं — कॉन्फ़िग साझाकरण यहाँ लागू नहीं होता।"],
"YScUUO": ["एक वेब पेज लाता है"],
+ "YStFYH": ["एजेंट खोलें"],
"YTLmTM": ["मूल <0>.git</0> फ़ोल्डर हटाएँ"],
"YW7Q86": ["खोज सेटिंग अभी लोड नहीं हुई — कुछ देर बाद फिर कोशिश करें"],
"YWK2zy": [["fileName"], " के लिए कॉन्फ़्लिक्ट डिफ़"],
@@ -3326,6 +3329,7 @@
"aS77on": ["क्या बदलता है?"],
"aSVmqV": ["अभी तक कोई AI टूल नहीं मिला। एक इंस्टॉल करने के बाद उसे Settings > This project से जोड़ें।"],
"aTDVi6": ["आपका कॉन्टेंट सुरक्षित रखा गया"],
+ "aV2vel": ["फलक ", ["number"]],
"aWlJai": ["साइन-इन प्रक्रिया शुरू की जा रही है"],
"aXkLuE": ["अप्लाई प्रतिक्रिया का प्रारूप गलत है"],
"a_u4ck": ["टैग लोड हो रहे हैं"],
@@ -3784,6 +3788,7 @@
"f1-q9m": ["स्किल अपने पास रखता है"],
"f14doC": ["Slidev"],
"f1XQyZ": ["ब्लॉक हिलाएँ"],
+ "f3YhVJ": ["कुछ भी खुला नहीं है"],
"f65AOQ": ["यहाँ से शुरू करें"],
"f6suyZ": ["बदलाव माँगे गए"],
"f8fH8W": ["डिज़ाइन"],
@@ -3801,6 +3806,7 @@
"fKsRVO": [["0"], "/", ["1"], " से स्किलें।"],
"fMsFdZ": ["स्वत: अपडेट सेटिंग नहीं सहेजी जा सकी: ", ["0"]],
"fNr-MX": ["अर्थ-आधारित खोज अक्षम करें"],
+ "fObclJ": ["संपादक पर वापस"],
"fOzzSV": ["लिंक लक्ष्य \"", ["shown"], "\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"],
"fRVBiq": [
"उपलब्ध होने पर टेलीमेट्री, सर्वर स्थिति और रनटाइम जानकारी जोड़ता है। क्रेडेंशियल हमेशा हटा दिए जाते हैं; दस्तावेज़ों के नाम, यदि शामिल हों, सादे पाठ में दिखते हैं (हटाए नहीं जाते)।"
@@ -3875,7 +3881,6 @@
["descriptorLabel"],
"> रेंडर नहीं हो सका (शायद कोई ग़लत प्रॉप)। क्या ग़लत हुआ यह देखने के लिए स्रोत कॉपी करें, या ब्लॉक हटा दें।"
],
- "g5V4_P": ["एजेंट पैनल संक्षिप्त करें"],
"g5w1sF": [
"वह फ़ोल्डर चुनें जिसे ",
["display"],
@@ -4103,14 +4108,6 @@
"i04BJx": ["इस प्रोजेक्ट के बाहर है — यहाँ केवल पढ़ने योग्य।"],
"i09An-": ["एक पुराना संस्करण बहाल किया गया (", ["0"], ")"],
"i1flq_": ["विकी लिंक सुझाव"],
- "i25FHa": [
- "एजेंट पैनल खोलें — ",
- [
- "liveThreadCount",
- "plural",
- { "one": ["#", " सक्रिय एजेंट थ्रेड"], "other": ["#", " सक्रिय एजेंट थ्रेड"] }
- ]
- ],
"i3f2kh": ["कोई मेल खाता कमांड नहीं।"],
"i6o7XB": ["भाषाएँ खोजें"],
"i92eAT": ["हम एक रिपॉज़िटरी बनाकर सिंक शुरू कर देंगे — किसी टर्मिनल की ज़रूरत नहीं।"],
@@ -4625,6 +4622,7 @@
],
"n7aopT": ["संपादक मोड"],
"n81AV0": [["owner"], "/", ["name"], " पहले से मौजूद है। कोई दूसरा नाम चुनें।"],
+ "nBFK5w": ["टर्मिनल का आकार बदलें"],
"nBHvPL": ["संपादन रद्द करें"],
"nBgzKO": ["इसे स्रोत बनाएँ — स्किल का असली फ़ोल्डर यहाँ आ जाता है"],
"nCzR-G": ["कोड ", ["userCode"], " कॉपी करें"],
@@ -4958,6 +4956,7 @@
"qyLmWw": ["स्रोत संपादक का खोज पैनल"],
"qze9od": ["यह फ़ोल्डर ", ["alsoAffects"], " का भी है।"],
"r-OJYm": ["एक मान्य ब्रांच नाम डालें (कोई रिक्त स्थान नहीं, शुरू में बिंदु नहीं, \"..\" नहीं)।"],
+ "r-wzd8": ["अपडेट और प्रतिक्रिया"],
"r2eKE3": ["पहले ", ["agentName"], " में साइन इन करें"],
"r3iaI0": ["अभी तक कोई चैट नहीं है।"],
"r4R7AZ": ["सफ़ाई के दौरान नेटवर्क त्रुटि"],
@@ -5191,6 +5190,7 @@
"ten9en": ["हाल का प्रोजेक्ट"],
"tfDRzk": ["सहेजें"],
"tfi40B": ["पेज बनाने में विफल"],
+ "tgB_VT": ["संपादक खोलें"],
"tgWuMB": ["संशोधित"],
"thnPBX": ["अगला संपादक टैब सक्रिय करें।"],
"ti6aF_": [["0"], " CLI से पूछें"],
@@ -5366,6 +5366,7 @@
"un-K1H": ["इसी कंप्यूटर पर रहता है। git में कमिट नहीं होता।"],
"un8kBM": ["पेज बनाया जा रहा है: ", ["linkTitle"], "."],
"uoJF_D": ["इसे सेट अप करना या शुरू करना बहुत कठिन था"],
+ "uqgCZJ": ["संपादक छिपाएँ"],
"uqs8Gd": [["others", "plural", { "one": ["#", " अन्य"], "other": ["#", " अन्य"] }]],
"ur2XSb": ["दृश्य संपादक"],
"uraHF0": ["GitLab"],
@@ -5662,6 +5663,7 @@
"xzAmL_": ["स्वत: स्वीकृत"],
"xzktOa": ["विकी लिंक संपादित करें"],
"y-LQPF": ["हल न की जा सकने वाला चित्र ", ["identity"], "। संदर्भ पर जाएँ।"],
+ "y0_w13": ["संपादक दिखाएँ"],
"y1eoq1": ["लिंक कॉपी करें"],
"y1t8bQ": ["सेटिंग अनुभाग"],
"y3aU20": ["बदलाव सहेजें"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index dc2669039..c65b4fda7 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -1670,6 +1670,7 @@ msgstr "सक्रिय"
msgid "Active panel content for the selected tab shows here."
msgstr "चयनित टैब की सक्रिय पैनल सामग्री यहाँ दिखती है।"
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "गतिविधि"
@@ -1961,6 +1962,10 @@ msgstr "एजेंट कनेक्शन"
msgid "Agent mode"
msgstr "एजेंट मोड"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "एजेंट पैनल"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Terminal को पढ़ने योग्य बनाए रखने के लिए एजेंट पैनल बंद कर दिया गया।"
@@ -1983,6 +1988,7 @@ msgstr "एजेंट प्रतिलेख"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "एजेंट"
@@ -2179,6 +2185,7 @@ msgstr "ऐप इंस्टेंस: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "क्या बदला इसका केवल-जोड़ा-जाने वाला लॉग।"
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "एप्लिकेशन"
@@ -2543,6 +2550,10 @@ msgstr "वापस"
msgid "Back to document view"
msgstr "दस्तावेज़ दृश्य पर वापस"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "संपादक पर वापस"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "बैकलिंक"
@@ -3463,10 +3474,6 @@ msgstr "समेटें"
msgid "Collapse {keyName}"
msgstr "{keyName} समेटें"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "एजेंट पैनल संक्षिप्त करें"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3490,10 +3497,6 @@ msgstr "Ask AI समेटें"
msgid "Collapse graph"
msgstr "ग्राफ़ समेटें"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Terminal संक्षिप्त करें"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "संक्षिप्त किया जा सकने वाला सामग्री ब्लॉक (Notion-शैली टॉगल)।"
@@ -3661,7 +3664,7 @@ msgstr "उपयोगकर्ता, प्रोजेक्ट और ए
msgid "conflict"
msgstr "टकराव"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "टकराव"
@@ -4300,6 +4303,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "\"{0}\" की नकल नहीं बनाई जा सकी: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "वह अंश नहीं मिल सका — जिस पाठ पर वह था वह बदल गया हो सकता है।"
@@ -4665,6 +4669,10 @@ msgstr "यह सेटिंग सहेजी नहीं जा सकी
msgid "Couldn't save your theme preference."
msgstr "आपकी थीम प्राथमिकता सहेजी नहीं जा सकी।"
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "उस अंश तक स्क्रॉल नहीं किया जा सका। फिर से कोशिश करें।"
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "रिपोर्ट नहीं भेजी जा सकी"
@@ -5285,6 +5293,7 @@ msgid "Diff render mode"
msgstr "अंतर रेंडर मोड"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "अंतर अनुपलब्ध"
@@ -5406,6 +5415,10 @@ msgstr "दस्तावेज़ नहीं मिला"
msgid "Document outline"
msgstr "दस्तावेज़ रूपरेखा"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "दस्तावेज़ पैनल"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "दस्तावेज़ पैनल"
@@ -5729,6 +5742,7 @@ msgstr "{boldName} को उसी जगह संपादित किया
msgid "Editing broken MDX source: {reason}"
msgstr "टूटा हुआ MDX स्रोत संपादित किया जा रहा है: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "संपादक"
@@ -5741,6 +5755,10 @@ msgstr "संपादक मोड"
msgid "editor pane"
msgstr "संपादक फलक"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "संपादक फलक"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "संपादक चयन"
@@ -6687,6 +6705,7 @@ msgstr "फ़ाइल: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "फ़ाइल का नाम"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "फ़ाइलें"
@@ -7349,11 +7368,17 @@ msgstr "विवरण छिपाएँ"
msgid "Hide document panel"
msgstr "दस्तावेज़ पैनल छिपाएँ"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "संपादक छिपाएँ"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "बाहरी URL नोड छिपाएँ"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Files छिपाएँ"
@@ -7384,12 +7409,13 @@ msgid "Hide Others"
msgstr "अन्य छिपाएँ"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "पैनल छिपाएँ"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "पैनल छिपाएँ ({panelShortcutLabel})"
@@ -9004,11 +9030,11 @@ msgstr "लिंक लक्ष्य, एंकर और प्रदर्
msgid "More"
msgstr "और"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "और क्रियाएँ"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "और क्रियाएँ ({syncAttentionLabel})"
@@ -10058,6 +10084,10 @@ msgstr "जब तक आप न कहें, कुछ नहीं चले
msgid "Nothing moves until you ask."
msgstr "जब तक आप न कहें, कुछ नहीं चलेगा।"
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "कुछ भी खुला नहीं है"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "अभी कुछ भी सेट नहीं।"
@@ -10107,7 +10137,7 @@ msgstr "बंद — बाहरी लिंक केवल अपना URL
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "बंद — खोज केवल कीवर्ड से क्रम तय करती है। कोई सामग्री इस कंप्यूटर से बाहर नहीं जाती।"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "ऑफ़लाइन"
@@ -10273,13 +10303,9 @@ msgstr "{tooltipName} के लिए गतिविधि पैनल खो
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "{tooltipName} के लिए गतिविधि पैनल खोलें, {realCurrentDoc} संपादित किया जा रहा है"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "एजेंट पैनल खोलें"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "एजेंट पैनल खोलें — {liveThreadCount, plural, one {# सक्रिय एजेंट थ्रेड} other {# सक्रिय एजेंट थ्रेड}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "एजेंट खोलें"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10326,6 +10352,10 @@ msgstr "चयनित फ़ाइल-ट्री आइटम के लि
msgid "Open documents tagged #{chip}"
msgstr "#{chip} टैग वाले दस्तावेज़ खोलें"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "संपादक खोलें"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "ईमेल मसौदा खोलें"
@@ -10497,7 +10527,7 @@ msgstr "स्रोत lint पैनल खोलें"
msgid "Open source: {mirrorSrc}"
msgstr "स्रोत खोलें: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "टर्मिनल खोलें"
@@ -11058,6 +11088,14 @@ msgstr "ऊपर खिसकाएँ"
msgid "pane {0}"
msgstr "फलक {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "फलक {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "पैनल"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "पैराग्राफ़"
@@ -11466,6 +11504,7 @@ msgstr "प्रोजेक्ट"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "प्रोजेक्ट"
@@ -11859,7 +11898,7 @@ msgstr "अनुशंसित"
msgid "Recommended agent skill"
msgstr "अनुशंसित एजेंट कौशल"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "फिर से जुड़ना ज़रूरी"
@@ -12448,10 +12487,19 @@ msgstr "दृश्य फ़िल्टर रीसेट करें"
msgid "Resize {handleKey}"
msgstr "{handleKey} का आकार बदलें"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "दस्तावेज़ पैनल का आकार बदलें"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "स्किल पैनल का आकार बदलें"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "टर्मिनल का आकार बदलें"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "अपने टर्मिनल में टकराव सुलझाएँ"
@@ -12864,9 +12912,8 @@ msgid "Scroll to start"
msgstr "शुरुआत तक स्क्रॉल करें"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12876,10 +12923,6 @@ msgstr "खोजें"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "अर्थ के आधार पर \"{semanticSubmitQuery}\" खोजें"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "खोजें ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "एजेंट खोजें"
@@ -13545,6 +13588,11 @@ msgstr "आरेख दिखाएँ"
msgid "Show document panel"
msgstr "दस्तावेज़ पैनल दिखाएँ"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "संपादक दिखाएँ"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "बाहरी URL नोड दिखाएँ"
@@ -13553,7 +13601,7 @@ msgstr "बाहरी URL नोड दिखाएँ"
msgid "Show fewer"
msgstr "कम दिखाएँ"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Files दिखाएँ"
@@ -13610,12 +13658,12 @@ msgid "Show original"
msgstr "मूल दिखाएँ"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "पैनल दिखाएँ"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "पैनल दिखाएँ ({panelShortcutLabel})"
@@ -14434,7 +14482,7 @@ msgstr "सिंक मोड"
msgid "Sync now"
msgstr "अभी सिंक करें"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "सिंक रुका हुआ"
@@ -14612,6 +14660,7 @@ msgstr "उपलब्ध टेम्पलेट"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16412,6 +16461,10 @@ msgstr "फ़ोल्डर प्रॉपर्टी अपडेट की
msgid "Updated to Version {version}"
msgstr "संस्करण {version} पर अपडेट किया गया"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "अपडेट और प्रतिक्रिया"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "अपडेट आते रहते हैं"
@@ -16985,10 +17038,6 @@ msgstr "कार्यक्षेत्र"
msgid "Workspace Command Palette"
msgstr "कार्यक्षेत्र कमांड पैलेट"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "कार्यक्षेत्र नेविगेशन"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index b1cd52b81..cf1883149 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -345,6 +345,7 @@
"3Fcb0I": ["Buka graf"],
"3HAPpl": ["Tidak ada skema yang cocok dengan pencarian Anda."],
"3HNlwb": ["Halo, dunia!"],
+ "3HOAcR": ["Panel agen"],
"3Ib6FN": ["Turunkan"],
"3J7d2N": ["Judul bagian besar."],
"3JYy1p": ["Cabang ", ["0"], " sudah tidak ada. Dikloning ke cabang bawaan."],
@@ -543,6 +544,7 @@
],
"5OTgC7": ["Membuka dan memfokuskan penyusun prompt Tanya AI di bawah."],
"5OqaJi": ["Masukkan nama proyek"],
+ "5Q9-G-": ["Panel dokumen"],
"5QGTaA": ["Jalur relatif tidak dapat disalin"],
"5RiC8D": [
"Skill penemuan dikelola bersama untuk semua alat AI. Instal skill ini dari Pengaturan → Studio Keterampilan."
@@ -769,6 +771,7 @@
"7cAW1G": ["Tidak ada kunci API yang disetel untuk endpoint ini. Tambahkan satu di atas."],
"7czmD1": ["OpenKnowledge membuka palet penulisan"],
"7d1a0d": ["Publik"],
+ "7dDoQu": ["Panel penyunting"],
"7dZnmw": ["Relevansi"],
"7hctf2": ["Jelaskan proyek yang ingin Anda buat"],
"7idx48": ["OKF keterampilan agen diinstal"],
@@ -1263,7 +1266,6 @@
"DWJtEo": ["Apa yang terjadi selanjutnya"],
"DXd9LM": ["Worktree baru"],
"D_WKe_": ["Klik avatar seorang agen di bilah kehadiran untuk melihat sesinya."],
- "DbCfXV": ["Cari (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"Tidak ada kecocokan. Sebagian berkas dikecualikan dari pencarian (berkas tersembunyi atau yang diabaikan)."
],
@@ -1485,6 +1487,7 @@
")."
],
"FWSjnp": ["Panel sunting sumber dan bidang properti berbentuk kode"],
+ "FYy2EN": ["Ubah ukuran panel dokumen"],
"FZtBeR": ["Aktifkan ", ["0"]],
"FeXcUS": [
["display"],
@@ -1550,6 +1553,7 @@
", tetapi kredensial akun itu tidak dapat digunakan."
],
"GBQjiV": ["Tambahkan keterampilan"],
+ "GCrhIF": ["Panel"],
"GDvlUT": ["Peran"],
"GEyl32": ["Memulai terminal…"],
"GGsM4y": ["Terpilih di graf"],
@@ -2098,7 +2102,6 @@
"Symlink adalah penunjuk ke folder sumber, bukan folder tersendiri. Setiap lokasi membaca bita yang persis sama, jadi tidak ada yang bisa melenceng, dan sebuah lokasi berhenti bekerja jika sumbernya dihapus."
],
"MTs6g3": ["Tidak bisa tersambung kembali setelah server dimulai ulang"],
- "MU_NVW": ["Ciutkan Terminal"],
"MUrVEo": ["Tidak ada proyek terbaru."],
"MV-Dkb": ["Ditemukan ", ["countDisplay"], " berkas markdown"],
"MVxpbf": ["Cari dan ganti"],
@@ -2865,13 +2868,13 @@
"</0> secara lokal, tetapi ia diubah di remote."
],
"V4JHny": ["Berbagi hanya mendukung remote GitHub."],
- "V6AIOn": ["Navigasi ruang kerja"],
"V6e25h": ["Pratinjau tema"],
"V7QxyT": ["Koneksi terputus"],
"VAHWL_": ["Terhubung sebagai <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"Bangun dan pantau dunia di balik cerita Anda. Rumah bagi tokoh, tempat, faksi, dan latar cerita yang mengikat semuanya, agar detailnya tetap konsisten selama Anda menulis."
],
+ "VBtCdv": ["Tidak dapat menggulir ke bagian teks itu. Coba lagi."],
"VFQXPl": [
"Pratinjau tautan eksternal menampilkan kartu berisi nama situs, judul halaman, dan deskripsi saat Anda mengarahkan kursor ke sebuah tautan."
],
@@ -3024,7 +3027,6 @@
"X2zUS5": ["Hapus komentar ini"],
"X3MMeA": ["Tidak satu pun masalah ini punya perbaikan otomatis."],
"X59Fx2": ["Tidak dapat membuka dokumen ini di Slidev."],
- "X7ShnN": ["Buka panel agen"],
"X8kjQX": ["Autentikasi ulang dengan GitHub"],
"X9VpsP": ["Memuat isi folder"],
"XA9uvc": ["OpenKnowledge memeriksa dan mengunduh pembaruan di latar belakang."],
@@ -3165,6 +3167,7 @@
"YS9mSt": ["\"", ["name"], "\" diperbarui dari ", ["0"]],
"YSFv5w": ["Tidak ada repositori git — berbagi konfigurasi tidak berlaku di sini."],
"YScUUO": ["Mengambil halaman web"],
+ "YStFYH": ["Buka agen"],
"YTLmTM": ["Hapus folder <0>.git</0> induknya"],
"YW7Q86": ["Pengaturan pencarian belum dimuat — coba lagi sebentar"],
"YWK2zy": ["Diff konflik untuk ", ["fileName"]],
@@ -3437,6 +3440,7 @@
"Belum ada alat AI yang terdeteksi. Setelah Anda memasang satu, hubungkan dari Pengaturan > Proyek ini."
],
"aTDVi6": ["Konten Anda dipertahankan"],
+ "aV2vel": ["Panel ", ["number"]],
"aWlJai": ["Memulai alur masuk"],
"aXkLuE": ["Respons apply salah bentuk"],
"a_u4ck": ["Memuat tag"],
@@ -3905,6 +3909,7 @@
"f1-q9m": ["menyimpan keterampilan"],
"f14doC": ["Slidev"],
"f1XQyZ": ["Pindahkan blok"],
+ "f3YhVJ": ["Tidak ada yang terbuka"],
"f65AOQ": ["Mulai dari"],
"f6suyZ": ["Perubahan diminta"],
"f8fH8W": ["Desain"],
@@ -3924,6 +3929,7 @@
"fKsRVO": ["Keterampilan dari ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["Pengaturan pembaruan otomatis tidak bisa disimpan: ", ["0"]],
"fNr-MX": ["Nonaktifkan pencarian semantik"],
+ "fObclJ": ["Kembali ke penyunting"],
"fOzzSV": ["Target tautan \"", ["shown"], "\" tidak merujuk ke file yang ada."],
"fRVBiq": [
"Menambahkan telemetri, keadaan server, dan info runtime bila tersedia. Kredensial selalu dihapus; nama dokumen, jika disertakan, muncul sebagai teks biasa (tidak disunting)."
@@ -3995,7 +4001,6 @@
["descriptorLabel"],
"> gagal dirender (kemungkinan prop yang salah). Salin sumbernya untuk melihat apa yang salah, atau hapus bloknya."
],
- "g5V4_P": ["Ciutkan panel agen"],
"g5w1sF": [
"Pilih sebuah folder untuk digabungkan KE DALAM ",
["display"],
@@ -4249,10 +4254,6 @@
"i04BJx": ["Berada di luar proyek ini — hanya-baca di sini."],
"i09An-": ["Versi terdahulu dipulihkan (", ["0"], ")"],
"i1flq_": ["Saran tautan wiki"],
- "i25FHa": [
- "Buka panel agen — ",
- ["liveThreadCount", "plural", { "other": ["#", " utas agen aktif"] }]
- ],
"i3f2kh": ["Tidak ada perintah yang cocok."],
"i6o7XB": ["Cari bahasa"],
"i92eAT": [
@@ -4799,6 +4800,7 @@
],
"n7aopT": ["Mode penyunting"],
"n81AV0": [["owner"], "/", ["name"], " sudah ada. Pilih nama lain."],
+ "nBFK5w": ["Ubah ukuran terminal"],
"nBHvPL": ["Batalkan penyuntingan"],
"nBgzKO": ["Jadikan ini sumbernya — folder asli keterampilan ini pindah ke sini"],
"nCzR-G": ["Salin kode ", ["userCode"]],
@@ -5139,6 +5141,7 @@
"qyLmWw": ["Panel pencarian penyunting sumber"],
"qze9od": ["Folder ini juga milik ", ["alsoAffects"], "."],
"r-OJYm": ["Masukkan nama cabang yang valid (tanpa spasi, tanpa titik di awal, tanpa \"..\")."],
+ "r-wzd8": ["Pembaruan dan masukan"],
"r2eKE3": ["Masuk dulu ke ", ["agentName"]],
"r3iaI0": ["Belum ada chat."],
"r4R7AZ": ["Galat jaringan saat pembersihan"],
@@ -5397,6 +5400,7 @@
"ten9en": ["Proyek terbaru"],
"tfDRzk": ["Simpan"],
"tfi40B": ["Gagal membuat halaman"],
+ "tgB_VT": ["Buka penyunting"],
"tgWuMB": ["Diubah"],
"thnPBX": ["Mengaktifkan tab penyunting berikutnya."],
"ti6aF_": ["Tanya CLI ", ["0"]],
@@ -5572,6 +5576,7 @@
"un-K1H": ["Tetap di komputer ini. Tidak di-commit ke git."],
"un8kBM": ["Membuat halaman: ", ["linkTitle"], "."],
"uoJF_D": ["Terlalu sulit disiapkan atau dimulai"],
+ "uqgCZJ": ["Sembunyikan Penyunting"],
"uqs8Gd": [["others", "plural", { "other": ["#", " lainnya"] }]],
"ur2XSb": ["Penyunting visual"],
"uraHF0": ["GitLab"],
@@ -5874,6 +5879,7 @@
"xzAmL_": ["Disetujui otomatis"],
"xzktOa": ["Sunting tautan wiki"],
"y-LQPF": ["Gambar ", ["identity"], " tidak dapat ditentukan. Buka referensi."],
+ "y0_w13": ["Tampilkan Penyunting"],
"y1eoq1": ["Salin tautan"],
"y1t8bQ": ["Bagian pengaturan"],
"y3aU20": ["Simpan perubahan"],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 5b7a9884e..d58a03b17 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -1670,6 +1670,7 @@ msgstr "Aktif"
msgid "Active panel content for the selected tab shows here."
msgstr "Isi panel aktif untuk tab yang dipilih muncul di sini."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "Aktivitas"
@@ -1961,6 +1962,10 @@ msgstr "Koneksi agen"
msgid "Agent mode"
msgstr "Mode agen"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "Panel agen"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Panel agen ditutup agar Terminal tetap mudah dibaca."
@@ -1983,6 +1988,7 @@ msgstr "Transkrip agen"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "Agen"
@@ -2179,6 +2185,7 @@ msgstr "Instans aplikasi: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "Log tambah-saja tentang apa yang berubah."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "Aplikasi"
@@ -2543,6 +2550,10 @@ msgstr "Kembali"
msgid "Back to document view"
msgstr "Kembali ke tampilan dokumen"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "Kembali ke penyunting"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "Tautan balik"
@@ -3463,10 +3474,6 @@ msgstr "Ciutkan"
msgid "Collapse {keyName}"
msgstr "Ciutkan {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "Ciutkan panel agen"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3490,10 +3497,6 @@ msgstr "Ciutkan Tanya AI"
msgid "Collapse graph"
msgstr "Ciutkan graf"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Ciutkan Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "Blok konten yang dapat dilipat (toggle gaya Notion)."
@@ -3661,7 +3664,7 @@ msgstr "Atur pengaturan pengguna, proyek, dan integrasi."
msgid "conflict"
msgstr "konflik"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Konflik"
@@ -4300,6 +4303,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "\"{0}\" tidak bisa digandakan: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "Tidak dapat menemukan bagian teks itu — teks yang ditandainya mungkin telah berubah."
@@ -4665,6 +4669,10 @@ msgstr "Pengaturan ini tidak dapat disimpan. Coba lagi."
msgid "Couldn't save your theme preference."
msgstr "Tidak dapat menyimpan preferensi tema Anda."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "Tidak dapat menggulir ke bagian teks itu. Coba lagi."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "Laporannya tidak bisa dikirim"
@@ -5285,6 +5293,7 @@ msgid "Diff render mode"
msgstr "Mode render perbedaan"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Perbedaan tidak tersedia"
@@ -5406,6 +5415,10 @@ msgstr "Dokumen tidak ditemukan"
msgid "Document outline"
msgstr "Kerangka dokumen"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "Panel dokumen"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "Panel dokumen"
@@ -5729,6 +5742,7 @@ msgstr "Menyunting {boldName} di tempatnya. Perubahan langsung tersimpan ke sali
msgid "Editing broken MDX source: {reason}"
msgstr "Menyunting sumber MDX yang rusak: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "Penyunting"
@@ -5741,6 +5755,10 @@ msgstr "Mode penyunting"
msgid "editor pane"
msgstr "panel editor"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "Panel penyunting"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Pilihan penyunting"
@@ -6687,6 +6705,7 @@ msgstr "Berkas: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "Nama berkas"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "Berkas"
@@ -7349,11 +7368,17 @@ msgstr "Sembunyikan detail"
msgid "Hide document panel"
msgstr "Sembunyikan panel dokumen"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "Sembunyikan Penyunting"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "Sembunyikan simpul URL eksternal"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Sembunyikan Berkas"
@@ -7384,12 +7409,13 @@ msgid "Hide Others"
msgstr "Sembunyikan lainnya"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "Sembunyikan panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "Sembunyikan panel ({panelShortcutLabel})"
@@ -9004,11 +9030,11 @@ msgstr "Ubah tujuan tautan, jangkar, dan label tampilannya."
msgid "More"
msgstr "Lainnya"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "Tindakan lainnya"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "Tindakan lainnya ({syncAttentionLabel})"
@@ -10058,6 +10084,10 @@ msgstr "Tidak ada yang berjalan sampai Anda meminta — pull dan push dari menu
msgid "Nothing moves until you ask."
msgstr "Tidak ada yang berjalan sampai Anda meminta."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "Tidak ada yang terbuka"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Belum ada yang disetel."
@@ -10107,7 +10137,7 @@ msgstr "Mati — tautan eksternal hanya menampilkan URL-nya. Tidak ada permintaa
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Mati — pencarian hanya memeringkat berdasarkan kata kunci. Tidak ada konten yang keluar dari komputer ini."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "Luring"
@@ -10273,13 +10303,9 @@ msgstr "Buka panel aktivitas untuk {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "Buka panel aktivitas untuk {tooltipName}, yang sedang menyunting {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "Buka panel agen"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "Buka panel agen — {liveThreadCount, plural, other {# utas agen aktif}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "Buka agen"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10326,6 +10352,10 @@ msgstr "Membuka konfirmasi penghapusan untuk item pohon berkas yang dipilih."
msgid "Open documents tagged #{chip}"
msgstr "Buka dokumen bertag #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "Buka penyunting"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "Buka draf surel"
@@ -10497,7 +10527,7 @@ msgstr "Buka panel lint sumber"
msgid "Open source: {mirrorSrc}"
msgstr "Buka sumber: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "Buka terminal"
@@ -11058,6 +11088,14 @@ msgstr "Geser ke atas"
msgid "pane {0}"
msgstr "panel {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "Panel {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "Panel"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Paragraf"
@@ -11466,6 +11504,7 @@ msgstr "proyek"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Proyek"
@@ -11859,7 +11898,7 @@ msgstr "Direkomendasikan"
msgid "Recommended agent skill"
msgstr "Keterampilan agen yang direkomendasikan"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "Perlu menyambung ulang"
@@ -12448,10 +12487,19 @@ msgstr "Setel ulang filter tampilan"
msgid "Resize {handleKey}"
msgstr "Ubah ukuran {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "Ubah ukuran panel dokumen"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "Ubah ukuran panel Keterampilan"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "Ubah ukuran terminal"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Selesaikan konfliknya di terminal Anda"
@@ -12864,9 +12912,8 @@ msgid "Scroll to start"
msgstr "Gulir ke awal"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12876,10 +12923,6 @@ msgstr "Cari"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "Cari \"{semanticSubmitQuery}\" berdasarkan makna"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "Cari ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "Cari agen"
@@ -13545,6 +13588,11 @@ msgstr "Tampilkan diagram"
msgid "Show document panel"
msgstr "Tampilkan panel dokumen"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "Tampilkan Penyunting"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "Tampilkan simpul URL eksternal"
@@ -13553,7 +13601,7 @@ msgstr "Tampilkan simpul URL eksternal"
msgid "Show fewer"
msgstr "Tampilkan lebih sedikit"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Tampilkan Berkas"
@@ -13610,12 +13658,12 @@ msgid "Show original"
msgstr "Tampilkan versi asli"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "Tampilkan panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "Tampilkan panel ({panelShortcutLabel})"
@@ -14434,7 +14482,7 @@ msgstr "Mode sinkronisasi"
msgid "Sync now"
msgstr "Sinkronkan sekarang"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "Sinkronisasi dijeda"
@@ -14612,6 +14660,7 @@ msgstr "Templat tersedia"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16412,6 +16461,10 @@ msgstr "properti folder diperbarui"
msgid "Updated to Version {version}"
msgstr "Diperbarui ke Versi {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "Pembaruan dan masukan"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "Pembaruan mengalir masuk"
@@ -16985,10 +17038,6 @@ msgstr "Ruang kerja"
msgid "Workspace Command Palette"
msgstr "Palet Perintah Ruang Kerja"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "Navigasi ruang kerja"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 865d65970..0c93514c3 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -333,6 +333,7 @@
"3Fcb0I": ["그래프 열기"],
"3HAPpl": ["검색과 일치하는 스키마 없음."],
"3HNlwb": ["안녕하세요, 여러분!"],
+ "3HOAcR": ["에이전트 패널"],
"3Ib6FN": ["아래로 이동"],
"3J7d2N": ["큰 섹션 제목입니다."],
"3JYy1p": ["브랜치 ", ["0"], "는 더 이상 존재하지 않습니다. 기본 브랜치로 클론했습니다."],
@@ -516,6 +517,7 @@
],
"5OTgC7": ["하단의 AI에게 묻기 프롬프트 작성기를 열고 포커스를 둡니다."],
"5OqaJi": ["프로젝트 이름 입력"],
+ "5Q9-G-": ["문서 패널"],
"5QGTaA": ["상대 경로를 복사하지 못했습니다"],
"5RiC8D": [
"검색 스킬은 모든 AI 도구에서 함께 관리됩니다. 설정 → 스킬 스튜디오에서 이 스킬을 설치하세요."
@@ -741,6 +743,7 @@
"7cAW1G": ["이 엔드포인트에 API 키가 설정되지 않았습니다. 위에서 추가합니다."],
"7czmD1": ["OpenKnowledge에서 작성 팔레트 조회"],
"7d1a0d": ["공개"],
+ "7dDoQu": ["편집기 패널"],
"7dZnmw": ["관련성"],
"7hctf2": ["만들려는 프로젝트 설명"],
"7idx48": ["OKF 에이전트 스킬 설치됨"],
@@ -1220,7 +1223,6 @@
"DWJtEo": ["다음 단계"],
"DXd9LM": ["새 워크트리"],
"D_WKe_": ["참여자 표시줄에서 에이전트 아바타를 클릭하면 세션을 볼 수 있습니다."],
- "DbCfXV": ["검색 (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"일치하는 항목이 없습니다. 일부 파일은 숨김 파일 또는 무시된 파일이라 검색에서 제외됩니다."
],
@@ -1427,6 +1429,7 @@
")를 실행 중입니다."
],
"FWSjnp": ["소스 창과 코드 속성 필드를 편집합니다."],
+ "FYy2EN": ["문서 패널 크기 조절"],
"FZtBeR": [["0"], " 활성화"],
"FeXcUS": [
["display"],
@@ -1488,6 +1491,7 @@
"이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
],
"GBQjiV": ["스킬 추가"],
+ "GCrhIF": ["패널"],
"GDvlUT": ["역할"],
"GEyl32": ["터미널 시작 중…"],
"GGsM4y": ["그래프에서 선택됨"],
@@ -2009,7 +2013,6 @@
"심볼릭 링크는 독립된 폴더 대신 소스 폴더를 가리킵니다. 모든 위치에서 정확히 같은 바이트를 읽으므로 내용이 달라질 수 없고, 소스를 삭제하면 해당 위치가 작동하지 않습니다."
],
"MTs6g3": ["서버를 다시 시작한 후 다시 연결하지 못했습니다"],
- "MU_NVW": ["터미널 접기"],
"MUrVEo": ["최근 프로젝트 없음."],
"MV-Dkb": [["countDisplay"], "개의 markdown 파일을 찾았습니다"],
"MVxpbf": ["찾기 및 바꾸기"],
@@ -2744,13 +2747,13 @@
],
"V48OUT": ["로컬에서 <0>", ["filePath"], "</0>을 삭제했지만, 원격에서 수정되었습니다."],
"V4JHny": ["공유는 GitHub 원격만 지원합니다."],
- "V6AIOn": ["워크스페이스 탐색"],
"V6e25h": ["테마 미리보기"],
"V7QxyT": ["연결 끊김"],
"VAHWL_": ["계정 <0>@", ["signedInLogin"], "</0>으로 연결됨"],
"VBE2dw": [
"이야기 속 세계를 만들고 관리합니다. 캐릭터, 장소, 세력, 그리고 이들을 연결하는 설정을 한곳에 모아 글을 쓰는 동안 세부 정보가 일관되게 유지되도록 합니다."
],
+ "VBtCdv": ["해당 구절로 스크롤하지 못했습니다. 다시 시도하세요."],
"VFQXPl": [
"외부 링크 위에 마우스를 올리면 사이트 이름, 페이지 제목, 설명이 있는 미리보기 카드가 나타납니다."
],
@@ -2887,7 +2890,6 @@
"X2zUS5": ["이 댓글 삭제"],
"X3MMeA": ["이 문제들에는 자동 수정이 없습니다."],
"X59Fx2": ["이 문서를 Slidev에서 열지 못했습니다."],
- "X7ShnN": ["에이전트 패널 열기"],
"X8kjQX": ["GitHub 재인증"],
"X9VpsP": ["폴더 내용 불러오는 중"],
"XA9uvc": ["OpenKnowledge가 백그라운드에서 업데이트를 확인하고 다운로드합니다."],
@@ -3027,6 +3029,7 @@
"YS9mSt": ["\"", ["name"], "\"을 ", ["0"], "에서 업데이트했습니다"],
"YSFv5w": ["git 저장소 없음, 여기에는 config 공유가 적용되지 않습니다."],
"YScUUO": ["웹 페이지를 가져옵니다"],
+ "YStFYH": ["에이전트 열기"],
"YTLmTM": ["상위 <0>.git</0> 폴더 제거"],
"YW7Q86": ["검색 설정을 아직 불러오지 못했습니다. 잠시 후 다시 시도합니다."],
"YWK2zy": [["fileName"], "의 충돌 차이"],
@@ -3293,6 +3296,7 @@
"aS77on": ["무엇이 바뀌나요?"],
"aSVmqV": ["아직 감지된 AI 도구가 없습니다. 설치한 후 Settings > This project에서 연결하세요."],
"aTDVi6": ["콘텐츠를 보관했습니다"],
+ "aV2vel": ["패널 ", ["number"]],
"aWlJai": ["로그인 흐름 시작 중"],
"aXkLuE": ["잘못된 apply 응답"],
"a_u4ck": ["태그 불러오는 중"],
@@ -3751,6 +3755,7 @@
"f1-q9m": ["스킬을 유지합니다"],
"f14doC": ["Slidev"],
"f1XQyZ": ["블록 이동"],
+ "f3YhVJ": ["열린 항목 없음"],
"f65AOQ": ["시작 위치"],
"f6suyZ": ["변경 요청됨"],
"f8fH8W": ["디자인"],
@@ -3768,6 +3773,7 @@
"fKsRVO": [["0"], "/", ["1"], "의 스킬."],
"fMsFdZ": ["자동 업데이트 설정 저장 실패: ", ["0"]],
"fNr-MX": ["의미 기반 검색 사용 안 함"],
+ "fObclJ": ["편집기로 돌아가기"],
"fOzzSV": ["링크 대상 \"", ["shown"], "\"이 존재하는 파일로 확인되지 않습니다."],
"fRVBiq": [
"사용 가능한 경우 텔레메트리, 서버 상태, 런타임 정보를 추가합니다. 자격 증명은 항상 제거되며, 포함된 문서 이름은 비공개 처리되지 않은 일반 텍스트로 표시됩니다."
@@ -3839,7 +3845,6 @@
["descriptorLabel"],
"> 컴포넌트를 렌더링하지 못했습니다. 잘못된 속성 때문일 수 있습니다. 문제를 확인하려면 소스를 복사하거나 블록을 삭제하세요."
],
- "g5V4_P": ["에이전트 패널 접기"],
"g5w1sF": [
"병합 대상 폴더를 ",
["display"],
@@ -4068,10 +4073,6 @@
"i04BJx": ["이 프로젝트 밖에 있습니다 — 여기서는 읽기 전용입니다."],
"i09An-": ["이전 버전 (", ["0"], ")으로 복원했습니다"],
"i1flq_": ["위키 링크 제안"],
- "i25FHa": [
- "에이전트 패널 열기 — ",
- ["liveThreadCount", "plural", { "other": ["#", " 실행 중인 에이전트 대화"] }]
- ],
"i3f2kh": ["일치하는 명령이 없습니다."],
"i6o7XB": ["언어 검색"],
"i92eAT": ["저장소를 만들고 동기화를 시작합니다. 터미널은 필요하지 않습니다."],
@@ -4594,6 +4595,7 @@
],
"n7aopT": ["편집기 모드"],
"n81AV0": [["owner"], "/", ["name"], "이 이미 존재합니다. 다른 이름을 선택하세요."],
+ "nBFK5w": ["터미널 크기 조절"],
"nBHvPL": ["편집 취소"],
"nBgzKO": ["이 위치를 소스로 지정. 스킬의 실제 폴더가 여기로 이동합니다"],
"nCzR-G": ["코드 ", ["userCode"], " 복사"],
@@ -4910,6 +4912,7 @@
"qyLmWw": ["소스 편집기 검색 패널"],
"qze9od": ["이 폴더는 ", ["alsoAffects"], "의 폴더이기도 합니다."],
"r-OJYm": ["유효한 브랜치 이름을 입력하세요(공백, 앞의 점, \"..\" 제외)."],
+ "r-wzd8": ["업데이트 및 피드백"],
"r2eKE3": ["먼저 ", ["agentName"], " 로그인"],
"r3iaI0": ["아직 채팅이 없습니다."],
"r4R7AZ": ["정리 중 네트워크 오류가 발생했습니다."],
@@ -5160,6 +5163,7 @@
"ten9en": ["최근 프로젝트"],
"tfDRzk": ["저장"],
"tfi40B": ["페이지 만들기 실패"],
+ "tgB_VT": ["편집기 열기"],
"tgWuMB": ["수정됨"],
"thnPBX": ["다음 편집기 탭 활성화"],
"ti6aF_": [["0"], " CLI 질문"],
@@ -5319,6 +5323,7 @@
"un-K1H": ["이 컴퓨터에 유지됩니다. git에 커밋되지 않습니다."],
"un8kBM": ["페이지 만드는 중: ", ["linkTitle"], "."],
"uoJF_D": ["설정하거나 시작하기가 너무 어려웠습니다"],
+ "uqgCZJ": ["편집기 가리기"],
"uqs8Gd": [["others", "plural", { "other": ["다른 파일 ", "#", "개"] }]],
"ur2XSb": ["비주얼 편집기"],
"uraHF0": ["GitLab"],
@@ -5611,6 +5616,7 @@
"xzAmL_": ["자동 승인됨"],
"xzktOa": ["위키 링크 편집"],
"y-LQPF": ["해결할 수 없는 이미지 ", ["identity"], ". 참조로 이동합니다."],
+ "y0_w13": ["편집기 표시"],
"y1eoq1": ["링크 복사"],
"y1t8bQ": ["설정 섹션"],
"y3aU20": ["변경 사항 저장"],
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 84c98a485..f47ecd80c 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -1674,6 +1674,7 @@ msgstr "활성"
msgid "Active panel content for the selected tab shows here."
msgstr "선택한 탭의 활성 패널 콘텐츠가 여기에 표시됩니다."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "활동"
@@ -1965,6 +1966,10 @@ msgstr "에이전트 연결"
msgid "Agent mode"
msgstr "에이전트 모드"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "에이전트 패널"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Terminal을 읽기 쉽게 에이전트 패널을 닫았습니다."
@@ -1987,6 +1992,7 @@ msgstr "에이전트 대화 기록"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "에이전트"
@@ -2183,6 +2189,7 @@ msgstr "앱 인스턴스: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "변경 사항의 추가 전용 로그입니다."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "애플리케이션"
@@ -2547,6 +2554,10 @@ msgstr "뒤로"
msgid "Back to document view"
msgstr "문서 보기로 돌아가기"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "편집기로 돌아가기"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "백링크"
@@ -3467,10 +3478,6 @@ msgstr "접기"
msgid "Collapse {keyName}"
msgstr "{keyName} 접기"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "에이전트 패널 접기"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "Ask AI 접기"
msgid "Collapse graph"
msgstr "그래프 접기"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "터미널 접기"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "접을 수 있는 콘텐츠 블록입니다. Notion 스타일 토글입니다."
@@ -3665,7 +3668,7 @@ msgstr "사용자, 프로젝트 및 통합 설정을 구성합니다."
msgid "conflict"
msgstr "충돌"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "충돌"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "\"{0}\" 복제 실패: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "해당 구절을 찾지 못했습니다. 원문 변경 가능성이 있습니다."
@@ -4669,6 +4673,10 @@ msgstr "이 설정을 저장하지 못했습니다. 다시 시도하세요."
msgid "Couldn't save your theme preference."
msgstr "테마 설정을 저장하지 못했습니다."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "해당 구절로 스크롤하지 못했습니다. 다시 시도하세요."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "보고서를 보내지 못했습니다"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "Diff 렌더링 모드"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Diff 사용 불가"
@@ -5410,6 +5419,10 @@ msgstr "문서를 찾을 수 없음"
msgid "Document outline"
msgstr "문서 개요"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "문서 패널"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "문서 패널"
@@ -5733,6 +5746,7 @@ msgstr "{boldName} 직접 편집 중입니다. 변경 사항은 편집기의 복
msgid "Editing broken MDX source: {reason}"
msgstr "손상된 MDX 소스 편집 중: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "편집기"
@@ -5745,6 +5759,10 @@ msgstr "편집기 모드"
msgid "editor pane"
msgstr "편집기 패널"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "편집기 패널"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "편집기 선택 영역"
@@ -6691,6 +6709,7 @@ msgstr "파일: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "파일 이름"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "파일"
@@ -7353,11 +7372,17 @@ msgstr "세부 정보 숨기기"
msgid "Hide document panel"
msgstr "문서 패널 가리기"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "편집기 가리기"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "외부 URL 노드 숨기기"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "파일 숨기기"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "다른 앱 가리기"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "패널 숨기기"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "패널 숨기기 ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "링크 대상, 앵커, 표시 레이블을 수정합니다."
msgid "More"
msgstr "더 보기"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "추가 작업"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "추가 작업 ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "요청하기 전까지는 아무것도 움직이지 않습니다. 동기
msgid "Nothing moves until you ask."
msgstr "요청하기 전까지는 아무것도 움직이지 않습니다."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "열린 항목 없음"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "아직 설정된 항목 없음."
@@ -10111,7 +10141,7 @@ msgstr "꺼짐, 외부 링크에는 URL만 나타납니다. 이 컴퓨터 밖으
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "꺼짐, 검색은 키워드로만 순위를 매깁니다. 이 컴퓨터 밖으로 콘텐츠가 전송되지 않습니다."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "오프라인"
@@ -10277,13 +10307,9 @@ msgstr "{tooltipName} 활동 패널 열기"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "{tooltipName} 활동 패널 열기, {realCurrentDoc} 편집 중"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "에이전트 패널 열기"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "에이전트 패널 열기 — {liveThreadCount, plural, other {# 실행 중인 에이전트 대화}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "에이전트 열기"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "선택한 파일 트리 항목의 삭제 확인을 엽니다."
msgid "Open documents tagged #{chip}"
msgstr "#{chip} 태그가 있는 문서 열기"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "편집기 열기"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "이메일 초안 열기"
@@ -10501,7 +10531,7 @@ msgstr "소스 lint 패널 열기"
msgid "Open source: {mirrorSrc}"
msgstr "소스 열기: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "터미널 열기"
@@ -11062,6 +11092,14 @@ msgstr "위로 이동"
msgid "pane {0}"
msgstr "패널 {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "패널 {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "패널"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "문단"
@@ -11470,6 +11508,7 @@ msgstr "프로젝트"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "프로젝트"
@@ -11863,7 +11902,7 @@ msgstr "권장"
msgid "Recommended agent skill"
msgstr "권장 에이전트 스킬"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "다시 연결 필요"
@@ -12452,10 +12491,19 @@ msgstr "보기 필터 초기화"
msgid "Resize {handleKey}"
msgstr "{handleKey} 크기 조정"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "문서 패널 크기 조절"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "스킬 패널 크기 조절"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "터미널 크기 조절"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "터미널에서 충돌 해결"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "시작으로 스크롤"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "검색"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "“{semanticSubmitQuery}”를 의미로 검색"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "검색 ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "에이전트 검색"
@@ -13549,6 +13592,11 @@ msgstr "다이어그램 보기"
msgid "Show document panel"
msgstr "문서 패널 표시"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "편집기 표시"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "외부 URL 노드 보기"
@@ -13557,7 +13605,7 @@ msgstr "외부 URL 노드 보기"
msgid "Show fewer"
msgstr "더 적게 보기"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "파일 보기"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "원본 표시"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "패널 보기"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "패널 보기 ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "동기화 모드"
msgid "Sync now"
msgstr "지금 동기화"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "동기화 일시 중지됨"
@@ -14616,6 +14664,7 @@ msgstr "사용 가능한 템플릿"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "폴더 속성 업데이트됨"
msgid "Updated to Version {version}"
msgstr "버전 {version}으로 업데이트됨"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "업데이트 및 피드백"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "업데이트가 들어옴"
@@ -16989,10 +17042,6 @@ msgstr "워크스페이스"
msgid "Workspace Command Palette"
msgstr "워크스페이스 명령 팔레트"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "워크스페이스 탐색"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/pl/messages.json b/packages/app/src/locales/pl/messages.json
index 2515f737b..5dd676be5 100644
--- a/packages/app/src/locales/pl/messages.json
+++ b/packages/app/src/locales/pl/messages.json
@@ -415,6 +415,7 @@
"3Fcb0I": ["Otwórz graf"],
"3HAPpl": ["Żaden schemat nie pasuje do wyszukiwania."],
"3HNlwb": ["Witaj, świecie!"],
+ "3HOAcR": ["Panel agentów"],
"3Ib6FN": ["Przenieś w dół"],
"3J7d2N": ["Duży nagłówek sekcji."],
"3JYy1p": ["Gałąź ", ["0"], " już nie istnieje. Sklonowano do gałęzi domyślnej."],
@@ -630,6 +631,7 @@
],
"5OTgC7": ["Otwórz i ustaw fokus na dolnym polu wpisywania Zapytaj AI."],
"5OqaJi": ["Wpisz nazwę projektu"],
+ "5Q9-G-": ["Panel dokumentu"],
"5QGTaA": ["Nie udało się skopiować ścieżki względnej"],
"5RiC8D": [
"Umiejętności discovery są zarządzane wspólnie dla wszystkich narzędzi AI. Zainstaluj tę z Ustawienia → Studio umiejętności."
@@ -929,6 +931,7 @@
"7cAW1G": ["Dla tego punktu końcowego nie ustawiono klucza API. Dodaj go powyżej."],
"7czmD1": ["OpenKnowledge wyszukało paletę tworzenia"],
"7d1a0d": ["Publiczne"],
+ "7dDoQu": ["Panel edytora"],
"7dZnmw": ["Trafność"],
"7hctf2": ["Opisz projekt, który chcesz utworzyć"],
"7idx48": ["Zainstalowano umiejętność agenta OKF"],
@@ -1510,7 +1513,6 @@
"DWJtEo": ["Co dalej"],
"DXd9LM": ["Nowe worktree"],
"D_WKe_": ["Kliknij awatar agenta na pasku obecności, aby zobaczyć jego sesję."],
- "DbCfXV": ["Szukaj (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"Brak dopasowań. Niektóre pliki są wyłączone z wyszukiwania (ukryte lub ignorowane)."
],
@@ -1749,6 +1751,7 @@
")."
],
"FWSjnp": ["Panel edycji źródła i pola właściwości kodu"],
+ "FYy2EN": ["Zmień rozmiar panelu dokumentu"],
"FZtBeR": ["Włącz ", ["0"]],
"FeXcUS": [
["display"],
@@ -1821,6 +1824,7 @@
", ale nie udało się użyć danych dostępowych tego konta."
],
"GBQjiV": ["Dodaj umiejętność"],
+ "GCrhIF": ["Panele"],
"GDvlUT": ["Rola"],
"GEyl32": ["Uruchamianie terminala…"],
"GGsM4y": ["Zaznaczone w grafie"],
@@ -2475,7 +2479,6 @@
"Symlink to wskaźnik na folder źródłowy, a nie osobny folder. Każda lokalizacja czyta dokładnie te same bajty, więc nic nie może się rozjechać, a lokalizacja przestaje działać, gdy źródło zostanie usunięte."
],
"MTs6g3": ["Nie udało się ponownie połączyć po restarcie serwera"],
- "MU_NVW": ["Zwiń terminal"],
"MUrVEo": ["Brak ostatnich projektów."],
"MV-Dkb": ["Znaleziono ", ["countDisplay"], " plików Markdown"],
"MVxpbf": ["Znajdź i zamień"],
@@ -3362,13 +3365,13 @@
"</0> został usunięty lokalnie, ale zmodyfikowany w źródle."
],
"V4JHny": ["Udostępnianie obsługuje wyłącznie zdalne repozytoria GitHub."],
- "V6AIOn": ["Nawigacja po obszarze roboczym"],
"V6e25h": ["Podgląd motywu"],
"V7QxyT": ["Połączenie zostało zerwane"],
"VAHWL_": ["Połączono jako <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"Zbuduj i śledź świat stojący za Twoją historią. Miejsce dla Twoich postaci, miejsc, frakcji i legend, które je spinają, dzięki czemu szczegóły pozostają spójne, gdy piszesz."
],
+ "VBtCdv": ["Nie udało się przewinąć do tego fragmentu. Spróbuj ponownie."],
"VFQXPl": [
"Podglądy linków zewnętrznych pokazują kartę z nazwą strony, tytułem i opisem po najechaniu na link."
],
@@ -3556,7 +3559,6 @@
"X2zUS5": ["Usuń ten komentarz"],
"X3MMeA": ["Żaden z tych problemów nie ma automatycznej poprawki."],
"X59Fx2": ["Nie można otworzyć tego dokumentu w Slidev."],
- "X7ShnN": ["Otwórz panel agentów"],
"X8kjQX": ["Uwierzytelnij się ponownie z GitHub"],
"X9VpsP": ["Ładowanie zawartości folderu"],
"XA9uvc": ["OpenKnowledge sprawdza i pobiera aktualizacje w tle."],
@@ -3725,6 +3727,7 @@
"YS9mSt": ["Zaktualizowano „", ["name"], "” na podstawie ", ["0"]],
"YSFv5w": ["Brak repozytorium git — udostępnianie konfiguracji nie dotyczy tego miejsca."],
"YScUUO": ["Pobiera stronę internetową"],
+ "YStFYH": ["Otwórz agentów"],
"YTLmTM": ["Usuń nadrzędny folder <0>.git</0>"],
"YW7Q86": ["Ustawienia wyszukiwania jeszcze się nie wczytały — spróbuj ponownie za chwilę"],
"YWK2zy": ["Widok różnic konfliktu dla ", ["fileName"]],
@@ -4022,6 +4025,7 @@
"Nie wykryto jeszcze narzędzi AI. Po zainstalowaniu połącz je w Ustawieniach > Ten projekt."
],
"aTDVi6": ["Zachowano Twoją zawartość"],
+ "aV2vel": ["Panel ", ["number"]],
"aWlJai": ["Uruchamianie procesu logowania"],
"aXkLuE": ["Nieprawidłowa odpowiedź apply"],
"a_u4ck": ["Ładowanie tagów"],
@@ -4633,6 +4637,7 @@
"f1-q9m": ["zachowuje umiejętności"],
"f14doC": ["Slidev"],
"f1XQyZ": ["Przenieś blok"],
+ "f3YhVJ": ["Nic nie jest otwarte"],
"f65AOQ": ["Zacznij od"],
"f6suyZ": ["Zażądano zmian"],
"f8fH8W": ["Design"],
@@ -4650,6 +4655,7 @@
"fKsRVO": ["Umiejętności z ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["Nie udało się zapisać ustawienia automatycznej aktualizacji: ", ["0"]],
"fNr-MX": ["Wyłącz wyszukiwanie semantyczne"],
+ "fObclJ": ["Wróć do edytora"],
"fOzzSV": ["Cel linku „", ["shown"], "” nie wskazuje na istniejący plik."],
"fRVBiq": [
"Dodaje telemetrię, stan serwera i informacje o czasie działania, gdy są dostępne. Dane logowania są zawsze usuwane; nazwy dokumentów, jeśli są dołączone, pojawiają się w postaci jawnej (bez maskowania)."
@@ -4758,7 +4764,6 @@
["descriptorLabel"],
"> nie wyrenderował się (prawdopodobnie zła właściwość). Skopiuj źródło, aby zobaczyć, co poszło nie tak, albo usuń blok."
],
- "g5V4_P": ["Zwiń panel agenta"],
"g5w1sF": [
"Wybierz folder do POŁĄCZENIA Z ",
["display"],
@@ -5034,19 +5039,6 @@
"i04BJx": ["Znajduje się poza tym projektem — tutaj tylko do odczytu."],
"i09An-": ["Przywrócono wcześniejszą wersję (", ["0"], ")"],
"i1flq_": ["Podpowiedzi linków wiki"],
- "i25FHa": [
- "Otwórz panel agentów — ",
- [
- "liveThreadCount",
- "plural",
- {
- "one": ["#", " aktywny wątek agenta"],
- "few": ["#", " aktywne wątki agenta"],
- "many": ["#", " aktywnych wątków agenta"],
- "other": ["#", " aktywnego wątku agenta"]
- }
- ]
- ],
"i3f2kh": ["Brak pasujących poleceń."],
"i6o7XB": ["Szukaj języków"],
"i92eAT": [
@@ -5647,6 +5639,7 @@
],
"n7aopT": ["Tryb edytora"],
"n81AV0": [["owner"], "/", ["name"], " już istnieje. Wybierz inną nazwę."],
+ "nBFK5w": ["Zmień rozmiar terminala"],
"nBHvPL": ["Anuluj edycję"],
"nBgzKO": ["Ustaw to jako źródło — prawdziwy folder umiejętności przenosi się tutaj"],
"nCzR-G": ["Skopiuj kod ", ["userCode"]],
@@ -6074,6 +6067,7 @@
"qyLmWw": ["Panel wyszukiwania w edytorze źródłowym"],
"qze9od": ["Ten folder należy również do ", ["alsoAffects"], "."],
"r-OJYm": ["Wpisz poprawną nazwę gałęzi (bez spacji, bez kropki na początku, bez \"..\")."],
+ "r-wzd8": ["Aktualizacje i opinie"],
"r2eKE3": ["Najpierw zaloguj się do ", ["agentName"]],
"r3iaI0": ["Brak czatów."],
"r4R7AZ": ["Błąd sieci podczas sprzątania"],
@@ -6352,6 +6346,7 @@
"ten9en": ["Ostatni projekt"],
"tfDRzk": ["Zapisz"],
"tfi40B": ["Nie udało się utworzyć strony"],
+ "tgB_VT": ["Otwórz edytor"],
"tgWuMB": ["Zmodyfikowane"],
"thnPBX": ["Aktywuj następną kartę edytora."],
"ti6aF_": ["Zapytaj CLI ", ["0"]],
@@ -6557,6 +6552,7 @@
"un-K1H": ["Pozostaje na tym komputerze. Nie jest zapisywane w Gitcie."],
"un8kBM": ["Tworzenie strony: ", ["linkTitle"], "."],
"uoJF_D": ["Był zbyt trudny w konfiguracji lub na starcie"],
+ "uqgCZJ": ["Ukryj edytor"],
"uqs8Gd": [
[
"others",
@@ -6949,6 +6945,7 @@
"xzAmL_": ["Zatwierdzone automatycznie"],
"xzktOa": ["Edytuj link wiki"],
"y-LQPF": ["Nie można rozwiązać obrazu ", ["identity"], ". Przejdź do odwołania."],
+ "y0_w13": ["Pokaż edytor"],
"y1eoq1": ["Kopiuj link"],
"y1t8bQ": ["Sekcje ustawień"],
"y3aU20": ["Zapisz zmiany"],
diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.po
index 405034dc1..f529c54fe 100644
--- a/packages/app/src/locales/pl/messages.po
+++ b/packages/app/src/locales/pl/messages.po
@@ -1674,6 +1674,7 @@ msgstr "Aktywne"
msgid "Active panel content for the selected tab shows here."
msgstr "Zawartość aktywnego panelu dla wybranej karty wyświetla się tutaj."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "Aktywność"
@@ -1965,6 +1966,10 @@ msgstr "Połączenia agentów"
msgid "Agent mode"
msgstr "Tryb agenta"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "Panel agentów"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Panel agenta został zamknięty, żeby Terminal pozostał czytelny."
@@ -1987,6 +1992,7 @@ msgstr "Transkrypcja agenta"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "Agenci"
@@ -2183,6 +2189,7 @@ msgstr "Instancja aplikacji: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "Dziennik tylko do dopisywania tego, co się zmieniło."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "Aplikacja"
@@ -2547,6 +2554,10 @@ msgstr "Wstecz"
msgid "Back to document view"
msgstr "Powrót do widoku dokumentu"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "Wróć do edytora"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "Linki zwrotne"
@@ -3467,10 +3478,6 @@ msgstr "Zwiń"
msgid "Collapse {keyName}"
msgstr "Zwiń {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "Zwiń panel agenta"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "Zwiń „Zapytaj AI”"
msgid "Collapse graph"
msgstr "Zwiń graf"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Zwiń terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "Blok treści z możliwością zwijania (przełącznik w stylu Notion)."
@@ -3665,7 +3668,7 @@ msgstr "Skonfiguruj ustawienia użytkownika, projektu i integracji."
msgid "conflict"
msgstr "konflikt"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Konflikt"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "Nie udało się zduplikować „{0}”: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "Nie udało się znaleźć tego fragmentu — tekst, na którym się znajdował, mógł się zmienić."
@@ -4669,6 +4673,10 @@ msgstr "Nie udało się zapisać tego ustawienia. Spróbuj ponownie."
msgid "Couldn't save your theme preference."
msgstr "Nie udało się zapisać preferencji motywu."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "Nie udało się przewinąć do tego fragmentu. Spróbuj ponownie."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "Nie udało się wysłać zgłoszenia"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "Tryb renderowania diffu"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Diff niedostępny"
@@ -5410,6 +5419,10 @@ msgstr "Nie znaleziono dokumentu"
msgid "Document outline"
msgstr "Plan dokumentu"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "Panel dokumentu"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "Panele dokumentu"
@@ -5733,6 +5746,7 @@ msgstr "Edytowanie {boldName} na miejscu. Zmiany zapisują się bezpośrednio w
msgid "Editing broken MDX source: {reason}"
msgstr "Edycja uszkodzonego źródła MDX: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "Edytor"
@@ -5745,6 +5759,10 @@ msgstr "Tryb edytora"
msgid "editor pane"
msgstr "panel edytora"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "Panel edytora"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Zaznaczenie w edytorze"
@@ -6691,6 +6709,7 @@ msgstr "Plik: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "Nazwa pliku"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "Pliki"
@@ -7353,11 +7372,17 @@ msgstr "Ukryj szczegóły"
msgid "Hide document panel"
msgstr "Ukryj panel dokumentu"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "Ukryj edytor"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "Ukryj węzły zewnętrznych adresów URL"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Ukryj pliki"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "Ukryj pozostałe"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "Ukryj panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "Ukryj panel ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "Zmień cel linku, kotwicę i etykietę wyświetlaną."
msgid "More"
msgstr "Więcej"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "Więcej akcji"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "Więcej akcji ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "Nic nie rusza się bez twojej prośby — pobieraj i wysyłaj z menu syn
msgid "Nothing moves until you ask."
msgstr "Nic nie rusza się bez twojej prośby."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "Nic nie jest otwarte"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Nic jeszcze nie ustawiono."
@@ -10111,7 +10141,7 @@ msgstr "Wyłączone — linki zewnętrzne pokazują tylko swój adres URL. Żadn
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Wyłączone — wyszukiwanie sortuje wyłącznie według słów kluczowych. Żadna zawartość nie opuszcza tego komputera."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "Offline"
@@ -10277,13 +10307,9 @@ msgstr "Otwórz panel aktywności dla {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "Otwórz panel aktywności dla {tooltipName}, edytując {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "Otwórz panel agentów"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "Otwórz panel agentów — {liveThreadCount, plural, one {# aktywny wątek agenta} few {# aktywne wątki agenta} many {# aktywnych wątków agenta} other {# aktywnego wątku agenta}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "Otwórz agentów"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "Otwórz potwierdzenie usunięcia dla zaznaczonych elementów drzewa plik
msgid "Open documents tagged #{chip}"
msgstr "Otwórz dokumenty oznaczone #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "Otwórz edytor"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "Otwórz szkic wiadomości e-mail"
@@ -10501,7 +10531,7 @@ msgstr "Otwórz panel lintu kodu źródłowego"
msgid "Open source: {mirrorSrc}"
msgstr "Otwórz źródło: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "Otwórz terminal"
@@ -11062,6 +11092,14 @@ msgstr "Przesuń w górę"
msgid "pane {0}"
msgstr "panel {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "Panel {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "Panele"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Akapit"
@@ -11470,6 +11508,7 @@ msgstr "projekt"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Projekt"
@@ -11863,7 +11902,7 @@ msgstr "Zalecane"
msgid "Recommended agent skill"
msgstr "Zalecana umiejętność agenta"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "Wymagane ponowne połączenie"
@@ -12452,10 +12491,19 @@ msgstr "Zresetuj filtry widoku"
msgid "Resize {handleKey}"
msgstr "Zmień rozmiar {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "Zmień rozmiar panelu dokumentu"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "Zmień rozmiar panelu umiejętności"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "Zmień rozmiar terminala"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Rozwiąż konflikt w terminalu"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "Przewiń na początek"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "Szukaj"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "Szukaj \"{semanticSubmitQuery}\" według znaczenia"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "Szukaj ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "Szukaj agentów"
@@ -13549,6 +13592,11 @@ msgstr "Pokaż diagram"
msgid "Show document panel"
msgstr "Pokaż panel dokumentu"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "Pokaż edytor"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "Pokazuj węzły zewnętrznych adresów URL"
@@ -13557,7 +13605,7 @@ msgstr "Pokazuj węzły zewnętrznych adresów URL"
msgid "Show fewer"
msgstr "Pokaż mniej"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Pokaż pliki"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "Pokaż oryginał"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "Pokaż panel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "Pokaż panel ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "Tryb synchronizacji"
msgid "Sync now"
msgstr "Synchronizuj teraz"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "Synchronizacja wstrzymana"
@@ -14616,6 +14664,7 @@ msgstr "Dostępne szablony"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "zaktualizowano właściwości folderu"
msgid "Updated to Version {version}"
msgstr "Zaktualizowano do wersji {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "Aktualizacje i opinie"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "Napływające aktualizacje"
@@ -16989,10 +17042,6 @@ msgstr "Obszar roboczy"
msgid "Workspace Command Palette"
msgstr "Paleta poleceń obszaru roboczego"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "Nawigacja po obszarze roboczym"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 6cd32d6e5..596d4dad0 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -347,6 +347,7 @@
"3Fcb0I": ["Ōƥēń ĝŕàƥĥ"],
"3HAPpl": ["Ńō śćĥēḿàś ḿàţćĥ ŷōũŕ śēàŕćĥ."],
"3HNlwb": ["Ĥēĺĺō, ŵōŕĺď!"],
+ "3HOAcR": ["Àĝēńţ ƥàńēĺ"],
"3Ib6FN": ["Ḿōvē ďōŵń"],
"3J7d2N": ["ßĩĝ śēćţĩōń ĥēàďĩńĝ."],
"3JYy1p": ["ßŕàńćĥ ", ["0"], " ńō ĺōńĝēŕ ēxĩśţś. Ćĺōńēď ţō ďēƒàũĺţ ƀŕàńćĥ."],
@@ -533,6 +534,7 @@
],
"5OTgC7": ["Ōƥēń àńď ƒōćũś ţĥē ƀōţţōḿ Àśķ ÀĨ ƥŕōḿƥţ ćōḿƥōśēŕ."],
"5OqaJi": ["Ēńţēŕ à ƥŕōĴēćţ ńàḿē"],
+ "5Q9-G-": ["Ďōćũḿēńţ ƥàńēĺ"],
"5QGTaA": ["Ćōũĺď ńōţ ćōƥŷ ŕēĺàţĩvē ƥàţĥ"],
"5RiC8D": [
"Ďĩśćōvēŕŷ śķĩĺĺś àŕē ḿàńàĝēď ƒōŕ àĺĺ ÀĨ ţōōĺś ţōĝēţĥēŕ. Ĩńśţàĺĺ ţĥĩś ōńē ƒŕōḿ Śēţţĩńĝś → Śķĩĺĺś Śţũďĩō."
@@ -762,6 +764,7 @@
"7cAW1G": ["Ńō ÀƤĨ ķēŷ ĩś śēţ ƒōŕ ţĥĩś ēńďƥōĩńţ. Àďď ōńē àƀōvē."],
"7czmD1": ["ŌƥēńĶńōŵĺēďĝē ĺōōķēď ũƥ ţĥē àũţĥōŕĩńĝ ƥàĺēţţē"],
"7d1a0d": ["Ƥũƀĺĩć"],
+ "7dDoQu": ["Ēďĩţōŕ ƥàńē"],
"7dZnmw": ["Ŕēĺēvàńćē"],
"7hctf2": ["Ďēśćŕĩƀē ţĥē ƥŕōĴēćţ ŷōũ ŵàńţ ţō ćŕēàţē"],
"7idx48": ["ŌĶƑ àĝēńţ śķĩĺĺ ĩńśţàĺĺēď"],
@@ -1268,7 +1271,6 @@
"DWJtEo": ["Ŵĥàţ ĥàƥƥēńś ńēxţ"],
"DXd9LM": ["Ńēŵ ŵōŕķţŕēē"],
"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],
- "DbCfXV": ["Śēàŕćĥ (", ["searchShortcutLabel"], ")"],
"DbILZA": ["Ńō ḿàţćĥēś. Śōḿē ƒĩĺēś àŕē ēxćĺũďēď ƒŕōḿ śēàŕćĥ (ĥĩďďēń ōŕ ĩĝńōŕēď ƒĩĺēś)."],
"DcFr-y": ["ŌƥēńĶńōŵĺēďĝē ďēĺēţēď à ďōćũḿēńţ"],
"DcH8-w": ["Ḿōvē ", ["0"], " ţō ƤŕōĴēćţ"],
@@ -1481,6 +1483,7 @@
")."
],
"FWSjnp": ["Ēďĩţ śōũŕćē ƥàńē àńď ćōďē ƥŕōƥēŕţŷ ƒĩēĺďś"],
+ "FYy2EN": ["Ŕēśĩźē ďōćũḿēńţ ƥàńēĺ"],
"FZtBeR": ["Ēńàƀĺē ", ["0"]],
"FeXcUS": [
["display"],
@@ -1538,6 +1541,7 @@
", ƀũţ ţĥàţ àććōũńţ'ś ćŕēďēńţĩàĺś ćōũĺďń'ţ ƀē ũśēď."
],
"GBQjiV": ["Àďď śķĩĺĺ"],
+ "GCrhIF": ["Ƥàńēĺś"],
"GDvlUT": ["Ŕōĺē"],
"GEyl32": ["Śţàŕţĩńĝ ţēŕḿĩńàĺ…"],
"GGsM4y": ["Śēĺēćţēď ĩń ĝŕàƥĥ"],
@@ -2088,7 +2092,6 @@
"À śŷḿĺĩńķ ĩś à ƥōĩńţēŕ ţō ţĥē śōũŕćē ƒōĺďēŕ ŕàţĥēŕ ţĥàń à ƒōĺďēŕ ōƒ ĩţś ōŵń. Ēvēŕŷ ĺōćàţĩōń ŕēàďś ţĥē ēxàćţ śàḿē ƀŷţēś, śō ńōţĥĩńĝ ćàń ďŕĩƒţ, àńď à ĺōćàţĩōń śţōƥś ŵōŕķĩńĝ ĩƒ ţĥē śōũŕćē ĩś ďēĺēţēď."
],
"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
- "MU_NVW": ["Ćōĺĺàƥśē Ţēŕḿĩńàĺ"],
"MUrVEo": ["Ńō ŕēćēńţ ƥŕōĴēćţś."],
"MV-Dkb": ["Ƒōũńď ", ["countDisplay"], " ḿàŕķďōŵń ƒĩĺēś"],
"MVxpbf": ["Ƒĩńď àńď ŕēƥĺàćē"],
@@ -2862,13 +2865,13 @@
],
"V48OUT": ["Ŷōũ ďēĺēţēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ḿōďĩƒĩēď ũƥśţŕēàḿ."],
"V4JHny": ["Śĥàŕĩńĝ śũƥƥōŕţś ĜĩţĤũƀ ŕēḿōţēś ōńĺŷ."],
- "V6AIOn": ["Ŵōŕķśƥàćē ńàvĩĝàţĩōń"],
"V6e25h": ["Ţĥēḿē ƥŕēvĩēŵ"],
"V7QxyT": ["Ćōńńēćţĩōń ďŕōƥƥēď"],
"VAHWL_": ["Ćōńńēćţēď àś <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"ßũĩĺď àńď ķēēƥ ţŕàćķ ōƒ ţĥē ŵōŕĺď ƀēĥĩńď ŷōũŕ śţōŕŷ. À ĥōḿē ƒōŕ ŷōũŕ ćĥàŕàćţēŕś, ƥĺàćēś, ƒàćţĩōńś, àńď ţĥē ĺōŕē ţĥàţ ţĩēś ţĥēḿ ţōĝēţĥēŕ, śō ďēţàĩĺś śţàŷ ćōńśĩśţēńţ àś ŷōũ ŵŕĩţē."
],
+ "VBtCdv": ["Ćōũĺďń'ţ śćŕōĺĺ ţō ţĥàţ ƥàśśàĝē. Ţŕŷ àĝàĩń."],
"VFQXPl": [
"Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś śĥōŵ à ćàŕď ŵĩţĥ ţĥē śĩţē ńàḿē, ƥàĝē ţĩţĺē, àńď ďēśćŕĩƥţĩōń ŵĥēń ŷōũ ĥōvēŕ à ĺĩńķ."
],
@@ -3004,7 +3007,6 @@
"X2zUS5": ["Ďēĺēţē ţĥĩś ćōḿḿēńţ"],
"X3MMeA": ["Ńōńē ōƒ ţĥēśē ƥŕōƀĺēḿś ĥàvē àń àũţōḿàţĩć ƒĩx."],
"X59Fx2": ["Ćōũĺďń'ţ ōƥēń ţĥĩś ďōćũḿēńţ ĩń Śĺĩďēv."],
- "X7ShnN": ["Ōƥēń àĝēńţś ƥàńēĺ"],
"X8kjQX": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ"],
"X9VpsP": ["Ĺōàďĩńĝ ƒōĺďēŕ ćōńţēńţś"],
"XA9uvc": ["ŌƥēńĶńōŵĺēďĝē ćĥēćķś ƒōŕ àńď ďōŵńĺōàďś ũƥďàţēś ĩń ţĥē ƀàćķĝŕōũńď."],
@@ -3149,6 +3151,7 @@
"YS9mSt": ["Ũƥďàţēď \"", ["name"], "\" ƒŕōḿ ", ["0"]],
"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],
"YScUUO": ["Ƒēţćĥēś à ŵēƀ ƥàĝē"],
+ "YStFYH": ["Ōƥēń àĝēńţś"],
"YTLmTM": ["Ŕēḿōvē ţĥē ƥàŕēńţ <0>.ĝĩţ</0> ƒōĺďēŕ"],
"YW7Q86": ["Śēàŕćĥ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"YWK2zy": ["Ćōńƒĺĩćţ ďĩƒƒ ƒōŕ ", ["fileName"]],
@@ -3425,6 +3428,7 @@
"Ńō ÀĨ ţōōĺś ďēţēćţēď ŷēţ. Ōńćē ŷōũ ĩńśţàĺĺ ōńē, ćōńńēćţ ĩţ ƒŕōḿ Śēţţĩńĝś > Ţĥĩś ƥŕōĴēćţ."
],
"aTDVi6": ["Ķēƥţ ŷōũŕ ćōńţēńţ"],
+ "aV2vel": ["Ƥàńē ", ["number"]],
"aWlJai": ["Śţàŕţĩńĝ śĩĝń-ĩń ƒĺōŵ"],
"aXkLuE": ["Ḿàĺƒōŕḿēď àƥƥĺŷ ŕēśƥōńśē"],
"a_u4ck": ["Ĺōàďĩńĝ ţàĝś"],
@@ -3910,6 +3914,7 @@
"f1-q9m": ["ķēēƥś ţĥē śķĩĺĺś"],
"f14doC": ["Śĺĩďēv"],
"f1XQyZ": ["Ḿōvē ƀĺōćķ"],
+ "f3YhVJ": ["Ńōţĥĩńĝ ōƥēń"],
"f65AOQ": ["Śţàŕţ ƒŕōḿ"],
"f6suyZ": ["Ćĥàńĝēś ŕēǫũēśţēď"],
"f8fH8W": ["Ďēśĩĝń"],
@@ -3927,6 +3932,7 @@
"fKsRVO": ["Śķĩĺĺś ƒŕōḿ ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["Ćōũĺďń'ţ śàvē ţĥē àũţō-ũƥďàţē śēţţĩńĝ: ", ["0"]],
"fNr-MX": ["Ďĩśàƀĺē śēḿàńţĩć śēàŕćĥ"],
+ "fObclJ": ["ßàćķ ţō ēďĩţōŕ"],
"fOzzSV": ["Ĺĩńķ ţàŕĝēţ \"", ["shown"], "\" ďōēś ńōţ ŕēśōĺvē ţō àń ēxĩśţĩńĝ ƒĩĺē."],
"fRVBiq": [
"Àďďś ţēĺēḿēţŕŷ, śēŕvēŕ śţàţē, àńď ŕũńţĩḿē ĩńƒō ŵĥēń àvàĩĺàƀĺē. Ćŕēďēńţĩàĺś àŕē àĺŵàŷś ŕēḿōvēď; ďōćũḿēńţ ńàḿēś, ĩƒ ĩńćĺũďēď, àƥƥēàŕ ĩń ćĺēàŕţēxţ (ńōţ ŕēďàćţēď)."
@@ -4013,7 +4019,6 @@
["descriptorLabel"],
"> ƒàĩĺēď ţō ŕēńďēŕ (ĺĩķēĺŷ à ƀàď ƥŕōƥ). Ćōƥŷ ţĥē śōũŕćē ţō śēē ŵĥàţ ŵēńţ ŵŕōńĝ, ōŕ ďēĺēţē ţĥē ƀĺōćķ."
],
- "g5V4_P": ["Ćōĺĺàƥśē àĝēńţ ƥàńēĺ"],
"g5w1sF": [
"Ƥĩćķ à ƒōĺďēŕ ţō ḿēŕĝē ĨŃŢŌ ",
["display"],
@@ -4252,14 +4257,6 @@
"i04BJx": ["Ĺĩvēś ōũţśĩďē ţĥĩś ƥŕōĴēćţ — ŕēàď-ōńĺŷ ĥēŕē."],
"i09An-": ["Ŕēśţōŕēď àń ēàŕĺĩēŕ vēŕśĩōń (", ["0"], ")"],
"i1flq_": ["Ŵĩķĩ ĺĩńķ śũĝĝēśţĩōńś"],
- "i25FHa": [
- "Ōƥēń àĝēńţś ƥàńēĺ — ",
- [
- "liveThreadCount",
- "plural",
- { "one": ["#", " ĺĩvē àĝēńţ ţĥŕēàď"], "other": ["#", " ĺĩvē àĝēńţ ţĥŕēàďś"] }
- ]
- ],
"i3f2kh": ["Ńō ḿàţćĥĩńĝ ćōḿḿàńďś."],
"i6o7XB": ["Śēàŕćĥ ĺàńĝũàĝēś"],
"i92eAT": ["Ŵē'ĺĺ ćŕēàţē à ŕēƥōśĩţōŕŷ àńď śţàŕţ śŷńćĩńĝ — ńō ţēŕḿĩńàĺ ńēēďēď."],
@@ -4796,6 +4793,7 @@
],
"n7aopT": ["Ēďĩţōŕ ḿōďē"],
"n81AV0": [["owner"], "/", ["name"], " àĺŕēàďŷ ēxĩśţś. Ƥĩćķ à ďĩƒƒēŕēńţ ńàḿē."],
+ "nBFK5w": ["Ŕēśĩźē ţēŕḿĩńàĺ"],
"nBHvPL": ["Ćàńćēĺ ēďĩţĩńĝ"],
"nBgzKO": ["Ḿàķē ţĥĩś ţĥē śōũŕćē — ţĥē śķĩĺĺ'ś ŕēàĺ ƒōĺďēŕ ḿōvēś ĥēŕē"],
"nCzR-G": ["Ćōƥŷ ćōďē ", ["userCode"]],
@@ -5150,6 +5148,7 @@
"qyLmWw": ["Śōũŕćē ēďĩţōŕ śēàŕćĥ ƥàńēĺ"],
"qze9od": ["Ţĥĩś ƒōĺďēŕ ĩś àĺśō ", ["alsoAffects"], "'ś."],
"r-OJYm": ["Ēńţēŕ à vàĺĩď ƀŕàńćĥ ńàḿē (ńō śƥàćēś, ńō ĺēàďĩńĝ ďōţ, ńō \"..\")."],
+ "r-wzd8": ["Ũƥďàţēś àńď ƒēēďƀàćķ"],
"r2eKE3": ["Śĩĝń ĩń ţō ", ["agentName"], " ƒĩŕśţ"],
"r3iaI0": ["Ńō ćĥàţś ŷēţ."],
"r4R7AZ": ["Ńēţŵōŕķ ēŕŕōŕ ďũŕĩńĝ ćĺēàńũƥ"],
@@ -5401,6 +5400,7 @@
"ten9en": ["Ŕēćēńţ ƥŕōĴēćţ"],
"tfDRzk": ["Śàvē"],
"tfi40B": ["Ƒàĩĺēď ţō ćŕēàţē ƥàĝē"],
+ "tgB_VT": ["Ōƥēń ēďĩţōŕ"],
"tgWuMB": ["Ḿōďĩƒĩēď"],
"thnPBX": ["Àćţĩvàţē ţĥē ńēxţ ēďĩţōŕ ţàƀ."],
"ti6aF_": ["Àśķ ", ["0"], " ĆĹĨ"],
@@ -5585,6 +5585,7 @@
"un-K1H": ["Śţàŷś ōń ţĥĩś ćōḿƥũţēŕ. Ńōţ ćōḿḿĩţţēď ţō ĝĩţ."],
"un8kBM": ["Ćŕēàţĩńĝ ƥàĝē: ", ["linkTitle"], "."],
"uoJF_D": ["Ĩţ ŵàś ţōō ĥàŕď ţō śēţ ũƥ ōŕ ĝēţ śţàŕţēď"],
+ "uqgCZJ": ["Ĥĩďē Ēďĩţōŕ"],
"uqs8Gd": [["others", "plural", { "one": ["#", " ōţĥēŕ"], "other": ["#", " ōţĥēŕś"] }]],
"ur2XSb": ["Vĩśũàĺ ēďĩţōŕ"],
"uraHF0": ["ĜĩţĹàƀ"],
@@ -5890,6 +5891,7 @@
"xzAmL_": ["Àũţō-àƥƥŕōvēď"],
"xzktOa": ["Ēďĩţ ŵĩķĩ ĺĩńķ"],
"y-LQPF": ["Ũńŕēśōĺvàƀĺē ĩḿàĝē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
+ "y0_w13": ["Śĥōŵ Ēďĩţōŕ"],
"y1eoq1": ["Ćōƥŷ ĺĩńķ"],
"y1t8bQ": ["Śēţţĩńĝś śēćţĩōńś"],
"y3aU20": ["Śàvē ćĥàńĝēś"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 3fc4d1115..93a55bb51 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1670,6 +1670,7 @@ msgstr ""
msgid "Active panel content for the selected tab shows here."
msgstr ""
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr ""
@@ -1961,6 +1962,10 @@ msgstr ""
msgid "Agent mode"
msgstr ""
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr ""
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr ""
@@ -1983,6 +1988,7 @@ msgstr ""
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr ""
@@ -2179,6 +2185,7 @@ msgstr ""
msgid "Append-only log of what changed."
msgstr ""
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr ""
@@ -2543,6 +2550,10 @@ msgstr ""
msgid "Back to document view"
msgstr ""
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr ""
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr ""
@@ -3463,10 +3474,6 @@ msgstr ""
msgid "Collapse {keyName}"
msgstr ""
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr ""
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3490,10 +3497,6 @@ msgstr ""
msgid "Collapse graph"
msgstr ""
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr ""
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr ""
@@ -3661,7 +3664,7 @@ msgstr ""
msgid "conflict"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr ""
@@ -4300,6 +4303,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr ""
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr ""
@@ -4665,6 +4669,10 @@ msgstr ""
msgid "Couldn't save your theme preference."
msgstr ""
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr ""
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr ""
@@ -5285,6 +5293,7 @@ msgid "Diff render mode"
msgstr ""
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr ""
@@ -5406,6 +5415,10 @@ msgstr ""
msgid "Document outline"
msgstr ""
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr ""
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr ""
@@ -5729,6 +5742,7 @@ msgstr ""
msgid "Editing broken MDX source: {reason}"
msgstr ""
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr ""
@@ -5741,6 +5755,10 @@ msgstr ""
msgid "editor pane"
msgstr ""
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr ""
@@ -6687,6 +6705,7 @@ msgstr ""
msgid "Filename"
msgstr ""
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr ""
@@ -7349,11 +7368,17 @@ msgstr ""
msgid "Hide document panel"
msgstr ""
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr ""
@@ -7384,12 +7409,13 @@ msgid "Hide Others"
msgstr ""
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr ""
@@ -9004,11 +9030,11 @@ msgstr ""
msgid "More"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr ""
@@ -10058,6 +10084,10 @@ msgstr ""
msgid "Nothing moves until you ask."
msgstr ""
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr ""
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr ""
@@ -10107,7 +10137,7 @@ msgstr ""
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr ""
@@ -10273,12 +10303,8 @@ msgstr ""
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr ""
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr ""
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
msgstr ""
#: src/lib/keyboard-shortcuts.ts
@@ -10326,6 +10352,10 @@ msgstr ""
msgid "Open documents tagged #{chip}"
msgstr ""
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr ""
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr ""
@@ -10497,7 +10527,7 @@ msgstr ""
msgid "Open source: {mirrorSrc}"
msgstr ""
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr ""
@@ -11058,6 +11088,14 @@ msgstr ""
msgid "pane {0}"
msgstr ""
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr ""
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr ""
@@ -11466,6 +11504,7 @@ msgstr ""
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr ""
@@ -11859,7 +11898,7 @@ msgstr ""
msgid "Recommended agent skill"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr ""
@@ -12448,10 +12487,19 @@ msgstr ""
msgid "Resize {handleKey}"
msgstr ""
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr ""
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr ""
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr ""
@@ -12864,9 +12912,8 @@ msgid "Scroll to start"
msgstr ""
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12876,10 +12923,6 @@ msgstr ""
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr ""
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr ""
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr ""
@@ -13545,6 +13588,11 @@ msgstr ""
msgid "Show document panel"
msgstr ""
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr ""
@@ -13553,7 +13601,7 @@ msgstr ""
msgid "Show fewer"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr ""
@@ -13610,12 +13658,12 @@ msgid "Show original"
msgstr ""
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr ""
@@ -14434,7 +14482,7 @@ msgstr ""
msgid "Sync now"
msgstr ""
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr ""
@@ -14612,6 +14660,7 @@ msgstr ""
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16412,6 +16461,10 @@ msgstr ""
msgid "Updated to Version {version}"
msgstr ""
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr ""
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr ""
@@ -16985,10 +17038,6 @@ msgstr ""
msgid "Workspace Command Palette"
msgstr ""
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr ""
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 63e779ad6..c38be414f 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -389,6 +389,7 @@
"3Fcb0I": ["Abrir o grafo"],
"3HAPpl": ["Nenhum esquema corresponde à sua busca."],
"3HNlwb": ["Olá, mundo!"],
+ "3HOAcR": ["Painel de agentes"],
"3Ib6FN": ["Mover para baixo"],
"3J7d2N": ["Título de seção grande."],
"3JYy1p": ["O ramo ", ["0"], " não existe mais. Clonado no ramo padrão."],
@@ -612,6 +613,7 @@
],
"5OTgC7": ["Abre e foca o compositor de prompts de Perguntar à IA na parte de baixo."],
"5OqaJi": ["Digite um nome de projeto"],
+ "5Q9-G-": ["Painel do documento"],
"5QGTaA": ["Não foi possível copiar o caminho relativo"],
"5RiC8D": [
"As habilidades de descoberta são gerenciadas em conjunto para todas as ferramentas de IA. Instale esta em Configurações → Estúdio de habilidades."
@@ -886,6 +888,7 @@
"7cAW1G": ["Nenhuma chave de API definida para este endpoint. Adicione uma acima."],
"7czmD1": ["OpenKnowledge consultou a paleta de edição"],
"7d1a0d": ["Público"],
+ "7dDoQu": ["Painel do editor"],
"7dZnmw": ["Relevância"],
"7hctf2": ["Descreva o projeto que você quer criar"],
"7idx48": ["OKF habilidade do agente instalada"],
@@ -1455,7 +1458,6 @@
"DWJtEo": ["O que acontece depois"],
"DXd9LM": ["Novo worktree"],
"D_WKe_": ["Clique no avatar de um agente na barra de presença para ver a sessão dele."],
- "DbCfXV": ["Buscar (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"Sem correspondências. Alguns arquivos ficam fora da busca (arquivos ocultos ou ignorados)."
],
@@ -1685,6 +1687,7 @@
")."
],
"FWSjnp": ["Painel de edição de código e campos de propriedade do tipo código"],
+ "FYy2EN": ["Redimensionar o painel do documento"],
"FZtBeR": ["Ativar ", ["0"]],
"FeXcUS": [
["display"],
@@ -1760,6 +1763,7 @@
", mas as credenciais dessa conta não puderam ser usadas."
],
"GBQjiV": ["Adicionar habilidade"],
+ "GCrhIF": ["Painéis"],
"GDvlUT": ["Função"],
"GEyl32": ["Iniciando terminal…"],
"GGsM4y": ["Selecionado no grafo"],
@@ -2392,7 +2396,6 @@
"Um link simbólico aponta para a pasta de origem em vez de ser uma pasta própria. Todos os locais leem exatamente os mesmos bytes, então nada se desvia, e um local para de funcionar se a origem for excluída."
],
"MTs6g3": ["Não deu para reconectar após o reinício do servidor"],
- "MU_NVW": ["Recolher o Terminal"],
"MUrVEo": ["Nenhum projeto recente."],
"MV-Dkb": [["countDisplay"], " arquivos markdown encontrados"],
"MVxpbf": ["Buscar e substituir"],
@@ -3247,13 +3250,13 @@
"</0> localmente, mas ele foi modificado no remoto."
],
"V4JHny": ["O compartilhamento só funciona com remotos do GitHub."],
- "V6AIOn": ["Navegação do espaço de trabalho"],
"V6e25h": ["Pré-visualização do tema"],
"V7QxyT": ["A conexão caiu"],
"VAHWL_": ["Conectado como <0>@", ["signedInLogin"], "</0>"],
"VBE2dw": [
"Construa e organize o mundo por trás da sua história. Um lugar para seus personagens, lugares, facções e a mitologia que os une, para que os detalhes não se contradigam enquanto você escreve."
],
+ "VBtCdv": ["Não foi possível rolar até esse trecho. Tente novamente."],
"VFQXPl": [
"A pré-visualização de links externos mostra um cartão com o nome do site, o título da página e a descrição quando você passa o cursor sobre um link."
],
@@ -3428,7 +3431,6 @@
"X2zUS5": ["Excluir este comentário"],
"X3MMeA": ["Nenhum destes problemas tem correção automática."],
"X59Fx2": ["Não foi possível abrir este documento no Slidev."],
- "X7ShnN": ["Abrir o painel de agentes"],
"X8kjQX": ["Autenticar de novo no GitHub"],
"X9VpsP": ["Carregando o conteúdo da pasta"],
"XA9uvc": ["O OpenKnowledge busca e baixa atualizações em segundo plano."],
@@ -3584,6 +3586,7 @@
"YS9mSt": ["\"", ["name"], "\" atualizado a partir de ", ["0"]],
"YSFv5w": ["Sem repositório git — o compartilhamento de configuração não se aplica aqui."],
"YScUUO": ["Busca uma página da web"],
+ "YStFYH": ["Abrir agentes"],
"YTLmTM": ["Excluir a pasta <0>.git</0> acima"],
"YW7Q86": ["As configurações de busca ainda não carregaram — tente de novo em instantes"],
"YWK2zy": ["Diferenças do conflito em ", ["fileName"]],
@@ -3867,6 +3870,7 @@
"Nenhuma ferramenta de IA detectada ainda. Depois de instalar uma, conecte-a em Configurações > Este projeto."
],
"aTDVi6": ["Seu conteúdo foi preservado"],
+ "aV2vel": ["Painel ", ["number"]],
"aWlJai": ["Iniciando o fluxo de login"],
"aXkLuE": ["Resposta de aplicação malformada"],
"a_u4ck": ["Carregando tags"],
@@ -4363,7 +4367,7 @@
"eQkgKV": ["Instalado"],
"eQn7nI": ["Carregando compartilhamento da configuração"],
"eQxm13": ["Falha ao atualizar o local dos anexos — ", ["detail"]],
- "eRSPr9": ["Abrir o terminal"],
+ "eRSPr9": ["Abrir terminal"],
"eTL5y9": ["Mostrar a pré-visualização da seleção"],
"eTsJYJ": ["descrição"],
"eUFXS1": ["Ordenar as habilidades"],
@@ -4443,6 +4447,7 @@
"f1-q9m": ["mantém as habilidades"],
"f14doC": ["Slidev"],
"f1XQyZ": ["Mover o bloco"],
+ "f3YhVJ": ["Nada aberto"],
"f65AOQ": ["Começar a partir de"],
"f6suyZ": ["Alterações solicitadas"],
"f8fH8W": ["Design"],
@@ -4460,6 +4465,7 @@
"fKsRVO": ["Habilidades de ", ["0"], "/", ["1"], "."],
"fMsFdZ": ["Não deu para salvar a configuração de atualização automática: ", ["0"]],
"fNr-MX": ["Desativar a busca semântica"],
+ "fObclJ": ["Voltar ao editor"],
"fOzzSV": ["O destino do link \"", ["shown"], "\" não corresponde a um arquivo existente."],
"fRVBiq": [
"Adiciona telemetria, estado do servidor e informações de execução quando disponíveis. As credenciais são sempre removidas; os nomes de documento, se incluídos, aparecem em texto simples (sem ocultação)."
@@ -4568,7 +4574,6 @@
["descriptorLabel"],
"> (provavelmente uma prop inválida). Copie o código para ver o que deu errado ou exclua o bloco."
],
- "g5V4_P": ["Recolher o painel de agentes"],
"g5w1sF": [
"Escolha uma pasta para mesclar DENTRO de ",
["display"],
@@ -4831,18 +4836,6 @@
"i04BJx": ["Vive fora deste projeto — somente leitura aqui."],
"i09An-": ["Uma versão anterior foi restaurada (", ["0"], ")"],
"i1flq_": ["Sugestões de link wiki"],
- "i25FHa": [
- "Abrir o painel de agentes — ",
- [
- "liveThreadCount",
- "plural",
- {
- "one": ["#", " conversa de agente ativa"],
- "many": ["#", " conversas de agente ativas"],
- "other": ["#", " conversas de agente ativas"]
- }
- ]
- ],
"i3f2kh": ["Nenhum comando corresponde."],
"i6o7XB": ["Pesquisar idiomas"],
"i92eAT": ["Vamos criar um repositório e começar a sincronizar — sem precisar de terminal."],
@@ -5421,6 +5414,7 @@
],
"n7aopT": ["Modo do editor"],
"n81AV0": [["owner"], "/", ["name"], " já existe. Escolha outro nome."],
+ "nBFK5w": ["Redimensionar o terminal"],
"nBHvPL": ["Cancelar edição"],
"nBgzKO": ["Tornar esta a fonte — a pasta real da habilidade se muda para cá"],
"nCzR-G": ["Copiar o código ", ["userCode"]],
@@ -5817,6 +5811,7 @@
"qyLmWw": ["Painel de busca do editor de código"],
"qze9od": ["Esta pasta também é de ", ["alsoAffects"], "."],
"r-OJYm": ["Digite um nome de ramo válido (sem espaços, sem ponto inicial, sem \"..\")."],
+ "r-wzd8": ["Atualizações e comentários"],
"r2eKE3": ["Entre primeiro no ", ["agentName"]],
"r3iaI0": ["Ainda não há chats."],
"r4R7AZ": ["Erro de rede durante a limpeza"],
@@ -6088,6 +6083,7 @@
"ten9en": ["Projeto recente"],
"tfDRzk": ["Salvar"],
"tfi40B": ["Falha ao criar a página"],
+ "tgB_VT": ["Abrir editor"],
"tgWuMB": ["Modificado"],
"thnPBX": ["Ativa a próxima aba do editor."],
"ti6aF_": ["Perguntar à CLI do ", ["0"]],
@@ -6289,6 +6285,7 @@
"un-K1H": ["Fica neste computador. Não vai para o git."],
"un8kBM": ["Criando a página: ", ["linkTitle"], "."],
"uoJF_D": ["Foi difícil demais configurar ou começar"],
+ "uqgCZJ": ["Ocultar o Editor"],
"uqs8Gd": [
[
"others",
@@ -6631,6 +6628,7 @@
"xzAmL_": ["Aprovado automaticamente"],
"xzktOa": ["Editar o link wiki"],
"y-LQPF": ["Não foi possível resolver a imagem ", ["identity"], ". Ir para a referência."],
+ "y0_w13": ["Mostrar o Editor"],
"y1eoq1": ["Copiar link"],
"y1t8bQ": ["Seções das configurações"],
"y3aU20": ["Salvar as alterações"],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 896d5efa8..92e535b53 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -1670,6 +1670,7 @@ msgstr "Ativo"
msgid "Active panel content for the selected tab shows here."
msgstr "O conteúdo do painel ativo da aba selecionada aparece aqui."
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "Atividade"
@@ -1961,6 +1962,10 @@ msgstr "Conexões de agentes"
msgid "Agent mode"
msgstr "Modo agente"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "Painel de agentes"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "O painel de agentes foi fechado para manter o Terminal legível."
@@ -1983,6 +1988,7 @@ msgstr "Transcrição do agente"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "Agentes"
@@ -2179,6 +2185,7 @@ msgstr "Instância do aplicativo: {label}, v{version}"
msgid "Append-only log of what changed."
msgstr "Log somente de acréscimo com o que mudou."
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "Aplicativo"
@@ -2543,6 +2550,10 @@ msgstr "Voltar"
msgid "Back to document view"
msgstr "Voltar para a visualização do documento"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "Voltar ao editor"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "Retrolinks"
@@ -3463,10 +3474,6 @@ msgstr "Recolher"
msgid "Collapse {keyName}"
msgstr "Recolher {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "Recolher o painel de agentes"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3490,10 +3497,6 @@ msgstr "Recolher Perguntar à IA"
msgid "Collapse graph"
msgstr "Recolher o grafo"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Recolher o Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "Bloco de conteúdo recolhível (alternador no estilo Notion)."
@@ -3661,7 +3664,7 @@ msgstr "Configure as opções de usuário, de projeto e de integrações."
msgid "conflict"
msgstr "conflito"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Conflito"
@@ -4300,6 +4303,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "Não deu para duplicar \"{0}\": {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "Não foi possível encontrar esse trecho — o texto em que ele estava pode ter mudado."
@@ -4665,6 +4669,10 @@ msgstr "Não foi possível salvar esta configuração. Tente novamente."
msgid "Couldn't save your theme preference."
msgstr "Não foi possível salvar sua preferência de tema."
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "Não foi possível rolar até esse trecho. Tente novamente."
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "Não deu para enviar o relatório"
@@ -5285,6 +5293,7 @@ msgid "Diff render mode"
msgstr "Modo de exibição das diferenças"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Diferenças indisponíveis"
@@ -5406,6 +5415,10 @@ msgstr "Documento não encontrado"
msgid "Document outline"
msgstr "Estrutura do documento"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "Painel do documento"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "Painéis do documento"
@@ -5729,6 +5742,7 @@ msgstr "Editando {boldName} no lugar. As alterações são salvas direto na cóp
msgid "Editing broken MDX source: {reason}"
msgstr "Editando código MDX quebrado: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "Editor"
@@ -5741,6 +5755,10 @@ msgstr "Modo do editor"
msgid "editor pane"
msgstr "painel do editor"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "Painel do editor"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Seleção do editor"
@@ -6687,6 +6705,7 @@ msgstr "Arquivo: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "Nome do arquivo"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "Arquivos"
@@ -7349,11 +7368,17 @@ msgstr "Ocultar detalhes"
msgid "Hide document panel"
msgstr "Ocultar o painel do documento"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "Ocultar o Editor"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "Ocultar os nós de URL externa"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "Ocultar Arquivos"
@@ -7384,12 +7409,13 @@ msgid "Hide Others"
msgstr "Ocultar os outros"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "Ocultar o painel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "Ocultar o painel ({panelShortcutLabel})"
@@ -9004,11 +9030,11 @@ msgstr "Altere o destino do link, a âncora e o texto exibido."
msgid "More"
msgstr "Mais"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "Mais ações"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "Mais ações ({syncAttentionLabel})"
@@ -10058,6 +10084,10 @@ msgstr "Nada se move até você pedir: use Pull e Push no menu de sincronizaçã
msgid "Nothing moves until you ask."
msgstr "Nada se move até você pedir."
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "Nada aberto"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Ainda não há nada definido."
@@ -10107,7 +10137,7 @@ msgstr "Desligado — os links externos mostram só a URL. Nenhuma requisição
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Desligada — a busca classifica só por palavra-chave. Nenhum conteúdo sai deste computador."
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "Offline"
@@ -10273,13 +10303,9 @@ msgstr "Abrir o painel de atividade de {tooltipName}"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "Abrir o painel de atividade de {tooltipName}, que está editando {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "Abrir o painel de agentes"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "Abrir o painel de agentes — {liveThreadCount, plural, one {# conversa de agente ativa} many {# conversas de agente ativas} other {# conversas de agente ativas}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "Abrir agentes"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10326,6 +10352,10 @@ msgstr "Abre a confirmação de exclusão dos itens selecionados na árvore de a
msgid "Open documents tagged #{chip}"
msgstr "Abrir os documentos com a tag #{chip}"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "Abrir editor"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "Abrir o rascunho de e-mail"
@@ -10497,9 +10527,9 @@ msgstr "Abrir o painel de análise do código"
msgid "Open source: {mirrorSrc}"
msgstr "Abrir a fonte: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
-msgstr "Abrir o terminal"
+msgstr "Abrir terminal"
#: src/components/acp/thread-auth-offer.ts
msgid "Open terminal to sign in"
@@ -11058,6 +11088,14 @@ msgstr "Deslocar para cima"
msgid "pane {0}"
msgstr "painel {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "Painel {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "Painéis"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Parágrafo"
@@ -11466,6 +11504,7 @@ msgstr "projeto"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Projeto"
@@ -11859,7 +11898,7 @@ msgstr "Recomendado"
msgid "Recommended agent skill"
msgstr "Habilidade recomendada do agente"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "É preciso reconectar"
@@ -12448,10 +12487,19 @@ msgstr "Redefinir os filtros de visualização"
msgid "Resize {handleKey}"
msgstr "Redimensionar {handleKey}"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "Redimensionar o painel do documento"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "Redimensionar o painel de Habilidades"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "Redimensionar o terminal"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Resolva o conflito no seu terminal"
@@ -12864,9 +12912,8 @@ msgid "Scroll to start"
msgstr "Rolar até o início"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12876,10 +12923,6 @@ msgstr "Buscar"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "Buscar \"{semanticSubmitQuery}\" por significado"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "Buscar ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "Buscar agentes"
@@ -13545,6 +13588,11 @@ msgstr "Mostrar o diagrama"
msgid "Show document panel"
msgstr "Mostrar o painel do documento"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "Mostrar o Editor"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "Mostrar os nós de URL externa"
@@ -13553,7 +13601,7 @@ msgstr "Mostrar os nós de URL externa"
msgid "Show fewer"
msgstr "Mostrar menos"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "Mostrar Arquivos"
@@ -13610,12 +13658,12 @@ msgid "Show original"
msgstr "Mostrar original"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "Mostrar o painel"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "Mostrar o painel ({panelShortcutLabel})"
@@ -14434,7 +14482,7 @@ msgstr "Modo de sincronização"
msgid "Sync now"
msgstr "Sincronizar agora"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "Sincronização pausada"
@@ -14612,6 +14660,7 @@ msgstr "Modelos disponíveis"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16412,6 +16461,10 @@ msgstr "propriedades da pasta atualizadas"
msgid "Updated to Version {version}"
msgstr "Atualizado para a versão {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "Atualizações e comentários"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "As atualizações chegam sozinhas"
@@ -16985,10 +17038,6 @@ msgstr "Espaço de trabalho"
msgid "Workspace Command Palette"
msgstr "Paleta de comandos do espaço de trabalho"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "Navegação do espaço de trabalho"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 14676839e..414db90d7 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -343,6 +343,7 @@
"3Fcb0I": ["گراف کھولیں"],
"3HAPpl": ["آپ کی تلاش سے کوئی اسکیما مماثل نہیں۔"],
"3HNlwb": ["سلام، دنیا!"],
+ "3HOAcR": ["ایجنٹ پینل"],
"3Ib6FN": ["نیچے لے جائیں"],
"3J7d2N": ["بڑا سیکشن عنوان۔"],
"3JYy1p": ["برانچ ", ["0"], " اب موجود نہیں۔ طے شدہ برانچ پر کلون کر دیا گیا۔"],
@@ -541,6 +542,7 @@
],
"5OTgC7": ["نیچے کا «AI سے پوچھیں» پرامپٹ کمپوزر کھولیں اور اس پر فوکس کریں۔"],
"5OqaJi": ["پروجیکٹ کا نام درج کریں"],
+ "5Q9-G-": ["دستاویز کا پینل"],
"5QGTaA": ["نسبتی راستہ نقل نہیں ہو سکا"],
"5RiC8D": [
"دریافتی اسکلز کا انتظام تمام AI ٹولز کے لیے ایک ساتھ کیا جاتا ہے۔ اسے ترتیبات میں مہارت اسٹوڈیو سے انسٹال کریں۔"
@@ -772,6 +774,7 @@
"7cAW1G": ["اس اینڈ پوائنٹ کے لیے کوئی API کلید مقرر نہیں۔ اوپر ایک شامل کریں۔"],
"7czmD1": ["OpenKnowledge نے تحریری پیلیٹ دیکھا"],
"7d1a0d": ["عوامی"],
+ "7dDoQu": ["ایڈیٹر پین"],
"7dZnmw": ["مطابقت"],
"7hctf2": ["جو پروجیکٹ آپ بنانا چاہتے ہیں اسے بیان کریں"],
"7idx48": ["OKF ایجنٹ کی مہارت انسٹال ہوگئی"],
@@ -1280,7 +1283,6 @@
"DWJtEo": ["آگے کیا ہو گا"],
"DXd9LM": ["نیا ورک ٹری"],
"D_WKe_": ["کسی ایجنٹ کا سیشن دیکھنے کے لیے موجودگی بار میں اس کے اوتار پر کلک کریں۔"],
- "DbCfXV": ["تلاش (", ["searchShortcutLabel"], ")"],
"DbILZA": [
"کوئی مماثلت نہیں۔ کچھ فائلیں تلاش سے خارج ہیں (چھپی ہوئی یا نظر انداز شدہ فائلیں)۔"
],
@@ -1500,6 +1502,7 @@
")۔"
],
"FWSjnp": ["سورس پین اور کوڈ خصوصیت کے فیلڈز میں ترمیم"],
+ "FYy2EN": ["دستاویز کے پینل کا سائز تبدیل کریں"],
"FZtBeR": [["0"], " فعال کریں"],
"FeXcUS": [
["display"],
@@ -1561,6 +1564,7 @@
" درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
],
"GBQjiV": ["مہارت شامل کریں"],
+ "GCrhIF": ["پینلز"],
"GDvlUT": ["کردار"],
"GEyl32": ["ٹرمینل شروع ہو رہا ہے…"],
"GGsM4y": ["گراف میں منتخب"],
@@ -2124,7 +2128,6 @@
"سِم لنک اپنا الگ فولڈر ہونے کے بجائے ماخذ فولڈر کی طرف اشارہ ہوتا ہے۔ ہر مقام بالکل وہی بائٹس پڑھتا ہے، اس لیے کچھ بھی الگ نہیں ہو سکتا، اور اگر ماخذ حذف ہو جائے تو وہ مقام کام کرنا بند کر دیتا ہے۔"
],
"MTs6g3": ["سرور دوبارہ چلنے کے بعد دوبارہ منسلک نہیں ہو سکا"],
- "MU_NVW": ["Terminal سمیٹیں"],
"MUrVEo": ["کوئی حالیہ پروجیکٹ نہیں۔"],
"MV-Dkb": [["countDisplay"], " Markdown فائلیں ملیں"],
"MVxpbf": ["تلاش اور تبدیلی"],
@@ -2912,13 +2915,13 @@
"</0> مقامی طور پر حذف کی، مگر اپ سٹریم اس میں ترمیم ہوئی۔"
],
"V4JHny": ["شیئرنگ صرف GitHub ریموٹس کے ساتھ کام کرتی ہے۔"],
- "V6AIOn": ["ورک اسپیس کی نیویگیشن"],
"V6e25h": ["تھیم کا پیش منظر"],
"V7QxyT": ["کنکشن منقطع ہو گیا"],
"VAHWL_": ["<0>@", ["signedInLogin"], "</0> کے طور پر منسلک"],
"VBE2dw": [
"اپنی کہانی کے پس منظر کی دنیا بنائیں اور اس کا حساب رکھیں۔ آپ کے کرداروں، مقامات، دھڑوں اور انہیں باہم جوڑنے والی روایات کا ٹھکانہ، تاکہ لکھتے وقت تفصیلات ہم آہنگ رہیں۔"
],
+ "VBtCdv": ["اس اقتباس تک اسکرول نہیں ہو سکا۔ دوبارہ کوشش کریں۔"],
"VFQXPl": [
"بیرونی لنکس کے پیش منظر لنک پر ماؤس لے جانے پر سائٹ کا نام، صفحے کا عنوان اور تفصیل والا کارڈ دکھاتے ہیں۔"
],
@@ -3063,7 +3066,6 @@
"X2zUS5": ["یہ تبصرہ حذف کریں"],
"X3MMeA": ["ان میں سے کسی مسئلے کا خودکار حل نہیں ہے۔"],
"X59Fx2": ["یہ دستاویز Slidev میں نہیں کھولی جا سکی۔"],
- "X7ShnN": ["ایجنٹس کا پینل کھولیں"],
"X8kjQX": ["GitHub سے دوبارہ توثیق کریں"],
"X9VpsP": ["فولڈر کا مواد لوڈ ہو رہا ہے"],
"XA9uvc": ["OpenKnowledge پس منظر میں اپ ڈیٹس دیکھتا اور ڈاؤن لوڈ کرتا ہے۔"],
@@ -3208,6 +3210,7 @@
"YS9mSt": ["«", ["name"], "» ", ["0"], " سے تازہ ہوا"],
"YSFv5w": ["کوئی git ریپازٹری نہیں — کنفیگ کا اشتراک یہاں لاگو نہیں ہوتا۔"],
"YScUUO": ["ایک ویب صفحہ لاتا ہے"],
+ "YStFYH": ["ایجنٹس کھولیں"],
"YTLmTM": ["والد <0>.git</0> فولڈر ہٹائیں"],
"YW7Q86": ["تلاش کی ترتیبات ابھی لوڈ نہیں ہوئیں — تھوڑی دیر بعد دوبارہ کوشش کریں"],
"YWK2zy": [["fileName"], " کے لیے کنفلکٹ ڈِف"],
@@ -3489,6 +3492,7 @@
"ابھی تک کوئی AI ٹول نہیں ملا۔ ایک انسٹال کرنے کے بعد اسے ترتیبات > یہ پروجیکٹ سے جوڑیں۔"
],
"aTDVi6": ["آپ کا مواد محفوظ رکھا گیا"],
+ "aV2vel": ["پین ", ["number"]],
"aWlJai": ["سائن اِن کا عمل شروع کیا جا رہا ہے"],
"aXkLuE": ["اپلائی کا جواب بگڑا ہوا ہے"],
"a_u4ck": ["ٹیگز لوڈ ہو رہے ہیں"],
@@ -3986,6 +3990,7 @@
"f1-q9m": ["مہارتیں اپنے پاس رکھتا ہے"],
"f14doC": ["Slidev"],
"f1XQyZ": ["بلاک منتقل کریں"],
+ "f3YhVJ": ["کچھ بھی کھلا نہیں"],
"f65AOQ": ["یہاں سے شروع کریں"],
"f6suyZ": ["تبدیلیوں کی درخواست کی گئی"],
"f8fH8W": ["ڈیزائن"],
@@ -4003,6 +4008,7 @@
"fKsRVO": [["0"], "/", ["1"], " سے مہارتیں۔"],
"fMsFdZ": ["خودکار اپ ڈیٹ کی ترتیب محفوظ نہیں ہو سکی: ", ["0"]],
"fNr-MX": ["معنوی تلاش بند کریں"],
+ "fObclJ": ["ایڈیٹر پر واپس"],
"fOzzSV": ["لنک کا ہدف \"", ["shown"], "\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"],
"fRVBiq": [
"دستیاب ہونے پر ٹیلی میٹری، سرور کی حالت اور رن ٹائم معلومات شامل کرتا ہے۔ اسناد ہمیشہ ہٹا دی جاتی ہیں؛ دستاویزات کے نام، اگر شامل ہوں، سادہ متن میں ظاہر ہوتے ہیں (چھپائے نہیں جاتے)۔"
@@ -4083,7 +4089,6 @@
["descriptorLabel"],
"> رینڈر نہیں ہو سکا (غالباً کوئی غلط پراپ)۔ خرابی دیکھنے کے لیے سورس کاپی کریں، یا بلاک حذف کر دیں۔"
],
- "g5V4_P": ["ایجنٹ پینل سمیٹیں"],
"g5w1sF": [
["display"],
" میں ضم کرنے کے لیے کوئی فولڈر منتخب کریں۔ وہ فولڈر اس کا سِم لنک بن جاتا ہے، اس لیے اس کا ایجنٹ یہاں رکھی ہر چیز پڑھتا ہے۔ یہ فولڈر حقیقی رہتا ہے۔ متصادم مہارتیں ضم کرنے کا عمل روک دیتی ہیں۔"
@@ -4323,14 +4328,6 @@
"i04BJx": ["اس پروجیکٹ سے باہر ہے — یہاں صرف پڑھنے کے لیے۔"],
"i09An-": ["ایک پرانا ورژن بحال کر دیا گیا (", ["0"], ")"],
"i1flq_": ["وکی لنک کی تجاویز"],
- "i25FHa": [
- "ایجنٹس کا پینل کھولیں — ",
- [
- "liveThreadCount",
- "plural",
- { "one": ["#", " فعال ایجنٹ تھریڈ"], "other": ["#", " فعال ایجنٹ تھریڈ"] }
- ]
- ],
"i3f2kh": ["کوئی مماثل کمانڈ نہیں۔"],
"i6o7XB": ["زبانیں تلاش کریں"],
"i92eAT": ["ہم ایک ریپازٹری بنا کر مطابقت پذیری شروع کر دیں گے — کسی ٹرمینل کی ضرورت نہیں۔"],
@@ -4882,6 +4879,7 @@
],
"n7aopT": ["ایڈیٹر موڈ"],
"n81AV0": [["owner"], "/", ["name"], " پہلے سے موجود ہے۔ کوئی اور نام منتخب کریں۔"],
+ "nBFK5w": ["ٹرمینل کا سائز تبدیل کریں"],
"nBHvPL": ["ترمیم منسوخ کریں"],
"nBgzKO": ["اسے ماخذ بنائیں — مہارت کا اصل فولڈر یہاں منتقل ہو جائے گا"],
"nCzR-G": ["کوڈ ", ["userCode"], " نقل کریں"],
@@ -5229,6 +5227,7 @@
"qyLmWw": ["سورس ایڈیٹر کا تلاش پینل"],
"qze9od": ["یہ فولڈر ", ["alsoAffects"], " کا بھی ہے۔"],
"r-OJYm": ["برانچ کا درست نام درج کریں (کوئی خالی جگہ نہیں، شروع میں نقطہ نہیں، «..» نہیں)۔"],
+ "r-wzd8": ["اپ ڈیٹس اور رائے"],
"r2eKE3": ["پہلے ", ["agentName"], " میں سائن اِن کریں"],
"r3iaI0": ["ابھی کوئی چیٹ نہیں۔"],
"r4R7AZ": ["صفائی کے دوران نیٹ ورک کی خرابی"],
@@ -5477,6 +5476,7 @@
"ten9en": ["حالیہ پروجیکٹ"],
"tfDRzk": ["محفوظ کریں"],
"tfi40B": ["صفحہ نہیں بن سکا"],
+ "tgB_VT": ["ایڈیٹر کھولیں"],
"tgWuMB": ["ترمیم شدہ"],
"thnPBX": ["ایڈیٹر کا اگلا ٹیب فعال کریں۔"],
"ti6aF_": [["0"], " CLI سے پوچھیں"],
@@ -5652,6 +5652,7 @@
"un-K1H": ["اسی کمپیوٹر پر رہتا ہے۔ git میں کمٹ نہیں ہوتا۔"],
"un8kBM": ["صفحہ بنایا جا رہا ہے: ", ["linkTitle"], "۔"],
"uoJF_D": ["اسے ترتیب دینا یا شروع کرنا بہت مشکل تھا"],
+ "uqgCZJ": ["ایڈیٹر چھپائیں"],
"uqs8Gd": [["others", "plural", { "one": ["#", " دیگر"], "other": ["#", " دیگر"] }]],
"ur2XSb": ["بصری ایڈیٹر"],
"uraHF0": ["GitLab"],
@@ -5965,6 +5966,7 @@
"xzAmL_": ["خودکار منظور شدہ"],
"xzktOa": ["وکی لنک میں ترمیم کریں"],
"y-LQPF": ["ناقابلِ حل تصویر ", ["identity"], "۔ حوالہ پر جائیں۔"],
+ "y0_w13": ["ایڈیٹر دکھائیں"],
"y1eoq1": ["لنک کاپی کریں"],
"y1t8bQ": ["ترتیبات کے سیکشنز"],
"y3aU20": ["تبدیلیاں محفوظ کریں"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 77c82d2b5..3be22c8ed 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -1674,6 +1674,7 @@ msgstr "فعال"
msgid "Active panel content for the selected tab shows here."
msgstr "منتخب ٹیب کے فعال پینل کا مواد یہاں دکھایا جاتا ہے۔"
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "سرگرمی"
@@ -1965,6 +1966,10 @@ msgstr "ایجنٹ کنکشنز"
msgid "Agent mode"
msgstr "ایجنٹ موڈ"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "ایجنٹ پینل"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "Terminal کو پڑھنے کے قابل رکھنے کے لیے ایجنٹ پینل بند کر دیا گیا۔"
@@ -1987,6 +1992,7 @@ msgstr "ایجنٹ کا ٹرانسکرپٹ"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "ایجنٹس"
@@ -2183,6 +2189,7 @@ msgstr "ایپ انسٹینس: {label}، v{version}"
msgid "Append-only log of what changed."
msgstr "کیا بدلا اس کا صرف اضافے والا لاگ۔"
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "ایپلیکیشن"
@@ -2547,6 +2554,10 @@ msgstr "واپس"
msgid "Back to document view"
msgstr "دستاویز کے منظر پر واپس"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "ایڈیٹر پر واپس"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "بیک لنکس"
@@ -3467,10 +3478,6 @@ msgstr "سکیڑیں"
msgid "Collapse {keyName}"
msgstr "{keyName} سکیڑیں"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "ایجنٹ پینل سمیٹیں"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "«AI سے پوچھیں» سکیڑیں"
msgid "Collapse graph"
msgstr "گراف سکیڑیں"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "Terminal سمیٹیں"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "سکڑنے والا مواد بلاک (Notion طرز کا ٹوگل)۔"
@@ -3665,7 +3668,7 @@ msgstr "صارف، پروجیکٹ اور انضمام کی ترتیبات مقر
msgid "conflict"
msgstr "تصادم"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "تصادم"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "«{0}» کی نقل نہیں بن سکی: {1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "وہ اقتباس نہیں مل سکا — جس متن پر یہ تھا وہ شاید تبدیل ہو چکا ہے۔"
@@ -4669,6 +4673,10 @@ msgstr "یہ ترتیب محفوظ نہیں ہو سکی۔ دوبارہ کوشش
msgid "Couldn't save your theme preference."
msgstr "آپ کی تھیم ترجیح محفوظ نہیں ہو سکی۔"
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "اس اقتباس تک اسکرول نہیں ہو سکا۔ دوبارہ کوشش کریں۔"
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "رپورٹ نہیں بھیجی جا سکی"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "فرق کے رینڈر کا موڈ"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "فرق دستیاب نہیں"
@@ -5410,6 +5419,10 @@ msgstr "دستاویز نہیں ملی"
msgid "Document outline"
msgstr "دستاویز کا خاکہ"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "دستاویز کا پینل"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "دستاویز کے پینلز"
@@ -5733,6 +5746,7 @@ msgstr "{boldName} میں اسی جگہ ترمیم ہو رہی ہے۔ تبدیل
msgid "Editing broken MDX source: {reason}"
msgstr "ٹوٹے ہوئے MDX سورس میں ترمیم: {reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "ایڈیٹر"
@@ -5745,6 +5759,10 @@ msgstr "ایڈیٹر موڈ"
msgid "editor pane"
msgstr "ایڈیٹر پین"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "ایڈیٹر پین"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "ایڈیٹر کا انتخاب"
@@ -6691,6 +6709,7 @@ msgstr "فائل: <0>{fixedName}.md</0>"
msgid "Filename"
msgstr "فائل کا نام"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "فائلیں"
@@ -7353,11 +7372,17 @@ msgstr "تفصیلات چھپائیں"
msgid "Hide document panel"
msgstr "دستاویز کا پینل چھپائیں"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "ایڈیٹر چھپائیں"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "بیرونی URL نوڈز چھپائیں"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "فائلیں چھپائیں"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "دیگر چھپائیں"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "پینل چھپائیں"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "پینل چھپائیں ({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "لنک کا ہدف، اینکر اور ظاہری لیبل تبدیل ک
msgid "More"
msgstr "مزید"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "مزید اعمال"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "مزید اعمال ({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "جب تک آپ نہ کہیں، کچھ نہیں چلے گا — مطاب
msgid "Nothing moves until you ask."
msgstr "جب تک آپ نہ کہیں، کچھ نہیں چلے گا۔"
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "کچھ بھی کھلا نہیں"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "ابھی کچھ مقرر نہیں۔"
@@ -10111,7 +10141,7 @@ msgstr "بند — بیرونی لنکس صرف اپنا URL دکھاتے ہیں
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "بند — تلاش صرف کلیدی الفاظ سے درجہ بندی کرتی ہے۔ کوئی مواد اس کمپیوٹر سے باہر نہیں جاتا۔"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "آف لائن"
@@ -10277,13 +10307,9 @@ msgstr "{tooltipName} کے لیے سرگرمی کا پینل کھولیں"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "{tooltipName} کے لیے سرگرمی کا پینل کھولیں، {realCurrentDoc} میں ترمیم کر رہا ہے"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "ایجنٹس کا پینل کھولیں"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "ایجنٹس کا پینل کھولیں — {liveThreadCount, plural, one {# فعال ایجنٹ تھریڈ} other {# فعال ایجنٹ تھریڈ}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "ایجنٹس کھولیں"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "منتخب فائل ٹری آئٹمز کے لیے حذف کی تصدیق
msgid "Open documents tagged #{chip}"
msgstr "#{chip} سے ٹیگ شدہ دستاویزات کھولیں"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "ایڈیٹر کھولیں"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "ای میل کا مسودہ کھولیں"
@@ -10501,7 +10531,7 @@ msgstr "سورس لِنٹ پینل کھولیں"
msgid "Open source: {mirrorSrc}"
msgstr "ماخذ کھولیں: {mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "ٹرمینل کھولیں"
@@ -11062,6 +11092,14 @@ msgstr "اوپر کھسکائیں"
msgid "pane {0}"
msgstr "پین {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "پین {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "پینلز"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "پیراگراف"
@@ -11470,6 +11508,7 @@ msgstr "پروجیکٹ"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "پروجیکٹ"
@@ -11863,7 +11902,7 @@ msgstr "تجویز کردہ"
msgid "Recommended agent skill"
msgstr "تجویز کردہ ایجنٹ کی مہارت"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "دوبارہ منسلک ہونا ضروری ہے"
@@ -12452,10 +12491,19 @@ msgstr "منظر کے فلٹرز دوبارہ ترتیب دیں"
msgid "Resize {handleKey}"
msgstr "{handleKey} کا حجم بدلیں"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "دستاویز کے پینل کا سائز تبدیل کریں"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "مہارتوں کے پینل کا سائز تبدیل کریں"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "ٹرمینل کا سائز تبدیل کریں"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "اپنے ٹرمینل میں تصادم حل کریں"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "شروع تک سکرول کریں"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "تلاش"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "«{semanticSubmitQuery}» کو معنی کے لحاظ سے تلاش کریں"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "تلاش ({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "ایجنٹس تلاش کریں"
@@ -13549,6 +13592,11 @@ msgstr "خاکہ دکھائیں"
msgid "Show document panel"
msgstr "دستاویز کا پینل دکھائیں"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "ایڈیٹر دکھائیں"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "بیرونی URL نوڈز دکھائیں"
@@ -13557,7 +13605,7 @@ msgstr "بیرونی URL نوڈز دکھائیں"
msgid "Show fewer"
msgstr "کم دکھائیں"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "فائلیں دکھائیں"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "اصل دکھائیں"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "پینل دکھائیں"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "پینل دکھائیں ({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "مطابقت پذیری کا موڈ"
msgid "Sync now"
msgstr "ابھی مطابق کریں"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "مطابقت پذیری روکی ہوئی"
@@ -14616,6 +14664,7 @@ msgstr "دستیاب ٹیمپلیٹس"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "فولڈر کی خصوصیات تازہ کیں"
msgid "Updated to Version {version}"
msgstr "ورژن {version} پر تازہ ہو گیا"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "اپ ڈیٹس اور رائے"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "اپ ڈیٹس آتی رہتی ہیں"
@@ -16989,10 +17042,6 @@ msgstr "ورک اسپیس"
msgid "Workspace Command Palette"
msgstr "ورک اسپیس کمانڈ پیلیٹ"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "ورک اسپیس کی نیویگیشن"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index a7807432e..2480c6133 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -305,6 +305,7 @@
"3Fcb0I": ["打开关系图"],
"3HAPpl": ["没有架构匹配你的搜索。"],
"3HNlwb": ["你好,世界!"],
+ "3HOAcR": ["智能体面板"],
"3Ib6FN": ["下移"],
"3J7d2N": ["大号章节标题。"],
"3JYy1p": ["分支 ", ["0"], " 已不存在,已克隆到默认分支。"],
@@ -472,6 +473,7 @@
],
"5OTgC7": ["打开并聚焦底部的「问 AI」提示词输入框。"],
"5OqaJi": ["请输入项目名"],
+ "5Q9-G-": ["文档面板"],
"5QGTaA": ["无法复制相对路径"],
"5RiC8D": ["发现技能由所有 AI 工具统一管理。请从“设置”→“技能工作室”安装此技能。"],
"5SwVv1": ["未安装"],
@@ -664,6 +666,7 @@
"7cAW1G": ["这个端点还没有设置 API 密钥。请在上方添加一个。"],
"7czmD1": ["OpenKnowledge 查看了创作面板"],
"7d1a0d": ["公开"],
+ "7dDoQu": ["编辑器窗格"],
"7dZnmw": ["相关度"],
"7hctf2": ["描述你想创建的项目"],
"7idx48": ["OKF 代理技能已安装"],
@@ -1109,7 +1112,6 @@
"DWJtEo": ["接下来会怎样"],
"DXd9LM": ["新建 worktree"],
"D_WKe_": ["在在线状态栏中点击某个智能体的头像即可查看它的会话。"],
- "DbCfXV": ["搜索(", ["searchShortcutLabel"], ")"],
"DbILZA": ["没有匹配项。部分文件不参与搜索(隐藏或被忽略的文件)。"],
"DcFr-y": ["OpenKnowledge 删除了一个文档"],
"DcH8-w": ["将 ", ["0"], " 个技能移至项目"],
@@ -1294,6 +1296,7 @@
"FUMerq": ["无法启用同步:", ["detail"]],
"FWQuPE": ["这个项目运行的 OpenKnowledge 版本与这个应用(v", ["0"], ")不同且不兼容。"],
"FWSjnp": ["编辑源码面板和代码类属性字段"],
+ "FYy2EN": ["调整文档面板大小"],
"FZtBeR": ["启用 ", ["0"]],
"FeXcUS": [
["display"],
@@ -1342,6 +1345,7 @@
"GAohqx": ["删除列"],
"GBEqoP": ["你的 Git 配置中指定了 ", ["declaredLogin"], ",但无法使用该账户的凭据。"],
"GBQjiV": ["添加技能"],
+ "GCrhIF": ["面板"],
"GDvlUT": ["角色"],
"GEyl32": ["正在启动终端…"],
"GGsM4y": ["在关系图中已选中"],
@@ -1800,7 +1804,6 @@
"符号链接是指向来源文件夹的指针,而不是独立的文件夹。每个位置读取的都是完全相同的字节,因此不会产生偏差;来源一旦被删除,该位置就会失效。"
],
"MTs6g3": ["服务器重启后无法重新连接"],
- "MU_NVW": ["收起 Terminal"],
"MUrVEo": ["没有最近的项目。"],
"MV-Dkb": ["找到 ", ["countDisplay"], " 个 markdown 文件"],
"MVxpbf": ["查找并替换"],
@@ -2492,13 +2495,13 @@
],
"V48OUT": ["你在本地删除了 <0>", ["filePath"], "</0>,但它在上游被修改过。"],
"V4JHny": ["共享仅支持 GitHub 远程仓库。"],
- "V6AIOn": ["工作区导航"],
"V6e25h": ["主题预览"],
"V7QxyT": ["连接已断开"],
"VAHWL_": ["已以 <0>@", ["signedInLogin"], "</0> 身份连接"],
"VBE2dw": [
"构建并梳理你故事背后的世界。一个安放角色、地点、势力以及把它们串联起来的设定的地方,让细节在写作过程中始终自洽。"
],
+ "VBtCdv": ["无法滚动到该段落。请重试。"],
"VFQXPl": ["开启后,把鼠标悬停在链接上会显示一张卡片,包含站点名称、页面标题和描述。"],
"VIrNh0": ["部分编辑尚未到达服务器,因此没有重新加载标签页。你的编辑仍然保留在这里。"],
"VJaBca": ["选择技能文件夹"],
@@ -2626,7 +2629,6 @@
"X2zUS5": ["删除这条评论"],
"X3MMeA": ["这些问题都没有自动修复方案。"],
"X59Fx2": ["无法在 Slidev 中打开此文档。"],
- "X7ShnN": ["打开智能体面板"],
"X8kjQX": ["重新通过 GitHub 认证"],
"X9VpsP": ["正在加载文件夹内容"],
"XA9uvc": ["OpenKnowledge 会在后台检查并下载更新。"],
@@ -2754,6 +2756,7 @@
"YS9mSt": ["已从 ", ["0"], " 更新“", ["name"], "”"],
"YSFv5w": ["没有 git 仓库——配置共享在这里不适用。"],
"YScUUO": ["获取网页"],
+ "YStFYH": ["打开智能体"],
"YTLmTM": ["删除上层的 <0>.git</0> 文件夹"],
"YW7Q86": ["搜索设置尚未加载——请稍后再试"],
"YWK2zy": [["fileName"], " 的冲突差异"],
@@ -2997,6 +3000,7 @@
"aS77on": ["会更改什么?"],
"aSVmqV": ["尚未检测到 AI 工具。安装之后,可在「设置 > 本项目」中连接。"],
"aTDVi6": ["已保留你的内容"],
+ "aV2vel": ["窗格 ", ["number"]],
"aWlJai": ["正在启动登录流程"],
"aXkLuE": ["应用响应格式错误"],
"a_u4ck": ["正在加载标签"],
@@ -3395,6 +3399,7 @@
"f1-q9m": ["保留这些技能"],
"f14doC": ["Slidev"],
"f1XQyZ": ["移动块"],
+ "f3YhVJ": ["没有打开的面板"],
"f65AOQ": ["起始于"],
"f6suyZ": ["已请求更改"],
"f8fH8W": ["设计"],
@@ -3412,6 +3417,7 @@
"fKsRVO": ["来自 ", ["0"], "/", ["1"], " 的技能。"],
"fMsFdZ": ["无法保存自动更新设置:", ["0"]],
"fNr-MX": ["关闭语义搜索"],
+ "fObclJ": ["返回编辑器"],
"fOzzSV": ["链接目标“", ["shown"], "”未指向现有文件。"],
"fRVBiq": [
"在可用时附上遥测数据、服务器状态和运行时信息。凭据始终会被移除;如果包含文档名,它们会以明文出现(不做隐去)。"
@@ -3477,7 +3483,6 @@
["descriptorLabel"],
"> 渲染失败(很可能是属性有误)。复制源码看看哪里出了问题,或删除这个块。"
],
- "g5V4_P": ["收起智能体面板"],
"g5w1sF": [
"选择一个文件夹,把它合并进 ",
["display"],
@@ -3692,10 +3697,6 @@
"i04BJx": ["位于此项目之外 — 在这里只读。"],
"i09An-": ["已恢复到较早的版本(", ["0"], ")"],
"i1flq_": ["维基链接建议"],
- "i25FHa": [
- "打开智能体面板 — ",
- ["liveThreadCount", "plural", { "other": ["#", " 个进行中的智能体线程"] }]
- ],
"i3f2kh": ["没有匹配的命令。"],
"i6o7XB": ["搜索语言"],
"i92eAT": ["我们会创建一个仓库并开始同步——不需要用终端。"],
@@ -4163,6 +4164,7 @@
],
"n7aopT": ["编辑器模式"],
"n81AV0": [["owner"], "/", ["name"], " 已存在。请换一个名称。"],
+ "nBFK5w": ["调整终端大小"],
"nBHvPL": ["取消编辑"],
"nBgzKO": ["把这里设为来源——技能的真实文件夹会移到这里"],
"nCzR-G": ["复制验证码 ", ["userCode"]],
@@ -4462,6 +4464,7 @@
"qyLmWw": ["源码编辑器搜索面板"],
"qze9od": ["此文件夹同时也属于 ", ["alsoAffects"], "。"],
"r-OJYm": ["请输入有效的分支名(不能有空格、不能以点开头、不能包含 \"..\")。"],
+ "r-wzd8": ["更新与反馈"],
"r2eKE3": ["请先登录 ", ["agentName"]],
"r3iaI0": ["还没有聊天。"],
"r4R7AZ": ["清理过程中出现网络错误"],
@@ -4678,6 +4681,7 @@
"ten9en": ["最近的项目"],
"tfDRzk": ["保存"],
"tfi40B": ["创建页面失败"],
+ "tgB_VT": ["打开编辑器"],
"tgWuMB": ["已修改"],
"thnPBX": ["激活编辑器的下一个标签页。"],
"ti6aF_": ["询问 ", ["0"], " CLI"],
@@ -4822,6 +4826,7 @@
"un-K1H": ["留在这台电脑上。不会提交到 git。"],
"un8kBM": ["正在创建页面:", ["linkTitle"], "。"],
"uoJF_D": ["设置或上手太麻烦了"],
+ "uqgCZJ": ["隐藏编辑器"],
"uqs8Gd": [["others", "plural", { "other": ["其他 ", "#", " 个文件"] }]],
"ur2XSb": ["可视化编辑器"],
"uraHF0": ["GitLab"],
@@ -5085,6 +5090,7 @@
"xzAmL_": ["已自动批准"],
"xzktOa": ["编辑维基链接"],
"y-LQPF": ["无法解析图片 ", ["identity"], "。转到引用位置。"],
+ "y0_w13": ["显示编辑器"],
"y1eoq1": ["复制链接"],
"y1t8bQ": ["设置分区"],
"y3aU20": ["保存更改"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index cffc2a9ac..8d1e891a9 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -1674,6 +1674,7 @@ msgstr "活跃"
msgid "Active panel content for the selected tab shows here."
msgstr "所选标签页的活动面板内容显示在这里。"
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "动态"
@@ -1965,6 +1966,10 @@ msgstr "智能体连接"
msgid "Agent mode"
msgstr "智能体模式"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "智能体面板"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "为保持 Terminal 清晰可读,已关闭智能体面板。"
@@ -1987,6 +1992,7 @@ msgstr "智能体记录"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "智能体"
@@ -2183,6 +2189,7 @@ msgstr "应用实例:{label},v{version}"
msgid "Append-only log of what changed."
msgstr "记录改动内容的只追加日志。"
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "应用程序"
@@ -2547,6 +2554,10 @@ msgstr "返回"
msgid "Back to document view"
msgstr "返回文档视图"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "返回编辑器"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "反向链接"
@@ -3467,10 +3478,6 @@ msgstr "折叠"
msgid "Collapse {keyName}"
msgstr "折叠 {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "收起智能体面板"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "折叠「问 AI」"
msgid "Collapse graph"
msgstr "折叠关系图"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "收起 Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "可折叠内容块(Notion 风格折叠)。"
@@ -3665,7 +3668,7 @@ msgstr "配置用户、项目和集成相关的设置。"
msgid "conflict"
msgstr "冲突"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "冲突"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "无法复制 \"{0}\":{1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "找不到该段落 — 它所在的文本可能已更改。"
@@ -4669,6 +4673,10 @@ msgstr "无法保存此设置。请重试。"
msgid "Couldn't save your theme preference."
msgstr "无法保存你的主题偏好。"
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "无法滚动到该段落。请重试。"
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "无法发送报告"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "差异渲染模式"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "无法显示差异"
@@ -5410,6 +5419,10 @@ msgstr "找不到文档"
msgid "Document outline"
msgstr "文档大纲"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "文档面板"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "文档面板"
@@ -5733,6 +5746,7 @@ msgstr "正在就地编辑 {boldName}。更改会直接保存到你编辑器中
msgid "Editing broken MDX source: {reason}"
msgstr "正在编辑损坏的 MDX 源码:{reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "编辑器"
@@ -5745,6 +5759,10 @@ msgstr "编辑器模式"
msgid "editor pane"
msgstr "编辑器窗格"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "编辑器窗格"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "编辑器选区"
@@ -6691,6 +6709,7 @@ msgstr "文件:<0>{fixedName}.md</0>"
msgid "Filename"
msgstr "文件名"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "文件"
@@ -7353,11 +7372,17 @@ msgstr "隐藏详情"
msgid "Hide document panel"
msgstr "隐藏文档面板"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "隐藏编辑器"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "隐藏外部 URL 节点"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "隐藏「文件」"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "隐藏其他"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "隐藏面板"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "隐藏面板({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "修改链接目标、锚点和显示标签。"
msgid "More"
msgstr "更多"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "更多操作"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "更多操作({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "在你发起操作之前不会有任何变动——请在同步菜单中
msgid "Nothing moves until you ask."
msgstr "在你发起操作之前不会有任何变动。"
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "没有打开的面板"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "还没有设置任何内容。"
@@ -10111,7 +10141,7 @@ msgstr "关闭——外部链接只显示 URL。不会有任何请求离开这
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "关闭——搜索仅按关键词排序。不会有任何内容离开这台电脑。"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "离线"
@@ -10277,13 +10307,9 @@ msgstr "打开 {tooltipName} 的活动面板"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "打开 {tooltipName} 的活动面板,它正在编辑 {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "打开智能体面板"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "打开智能体面板 — {liveThreadCount, plural, other {# 个进行中的智能体线程}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "打开智能体"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "为选中的文件树项目打开删除确认框。"
msgid "Open documents tagged #{chip}"
msgstr "打开带 #{chip} 标签的文档"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "打开编辑器"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "打开邮件草稿"
@@ -10501,7 +10531,7 @@ msgstr "打开源码检查面板"
msgid "Open source: {mirrorSrc}"
msgstr "来源:{mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "打开终端"
@@ -11062,6 +11092,14 @@ msgstr "向上平移"
msgid "pane {0}"
msgstr "窗格 {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "窗格 {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "面板"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "段落"
@@ -11470,6 +11508,7 @@ msgstr "项目"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "项目"
@@ -11863,7 +11902,7 @@ msgstr "推荐"
msgid "Recommended agent skill"
msgstr "推荐代理技能"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "需要重新连接"
@@ -12452,10 +12491,19 @@ msgstr "重置视图筛选条件"
msgid "Resize {handleKey}"
msgstr "调整 {handleKey} 的大小"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "调整文档面板大小"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "调整「技能」面板大小"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "调整终端大小"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "在你的终端中解决冲突"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "滚动到开头"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "搜索"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "按语义搜索 \"{semanticSubmitQuery}\""
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "搜索({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "搜索智能体"
@@ -13549,6 +13592,11 @@ msgstr "显示图示"
msgid "Show document panel"
msgstr "显示文档面板"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "显示编辑器"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "显示外部 URL 节点"
@@ -13557,7 +13605,7 @@ msgstr "显示外部 URL 节点"
msgid "Show fewer"
msgstr "显示更少"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "显示「文件」"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "显示原始版本"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "显示面板"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "显示面板({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "同步模式"
msgid "Sync now"
msgstr "立即同步"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "同步已暂停"
@@ -14616,6 +14664,7 @@ msgstr "可用模板"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "已更新文件夹属性"
msgid "Updated to Version {version}"
msgstr "已更新到版本 {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "更新与反馈"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "更新会自动流入"
@@ -16989,10 +17042,6 @@ msgstr "工作区"
msgid "Workspace Command Palette"
msgstr "工作区命令面板"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "工作区导航"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 4448d022a..9190e8dbb 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -307,6 +307,7 @@
"3Fcb0I": ["開啟關係圖"],
"3HAPpl": ["沒有結構描述符合你的搜尋。"],
"3HNlwb": ["你好,世界!"],
+ "3HOAcR": ["智慧代理面板"],
"3Ib6FN": ["下移"],
"3J7d2N": ["大型章節標題。"],
"3JYy1p": ["分支 ", ["0"], " 已不存在,已改為複製預設分支。"],
@@ -474,6 +475,7 @@
],
"5OTgC7": ["開啟並聚焦底部的「問 AI」提示輸入框。"],
"5OqaJi": ["請輸入專案名稱"],
+ "5Q9-G-": ["文件面板"],
"5QGTaA": ["無法複製相對路徑"],
"5RiC8D": ["探索技能由所有 AI 工具統一管理。請從「設定」→「技能工作室」安裝此技能。"],
"5SwVv1": ["未安裝"],
@@ -664,6 +666,7 @@
"7cAW1G": ["這個端點還沒有設定 API 金鑰。請在上面加一個。"],
"7czmD1": ["OpenKnowledge 查看了創作面板"],
"7d1a0d": ["公開"],
+ "7dDoQu": ["編輯器窗格"],
"7dZnmw": ["相關度"],
"7hctf2": ["描述你想建立的專案"],
"7idx48": ["OKF 代理程式技能已安裝"],
@@ -1111,7 +1114,6 @@
"DWJtEo": ["接下來會怎樣"],
"DXd9LM": ["新增 worktree"],
"D_WKe_": ["在協作狀態列中點一下某個代理的頭像,即可查看它的工作階段。"],
- "DbCfXV": ["搜尋(", ["searchShortcutLabel"], ")"],
"DbILZA": ["沒有相符項。有些檔案不會納入搜尋(隱藏或被忽略的檔案)。"],
"DcFr-y": ["OpenKnowledge 刪除了一個文件"],
"DcH8-w": ["將 ", ["0"], " 個技能移至專案"],
@@ -1300,6 +1302,7 @@
"FUMerq": ["無法啟用同步:", ["detail"]],
"FWQuPE": ["這個專案執行的 OpenKnowledge 版本和這個應用程式(v", ["0"], ")不同,而且不相容。"],
"FWSjnp": ["編輯原始碼窗格和程式碼類屬性欄位"],
+ "FYy2EN": ["調整文件面板大小"],
"FZtBeR": ["啟用 ", ["0"]],
"FeXcUS": [
["display"],
@@ -1348,6 +1351,7 @@
"GAohqx": ["刪除欄"],
"GBEqoP": ["你的 Git 設定中指定了 ", ["declaredLogin"], ",但無法使用該帳戶的憑證。"],
"GBQjiV": ["新增技能"],
+ "GCrhIF": ["面板"],
"GDvlUT": ["角色"],
"GEyl32": ["正在啟動終端機…"],
"GGsM4y": ["在關係圖中已選取"],
@@ -1820,7 +1824,6 @@
"符號連結是指向來源資料夾的指標,而不是自己獨立的資料夾。每個位置讀到的都是完全相同的位元組,因此不會產生偏差;來源一旦被刪除,該位置就會失效。"
],
"MTs6g3": ["伺服器重新啟動後無法重新連線"],
- "MU_NVW": ["收合 Terminal"],
"MUrVEo": ["沒有最近的專案。"],
"MV-Dkb": ["找到 ", ["countDisplay"], " 個 markdown 檔案"],
"MVxpbf": ["尋找並取代"],
@@ -2514,13 +2517,13 @@
],
"V48OUT": ["你在本機刪除了 <0>", ["filePath"], "</0>,但它在上游被修改過。"],
"V4JHny": ["分享僅支援 GitHub 遠端儲存庫。"],
- "V6AIOn": ["工作區導覽"],
"V6e25h": ["主題預覽"],
"V7QxyT": ["連線已中斷"],
"VAHWL_": ["已以 <0>@", ["signedInLogin"], "</0> 的身分連接"],
"VBE2dw": [
"建立並掌握你故事背後的世界。一個安放角色、地點、勢力,以及把它們串起來的設定的地方,讓細節在寫作過程中保持一致。"
],
+ "VBtCdv": ["無法捲動到該段落。請重試。"],
"VFQXPl": [
"開啟外部連結預覽後,把游標停在連結上會顯示一張卡片,包含網站名稱、頁面標題和描述。"
],
@@ -2650,7 +2653,6 @@
"X2zUS5": ["刪除這則註解"],
"X3MMeA": ["這些問題都沒有自動修正的方式。"],
"X59Fx2": ["無法在 Slidev 中開啟此文件。"],
- "X7ShnN": ["開啟代理面板"],
"X8kjQX": ["重新用 GitHub 驗證"],
"X9VpsP": ["正在載入資料夾內容"],
"XA9uvc": ["OpenKnowledge 會在背景檢查並下載更新。"],
@@ -2778,6 +2780,7 @@
"YS9mSt": ["已從 ", ["0"], " 更新「", ["name"], "」"],
"YSFv5w": ["沒有 git 儲存庫——設定分享在這裡不適用。"],
"YScUUO": ["擷取網頁"],
+ "YStFYH": ["開啟智慧代理"],
"YTLmTM": ["刪除上層的 <0>.git</0> 資料夾"],
"YW7Q86": ["搜尋設定尚未載入——請稍候再試"],
"YWK2zy": [["fileName"], " 的衝突差異"],
@@ -3019,6 +3022,7 @@
"aS77on": ["會變更什麼?"],
"aSVmqV": ["尚未偵測到 AI 工具。安裝之後,可在「設定 > 這個專案」中連接。"],
"aTDVi6": ["已保留你的內容"],
+ "aV2vel": ["窗格 ", ["number"]],
"aWlJai": ["正在啟動登入流程"],
"aXkLuE": ["套用回應格式錯誤"],
"a_u4ck": ["正在載入標籤"],
@@ -3415,6 +3419,7 @@
"f1-q9m": ["保留這些技能"],
"f14doC": ["Slidev"],
"f1XQyZ": ["移動區塊"],
+ "f3YhVJ": ["沒有開啟的面板"],
"f65AOQ": ["起點"],
"f6suyZ": ["已要求變更"],
"f8fH8W": ["設計"],
@@ -3432,6 +3437,7 @@
"fKsRVO": ["來自 ", ["0"], "/", ["1"], " 的技能。"],
"fMsFdZ": ["無法儲存自動更新設定:", ["0"]],
"fNr-MX": ["關閉語意搜尋"],
+ "fObclJ": ["返回編輯器"],
"fOzzSV": ["連結目標「", ["shown"], "」未指向現有檔案。"],
"fRVBiq": [
"在可取得時附上遙測資料、伺服器狀態和執行階段資訊。憑證一律會移除;如果包含文件名稱,它們會以明文出現(不做遮蔽)。"
@@ -3497,7 +3503,6 @@
["descriptorLabel"],
"> 顯示失敗(很可能是屬性有誤)。複製原始碼看看哪裡出了問題,或刪除這個區塊。"
],
- "g5V4_P": ["收合智慧代理面板"],
"g5w1sF": [
"挑一個資料夾,把它併進 ",
["display"],
@@ -3712,10 +3717,6 @@
"i04BJx": ["位於此專案之外 — 在這裡唯讀。"],
"i09An-": ["已還原到較早的版本(", ["0"], ")"],
"i1flq_": ["維基連結建議"],
- "i25FHa": [
- "開啟代理面板 — ",
- ["liveThreadCount", "plural", { "other": ["#", " 個進行中的代理執行緒"] }]
- ],
"i3f2kh": ["沒有相符的指令。"],
"i6o7XB": ["搜尋語言"],
"i92eAT": ["我們會建立一個儲存庫並開始同步——不必用終端機。"],
@@ -4183,6 +4184,7 @@
],
"n7aopT": ["編輯器模式"],
"n81AV0": [["owner"], "/", ["name"], " 已存在。請換一個名稱。"],
+ "nBFK5w": ["調整終端機大小"],
"nBHvPL": ["取消編輯"],
"nBgzKO": ["把這裡設為來源——技能真正的資料夾會搬到這裡"],
"nCzR-G": ["複製驗證碼 ", ["userCode"]],
@@ -4484,6 +4486,7 @@
"qyLmWw": ["原始碼編輯器搜尋面板"],
"qze9od": ["此資料夾同時也屬於 ", ["alsoAffects"], "。"],
"r-OJYm": ["請輸入有效的分支名稱(不能有空格、不能以點開頭、不能包含「..」)。"],
+ "r-wzd8": ["更新與意見回饋"],
"r2eKE3": ["請先登入 ", ["agentName"]],
"r3iaI0": ["尚無聊天。"],
"r4R7AZ": ["清理過程中發生網路錯誤"],
@@ -4700,6 +4703,7 @@
"ten9en": ["最近的專案"],
"tfDRzk": ["儲存"],
"tfi40B": ["建立頁面失敗"],
+ "tgB_VT": ["開啟編輯器"],
"tgWuMB": ["已修改"],
"thnPBX": ["切換到編輯器的下一個分頁。"],
"ti6aF_": ["詢問 ", ["0"], " CLI"],
@@ -4846,6 +4850,7 @@
"un-K1H": ["留在這台電腦上。不會提交到 git。"],
"un8kBM": ["正在建立頁面:", ["linkTitle"], "。"],
"uoJF_D": ["設定或上手太麻煩了"],
+ "uqgCZJ": ["隱藏編輯器"],
"uqs8Gd": [["others", "plural", { "other": ["其他 ", "#", " 個檔案"] }]],
"ur2XSb": ["視覺化編輯器"],
"uraHF0": ["GitLab"],
@@ -5111,6 +5116,7 @@
"xzAmL_": ["已自動核准"],
"xzktOa": ["編輯維基連結"],
"y-LQPF": ["無法解析圖片 ", ["identity"], "。前往引用位置。"],
+ "y0_w13": ["顯示編輯器"],
"y1eoq1": ["複製連結"],
"y1t8bQ": ["設定分區"],
"y3aU20": ["儲存變更"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 512055001..65fe14251 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -1674,6 +1674,7 @@ msgstr "使用中"
msgid "Active panel content for the selected tab shows here."
msgstr "所選分頁的作用中面板內容會顯示在這裡。"
+#: src/components/EditorArea.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Activity"
msgstr "動態"
@@ -1965,6 +1966,10 @@ msgstr "智慧代理連線"
msgid "Agent mode"
msgstr "代理模式"
+#: src/components/EditorArea.tsx
+msgid "Agent panel"
+msgstr "智慧代理面板"
+
#: src/components/EditorArea.tsx
msgid "Agent panel closed to keep Terminal readable."
msgstr "為保持 Terminal 清晰可讀,已關閉智慧代理面板。"
@@ -1987,6 +1992,7 @@ msgstr "代理記錄"
#: src/components/EditorArea.tsx
#: src/components/ExploreSkills.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Agents"
msgstr "代理"
@@ -2183,6 +2189,7 @@ msgstr "應用程式實例:{label},v{version}"
msgid "Append-only log of what changed."
msgstr "記錄變更內容的唯附加記錄檔。"
+#: src/components/AppHeader.tsx
#: src/components/CommandPalette.tsx
msgid "Application"
msgstr "應用程式"
@@ -2547,6 +2554,10 @@ msgstr "返回"
msgid "Back to document view"
msgstr "回到文件檢視"
+#: src/components/EditorArea.tsx
+msgid "Back to editor"
+msgstr "返回編輯器"
+
#: src/components/LinksPanel.tsx
msgid "Backlinks"
msgstr "反向連結"
@@ -3467,10 +3478,6 @@ msgstr "摺疊"
msgid "Collapse {keyName}"
msgstr "摺疊 {keyName}"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse agent panel"
-msgstr "收合智慧代理面板"
-
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -3494,10 +3501,6 @@ msgstr "摺疊「問 AI」"
msgid "Collapse graph"
msgstr "摺疊關係圖"
-#: src/components/TerminalTabStrip.tsx
-msgid "Collapse Terminal"
-msgstr "收合 Terminal"
-
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible content block (Notion-style toggle)."
msgstr "可摺疊內容區塊(Notion 風格摺疊)。"
@@ -3665,7 +3668,7 @@ msgstr "設定使用者、專案和整合相關的選項。"
msgid "conflict"
msgstr "衝突"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "衝突"
@@ -4304,6 +4307,7 @@ msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "無法複製「{0}」:{1}"
#: src/comments/reveal-comment.ts
+#: src/comments/ThreadCard.tsx
msgid "Couldn't find that passage — the text it was on may have changed."
msgstr "找不到該段落 — 它所在的文字可能已變更。"
@@ -4669,6 +4673,10 @@ msgstr "無法儲存此設定。請再試一次。"
msgid "Couldn't save your theme preference."
msgstr "無法儲存你的主題偏好。"
+#: src/comments/reveal-comment.ts
+msgid "Couldn't scroll to that passage. Try again."
+msgstr "無法捲動到該段落。請重試。"
+
#: src/components/BugReportSendToast.tsx
msgid "Couldn't send the report"
msgstr "無法送出回報"
@@ -5289,6 +5297,7 @@ msgid "Diff render mode"
msgstr "差異顯示模式"
#: src/components/AgentDiffPane.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "無法顯示差異"
@@ -5410,6 +5419,10 @@ msgstr "找不到文件"
msgid "Document outline"
msgstr "文件大綱"
+#: src/components/EditorArea.tsx
+msgid "Document panel"
+msgstr "文件面板"
+
#: src/components/DocPanel.tsx
msgid "Document panels"
msgstr "文件面板"
@@ -5733,6 +5746,7 @@ msgstr "正在原地編輯 {boldName}。變更會直接存到你編輯器裡的
msgid "Editing broken MDX source: {reason}"
msgstr "正在編輯壞掉的 MDX 原始碼:{reason}"
+#: src/components/HeaderPaneButtons.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Editor"
msgstr "編輯器"
@@ -5745,6 +5759,10 @@ msgstr "編輯器模式"
msgid "editor pane"
msgstr "編輯器窗格"
+#: src/components/EditorWorkspace.tsx
+msgid "Editor pane"
+msgstr "編輯器窗格"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "編輯器選取範圍"
@@ -6691,6 +6709,7 @@ msgstr "檔案:<0>{fixedName}.md</0>"
msgid "Filename"
msgstr "檔案名稱"
+#: src/components/EditorArea.tsx
#: src/components/FileSidebar.tsx
msgid "Files"
msgstr "檔案"
@@ -7353,11 +7372,17 @@ msgstr "隱藏詳細資料"
msgid "Hide document panel"
msgstr "隱藏文件面板"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Hide Editor"
+msgstr "隱藏編輯器"
+
#: src/components/GraphPanel.tsx
msgid "Hide external URL nodes"
msgstr "隱藏外部 URL 節點"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
+#: src/components/FileSidebar.tsx
#: src/components/ui/sidebar.tsx
msgid "Hide Files"
msgstr "隱藏「檔案」"
@@ -7388,12 +7413,13 @@ msgid "Hide Others"
msgstr "隱藏其他"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
+#: src/components/EditorArea.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Hide panel"
msgstr "隱藏面板"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Hide panel ({panelShortcutLabel})"
msgstr "隱藏面板({panelShortcutLabel})"
@@ -9008,11 +9034,11 @@ msgstr "修改連結目標、錨點和顯示標籤。"
msgid "More"
msgstr "更多"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions"
msgstr "更多動作"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
msgid "More actions ({syncAttentionLabel})"
msgstr "更多動作({syncAttentionLabel})"
@@ -10062,6 +10088,10 @@ msgstr "在你發起操作之前不會有任何變動——請在同步選單中
msgid "Nothing moves until you ask."
msgstr "在你發起操作之前不會有任何變動。"
+#: src/components/NothingOpen.tsx
+msgid "Nothing open"
+msgstr "沒有開啟的面板"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "還沒有設定任何東西。"
@@ -10111,7 +10141,7 @@ msgstr "關閉——外部連結只顯示 URL。不會有任何要求離開這
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "關閉——搜尋只按關鍵字排序。不會有任何內容離開這台電腦。"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Offline"
msgstr "離線"
@@ -10277,13 +10307,9 @@ msgstr "開啟 {tooltipName} 的活動面板"
msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"
msgstr "開啟 {tooltipName} 的活動面板,它正在編輯 {realCurrentDoc}"
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel"
-msgstr "開啟代理面板"
-
-#: src/components/TerminalRevealTab.tsx
-msgid "Open agents panel — {liveThreadCount, plural, one {# live agent thread} other {# live agent threads}}"
-msgstr "開啟代理面板 — {liveThreadCount, plural, other {# 個進行中的代理執行緒}}"
+#: src/components/NothingOpen.tsx
+msgid "Open agents"
+msgstr "開啟智慧代理"
#: src/lib/keyboard-shortcuts.ts
msgid "Open an existing project folder from disk."
@@ -10330,6 +10356,10 @@ msgstr "為選取的檔案樹項目開啟刪除確認框。"
msgid "Open documents tagged #{chip}"
msgstr "開啟標了 #{chip} 的文件"
+#: src/components/NothingOpen.tsx
+msgid "Open editor"
+msgstr "開啟編輯器"
+
#: src/components/BugReportSendToast.tsx
msgid "Open email draft"
msgstr "開啟郵件草稿"
@@ -10501,7 +10531,7 @@ msgstr "開啟原始碼檢查面板"
msgid "Open source: {mirrorSrc}"
msgstr "來源:{mirrorSrc}"
-#: src/components/TerminalRevealTab.tsx
+#: src/components/NothingOpen.tsx
msgid "Open terminal"
msgstr "開啟終端機"
@@ -11062,6 +11092,14 @@ msgstr "向上平移"
msgid "pane {0}"
msgstr "窗格 {0}"
+#: src/components/EditorWorkspace.tsx
+msgid "Pane {number}"
+msgstr "窗格 {number}"
+
+#: src/components/HeaderPaneButtons.tsx
+msgid "Panels"
+msgstr "面板"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "段落"
@@ -11470,6 +11508,7 @@ msgstr "專案"
#: src/components/settings/LintingSection.tsx
#: src/components/settings/ScopeBadge.tsx
#: src/components/SkillsTree.tsx
+#: src/components/WebProjectName.tsx
#: src/lib/skill-scope.ts
msgid "Project"
msgstr "專案"
@@ -11863,7 +11902,7 @@ msgstr "建議"
msgid "Recommended agent skill"
msgstr "推薦代理技能"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Reconnect required"
msgstr "需要重新連接"
@@ -12452,10 +12491,19 @@ msgstr "重設檢視篩選條件"
msgid "Resize {handleKey}"
msgstr "調整 {handleKey} 的大小"
+#: src/components/EditorArea.tsx
+msgid "Resize document panel"
+msgstr "調整文件面板大小"
+
#: src/components/SkillsSidebarDock.tsx
msgid "Resize skills panel"
msgstr "調整「技能」面板大小"
+#: src/components/EditorArea.tsx
+#: src/components/TerminalDock.tsx
+msgid "Resize terminal"
+msgstr "調整終端機大小"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "在你的終端機中解決衝突"
@@ -12868,9 +12916,8 @@ msgid "Scroll to start"
msgstr "捲動到開頭"
#: src/components/CommandPalette.tsx
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderSearchBar.tsx
#: src/components/settings/SettingsDialogShell.tsx
-#: src/components/SidebarSearchBar.tsx
#: src/lib/acp/tool-call-display.ts
#: src/lib/keyboard-shortcuts.ts
msgid "Search"
@@ -12880,10 +12927,6 @@ msgstr "搜尋"
msgid "Search \"{semanticSubmitQuery}\" by meaning"
msgstr "按語意搜尋「{semanticSubmitQuery}」"
-#: src/components/EditorHeader.tsx
-msgid "Search ({searchShortcutLabel})"
-msgstr "搜尋({searchShortcutLabel})"
-
#: src/components/settings/AgentConnectionsSection.tsx
msgid "Search agents"
msgstr "搜尋代理"
@@ -13549,6 +13592,11 @@ msgstr "顯示圖表"
msgid "Show document panel"
msgstr "顯示文件面板"
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+msgid "Show Editor"
+msgstr "顯示編輯器"
+
#: src/components/GraphPanel.tsx
msgid "Show external URL nodes"
msgstr "顯示外部 URL 節點"
@@ -13557,7 +13605,7 @@ msgstr "顯示外部 URL 節點"
msgid "Show fewer"
msgstr "顯示少一點"
-#: src/components/EditorHeader.tsx
+#: src/components/FileListToggle.tsx
#: src/components/ui/sidebar.tsx
msgid "Show Files"
msgstr "顯示「檔案」"
@@ -13614,12 +13662,12 @@ msgid "Show original"
msgstr "顯示原始版本"
#: src/components/AgentDiffPane.tsx
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Show panel"
msgstr "顯示面板"
-#: src/components/EditorToolbar.tsx
+#: src/components/DocPanelToggle.tsx
msgid "Show panel ({panelShortcutLabel})"
msgstr "顯示面板({panelShortcutLabel})"
@@ -14438,7 +14486,7 @@ msgstr "同步模式"
msgid "Sync now"
msgstr "立即同步"
-#: src/components/EditorHeader.tsx
+#: src/components/HeaderOverflowActions.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sync paused"
msgstr "同步已暫停"
@@ -14616,6 +14664,7 @@ msgstr "可用的範本"
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/HeaderPaneButtons.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AgentConnectionsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -16416,6 +16465,10 @@ msgstr "已更新資料夾屬性"
msgid "Updated to Version {version}"
msgstr "已更新到版本 {version}"
+#: src/components/CornerCardStack.tsx
+msgid "Updates and feedback"
+msgstr "更新與意見回饋"
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Updates flow in"
msgstr "更新會自動流入"
@@ -16989,10 +17042,6 @@ msgstr "工作區"
msgid "Workspace Command Palette"
msgstr "工作區指令面板"
-#: src/components/EditorHeader.tsx
-msgid "Workspace navigation"
-msgstr "工作區導覽"
-
#: src/components/NavigatorApp.tsx
#: src/components/RecentProjectsMenu.tsx
msgid "worktree"
diff --git a/packages/app/src/test-utils/config-context.ts b/packages/app/src/test-utils/config-context.ts
new file mode 100644
index 000000000..f27d73d67
--- /dev/null
+++ b/packages/app/src/test-utils/config-context.ts
@@ -0,0 +1,29 @@
+import { ConfigSchema } from '@inkeep/open-knowledge-core/config/schema';
+import type { ConfigContextValue } from '@/lib/config-context';
+
+export interface ProjectTerminalSetting {
+ readonly synced: boolean;
+ readonly enabled: boolean | null;
+}
+
+export const TERMINAL_SETTING_UNSET: ProjectTerminalSetting = { synced: true, enabled: null };
+
+export function configContextWithTerminal({
+ synced,
+ enabled,
+}: ProjectTerminalSetting): ConfigContextValue {
+ return {
+ userBinding: null,
+ userSynced: synced,
+ projectBinding: null,
+ projectLocalBinding: null,
+ okignoreBinding: null,
+ okignoreSynced: synced,
+ userConfig: null,
+ projectConfig: null,
+ projectSynced: synced,
+ projectLocalConfig: ConfigSchema.parse({ terminal: { enabled } }),
+ projectLocalSynced: synced,
+ merged: null,
+ };
+}
diff --git a/packages/app/tests/a11y/acp-agent-notice.e2e.ts b/packages/app/tests/a11y/acp-agent-notice.e2e.ts
index e2d9ac232..adb80dca7 100644
--- a/packages/app/tests/a11y/acp-agent-notice.e2e.ts
+++ b/packages/app/tests/a11y/acp-agent-notice.e2e.ts
@@ -46,7 +46,7 @@ const ANNOUNCER = '[data-testid="agent-thread-warning-announcer"]';
const THREAD_ROOT = '[data-agent-thread-root]';
const COMPOSER = '[data-testid="agent-thread-composer"]';
const AGENTS_PANEL = '[data-agents-panel-mount]';
-const AGENTS_PANEL_REVEAL = '[data-terminal-reveal="right"]';
+const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
const DOCK_EMPTY = '[data-testid="sessions-dock-empty"]';
const TRANSCRIPT = '[data-testid="agent-thread-transcript"]';
const EMPTY_AGENT_CATALOG = { agents: [], stale: false, maxThreads: 8 };
@@ -98,7 +98,7 @@ function threadRosterDelivered(page: Page): Promise<void> {
}
async function openAgentsPanel(page: Page): Promise<void> {
- await page.locator(AGENTS_PANEL_REVEAL).click({ timeout: PANEL_OPEN_TIMEOUT_MS });
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click({ timeout: PANEL_OPEN_TIMEOUT_MS });
await expect(
page.locator(AGENTS_PANEL).locator(DOCK_EMPTY),
'the agents panel did not open onto an empty session dock: it is either collapsed to zero width or a session was seeded into it',
diff --git a/packages/app/tests/a11y/corner-stack.e2e.ts b/packages/app/tests/a11y/corner-stack.e2e.ts
new file mode 100644
index 000000000..f351a4e96
--- /dev/null
+++ b/packages/app/tests/a11y/corner-stack.e2e.ts
@@ -0,0 +1,553 @@
+import AxeBuilder from '@axe-core/playwright';
+import type { ElementHandle, JSHandle, Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ arrangeTerminalAlone,
+ CHAT_PANE_CARD,
+ CORNER_STACK_TEST_ID,
+ contrastRatioOf,
+ cornerStack,
+ expect,
+ expectDocumentOpen,
+ feedbackCard,
+ headerPaneButton,
+ NEWSLETTER_USED_UP,
+ newsletterCard,
+ noticeWithText,
+ openDesktopLayout,
+ openWebLayout,
+ readContrastPair,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ seedNewsletterStateBeforeLoad,
+ setHeaderPane,
+ terminalPaneCard,
+ test,
+ type WorkerServer,
+} from '../stress/_helpers';
+import {
+ emitUpdateEvent,
+ installUpdateEventOverlay,
+} from '../stress/fixtures/update-event-overlay';
+
+const WIDE = { width: 1440, height: 900 } as const;
+const VERSION = '9.9.9';
+const DOWNLOAD_URL = 'https://openknowledge.ai/download';
+const RELEASE_URL = 'https://openknowledge.ai/changelog';
+const STACK_NAME = 'Updates and feedback';
+const STACK = `[data-testid="${CORNER_STACK_TEST_ID}"]`;
+const BOTTOM_TERMINAL = terminalPaneCard('bottom');
+const ANY_TERMINAL = '[data-pane="terminal"], .xterm';
+const WCAG_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'];
+const FEEDBACK_LATCH_TIMEOUT_MS = 15_000;
+const HARNESS_TIMEOUT_MS = 30_000;
+const MAX_TAB_PRESSES = 40;
+const CHAT_AGENT = { source: 'registry', id: 'codex-acp', name: 'Codex' } as const;
+const TAB_STOP_CANDIDATES =
+ 'a[href], area[href], button, input, select, textarea, iframe, summary, [tabindex], [contenteditable=""], [contenteditable="true"]';
+const LIVE_REGION =
+ '[role="status"], [role="alert"], [role="log"], [role="marquee"], [role="timer"], [aria-live]:not([aria-live="off"]), output';
+
+type Host = 'web' | 'desktop';
+
+interface LiveRegion {
+ readonly role: string | null;
+ readonly live: string | null;
+ readonly isUpdateNotice: boolean;
+ readonly text: string;
+}
+
+async function openWithFeedbackShowing(
+ page: Page,
+ api: ApiHelpers,
+ slug: string,
+): Promise<Locator> {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-a11y-${slug}-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openWebLayout(page, docName, WIDE);
+ await expectDocumentOpen(page, docName);
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+ return card;
+}
+
+async function openDesktop(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+): Promise<void> {
+ const docName = `corner-a11y-${slug}-w${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: docName, markdown: `# ${docName}\n\nA document under the corner stack.\n` },
+ ]);
+ await installUpdateEventOverlay(page);
+ await openDesktopLayout(page, workerServer, docName, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ await expectDocumentOpen(page, docName);
+}
+
+async function emitInstallFailed(page: Page): Promise<Locator> {
+ await emitUpdateEvent(page, 'onUpdateRelaunchFailed', {
+ version: VERSION,
+ downloadUrl: DOWNLOAD_URL,
+ });
+ const notice = noticeWithText(page, `Update to ${VERSION} didn't install.`);
+ await expect(notice).toBeVisible();
+ return notice;
+}
+
+async function emitWhatsNew(page: Page): Promise<void> {
+ await emitUpdateEvent(page, 'onWhatsNew', { version: VERSION, releaseUrl: RELEASE_URL });
+}
+
+async function tabStops(page: Page): Promise<JSHandle<HTMLElement[]>> {
+ return await page.evaluateHandle(
+ (candidates) =>
+ Array.from(document.querySelectorAll<HTMLElement>(candidates)).filter(
+ (el) =>
+ el.tabIndex >= 0 &&
+ !el.matches(':disabled') &&
+ el.closest('[inert]') === null &&
+ el.getClientRects().length > 0 &&
+ getComputedStyle(el).visibility === 'visible',
+ ),
+ TAB_STOP_CANDIDATES,
+ );
+}
+
+async function lastTabStopBeforeStack(page: Page): Promise<ElementHandle<HTMLElement>> {
+ const stops = await tabStops(page);
+ const last = await stops.evaluateHandle((list, stackSelector) => {
+ const stack = document.querySelector(stackSelector);
+ if (stack === null) throw new Error('the corner stack is not in the page');
+ const before = list.filter(
+ (el) =>
+ !stack.contains(el) &&
+ (el.compareDocumentPosition(stack) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0,
+ );
+ const found = before.at(-1);
+ if (found === undefined) throw new Error('no tab stop precedes the corner stack');
+ return found;
+ }, STACK);
+ await stops.dispose();
+ const element = last.asElement();
+ if (element === null) throw new Error('expected the last tab stop to be an element');
+ return element;
+}
+
+async function sameTabStopsOutsideCard(
+ page: Page,
+ card: Locator,
+ before: JSHandle<HTMLElement[]>,
+ after: JSHandle<HTMLElement[]>,
+): Promise<{ readonly before: number; readonly after: number; readonly identical: boolean }> {
+ const cardElement = await card.elementHandle();
+ if (cardElement === null) throw new Error('expected the card to be in the page');
+ try {
+ return await page.evaluate(
+ ({ previous, next, within }) => {
+ const outside = (list: HTMLElement[]) => list.filter((el) => !within.contains(el));
+ const was = outside(previous);
+ const now = outside(next);
+ return {
+ before: was.length,
+ after: now.length,
+ identical: was.length === now.length && was.every((el, index) => el === now[index]),
+ };
+ },
+ { previous: before, next: after, within: cardElement },
+ );
+ } finally {
+ await cardElement.dispose();
+ }
+}
+
+async function focusedElement(page: Page): Promise<JSHandle<Element | null>> {
+ return await page.evaluateHandle(() => document.activeElement);
+}
+
+async function stillFocused(focused: JSHandle<Element | null>): Promise<boolean> {
+ return await focused.evaluate((el) => el !== null && el === document.activeElement);
+}
+
+async function focusIsInside(page: Page, selector: string): Promise<boolean> {
+ return await page.evaluate((within) => document.activeElement?.closest(within) != null, selector);
+}
+
+async function liveRegionsIn(scope: Locator): Promise<LiveRegion[]> {
+ return await scope.evaluate((root, selector) => {
+ const regions = [root, ...Array.from(root.querySelectorAll(selector))].filter((el) =>
+ el.matches(selector),
+ );
+ return regions.map((el) => ({
+ role: el.getAttribute('role'),
+ live: el.getAttribute('aria-live'),
+ isUpdateNotice: el.matches('[data-testid^="update-notice-"]'),
+ text: el.textContent?.trim() ?? '',
+ }));
+ }, LIVE_REGION);
+}
+
+async function seriousOrCriticalViolations(page: Page) {
+ const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).include(STACK).analyze();
+ return results.violations.filter(
+ (violation) => violation.impact === 'serious' || violation.impact === 'critical',
+ );
+}
+
+function threadRosterDelivered(page: Page): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(
+ () => reject(new Error('thread socket never delivered its roster')),
+ HARNESS_TIMEOUT_MS,
+ );
+ page.on('websocket', (socket) => {
+ if (!socket.url().includes('/collab/thread')) return;
+ socket.on('framereceived', (frame) => {
+ if (typeof frame.payload !== 'string') return;
+ if (!frame.payload.includes('"op":"threads"')) return;
+ clearTimeout(timer);
+ resolve();
+ });
+ });
+ });
+}
+
+async function focusTheTerminal(page: Page): Promise<void> {
+ await page.locator(`${BOTTOM_TERMINAL} .xterm`).click();
+ await expect.poll(() => focusIsInside(page, BOTTOM_TERMINAL)).toBe(true);
+}
+
+test.describe('the corner stack for keyboard users', () => {
+ test('Tab from the last pane control reaches the feedback card, which follows the panes in the page', async ({
+ page,
+ api,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, 'tab-order');
+
+ const order = await page.evaluate((stackSelector) => {
+ const stack = document.querySelector(stackSelector);
+ if (stack === null) throw new Error('the corner stack is not in the page');
+ const panes = [
+ document.querySelector('[data-app-main]'),
+ ...Array.from(document.querySelectorAll('[data-slot="pane-card"]')),
+ ].filter((el): el is Element => el !== null);
+ return {
+ panes: panes.length,
+ stackFollowsEveryPane: panes.every(
+ (pane) =>
+ !pane.contains(stack) &&
+ (pane.compareDocumentPosition(stack) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0,
+ ),
+ };
+ }, STACK);
+ expect(order.panes).toBeGreaterThan(1);
+ expect(order.stackFollowsEveryPane).toBe(true);
+
+ const lastPaneStop = await lastTabStopBeforeStack(page);
+ expect(await lastPaneStop.evaluate((el) => el.closest('[data-app-main]') !== null)).toBe(true);
+ await lastPaneStop.focus();
+ expect(await lastPaneStop.evaluate((el) => el === document.activeElement)).toBe(true);
+
+ await page.keyboard.press('Tab');
+ await expect(card.getByRole('button', { name: 'Close', exact: true })).toBeFocused();
+
+ await page.keyboard.press('Shift+Tab');
+ expect(await lastPaneStop.evaluate((el) => el === document.activeElement)).toBe(true);
+ });
+
+ test('from a focused bottom terminal with the editor hidden, Ctrl+` leaves the terminal and Tab reaches the install-failed notice without entering it', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'ctrl-backquote');
+ await arrangeTerminalAlone(page, 'bottom');
+ await focusTheTerminal(page);
+
+ const notice = await emitInstallFailed(page);
+ expect(await focusIsInside(page, BOTTOM_TERMINAL)).toBe(true);
+
+ await page.keyboard.press('Control+Backquote');
+ await expect(headerPaneButton(page, 'terminal')).toHaveAttribute('aria-pressed', 'false');
+ await expect(page.getByRole('region', { name: 'Nothing open', exact: true })).toBeVisible();
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ document.activeElement?.matches(
+ '[data-nothing-open], [data-testid="header-pane-button-editor"]',
+ ) === true,
+ ),
+ )
+ .toBe(true);
+
+ const visited: string[] = [];
+ let reachedNotice = false;
+ for (let press = 0; press < MAX_TAB_PRESSES && !reachedNotice; press += 1) {
+ await page.keyboard.press('Tab');
+ const zone = await page.evaluate(
+ ({ terminal, stack }) => {
+ const active = document.activeElement;
+ if (active === null || active === document.body) return 'none';
+ if (active.closest(terminal) !== null) return 'terminal';
+ if (active.closest(stack) !== null) return 'stack';
+ return 'other';
+ },
+ { terminal: ANY_TERMINAL, stack: STACK },
+ );
+ visited.push(zone);
+ reachedNotice = zone === 'stack';
+ }
+
+ expect(reachedNotice, `zones Tab passed through: ${visited.join(', ')}`).toBe(true);
+ expect(visited).not.toContain('terminal');
+ await expect(notice.getByRole('button', { name: 'Dismiss notice', exact: true })).toBeFocused();
+ });
+});
+
+interface FocusSite {
+ readonly name: string;
+ readonly focus: (page: Page) => Promise<void>;
+}
+
+const FOCUS_SITES: readonly FocusSite[] = [
+ {
+ name: 'the editor',
+ focus: async (page) => {
+ const editor = page.locator('.tiptap-editor .ProseMirror').first();
+ await editor.click();
+ await expect(editor).toBeFocused();
+ },
+ },
+ {
+ name: 'the terminal',
+ focus: async (page) => {
+ await setHeaderPane(page, 'terminal', true);
+ await expect(page.locator(BOTTOM_TERMINAL)).toBeVisible();
+ await focusTheTerminal(page);
+ },
+ },
+ {
+ name: 'the chat composer',
+ focus: async (page) => {
+ await setHeaderPane(page, 'agents', true);
+ await expect(page.locator(CHAT_PANE_CARD)).toBeVisible();
+ await page.waitForFunction(() => window.__acpThreadHarness !== undefined, null, {
+ timeout: HARNESS_TIMEOUT_MS,
+ });
+ const threadId = await page.evaluate((agent) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ return harness.openThread({ agent, title: 'Corner stack focus' });
+ }, CHAT_AGENT);
+ const composer = page.locator(
+ `[data-session-id="${threadId}"] [data-testid="agent-thread-composer"]`,
+ );
+ await expect(composer).toBeVisible({ timeout: HARNESS_TIMEOUT_MS });
+ await composer.focus();
+ await expect(composer).toBeFocused();
+ },
+ },
+];
+
+test.describe('an arriving notice never takes focus', () => {
+ for (const { name, focus } of FOCUS_SITES) {
+ test(`a notice arriving while focus is in ${name} leaves focus there and adds no tab stop outside the card`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const roster = threadRosterDelivered(page);
+ await openDesktop(
+ page,
+ api,
+ workerServer,
+ `no-focus-theft-${name.replaceAll(/[^a-z]+/g, '-')}`,
+ );
+ await roster;
+ await focus(page);
+ const focused = await focusedElement(page);
+ const before = await tabStops(page);
+
+ const notice = await emitInstallFailed(page);
+
+ expect(await stillFocused(focused)).toBe(true);
+ const after = await tabStops(page);
+ const comparison = await sameTabStopsOutsideCard(page, notice, before, after);
+ expect(comparison.before).toBeGreaterThan(0);
+ expect(comparison).toMatchObject({ identical: true });
+ await expect(notice.getByRole('button')).toHaveCount(3);
+ expect(await stillFocused(focused)).toBe(true);
+ });
+ }
+});
+
+test.describe('the corner stack for screen-reader users', () => {
+ test('exactly one region carries the stack name, and it shares no words with the toaster region', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'region-name');
+ await emitUpdateEvent(page, 'onUpdateRelaunchFailed', {
+ version: VERSION,
+ downloadUrl: DOWNLOAD_URL,
+ });
+ const stack = page.getByTestId(CORNER_STACK_TEST_ID);
+ await expect(stack).toBeVisible();
+
+ const stackName = await stack.getAttribute('aria-label');
+ if (stackName === null) throw new Error('expected the corner stack to carry a name');
+ expect(stackName).not.toContain('Notifications');
+ expect(stackName).toBe(STACK_NAME);
+ await expect(page.getByRole('region', { name: stackName, exact: true })).toHaveCount(1);
+
+ const toaster = page.getByRole('region', { name: /^Notifications/ });
+ await expect(toaster).toHaveCount(1);
+ const toasterName = await toaster.getAttribute('aria-label');
+ if (toasterName === null) throw new Error('expected the toaster region to carry a name');
+ expect(toasterName).not.toContain(stackName);
+ expect(stackName).not.toContain(toasterName);
+ });
+
+ test('an update notice is the stack only live region and announces politely', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'notice-live-region');
+ const notice = await emitInstallFailed(page);
+
+ await expect(notice).toHaveAttribute('role', 'status');
+ await expect(notice).toHaveAttribute('aria-live', 'polite');
+ expect(await liveRegionsIn(cornerStack(page))).toEqual([
+ expect.objectContaining({ role: 'status', live: 'polite', isUpdateNotice: true }),
+ ]);
+ });
+
+ test('the newsletter card is the region Stay in the loop and adds no live region beyond its status line and, while an error shows, its alert', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await page.route('**/api/subscribe', (route) => route.abort());
+ await openDesktop(page, api, workerServer, 'newsletter-live-regions');
+ await emitWhatsNew(page);
+ const card = newsletterCard(page);
+ await expect(card).toBeVisible();
+ await expect(card).toContainText(`Updated to Version ${VERSION}`);
+
+ expect(await liveRegionsIn(cornerStack(page))).toEqual([
+ { role: 'status', live: null, isUpdateNotice: false, text: 'Product updates in your inbox.' },
+ ]);
+ expect(
+ await card
+ .getByText(`Updated to Version ${VERSION}`, { exact: true })
+ .evaluate((el, selector) => el.closest(selector) === null, LIVE_REGION),
+ ).toBe(true);
+
+ await card.getByRole('textbox', { name: 'Email address' }).fill('not-an-email');
+ await card.getByTestId('subscribe-submit').click();
+ await expect(card.getByRole('alert')).toHaveText('Please enter a valid email address.');
+
+ expect(await liveRegionsIn(cornerStack(page))).toEqual([
+ { role: 'status', live: null, isUpdateNotice: false, text: 'Product updates in your inbox.' },
+ {
+ role: 'alert',
+ live: null,
+ isUpdateNotice: false,
+ text: 'Please enter a valid email address.',
+ },
+ ]);
+ });
+});
+
+interface ScannedCard {
+ readonly name: string;
+ readonly host: Host;
+ readonly show: (page: Page) => Promise<Locator>;
+}
+
+const SCANNED_CARDS: readonly ScannedCard[] = [
+ {
+ name: 'the feedback card',
+ host: 'web',
+ show: async (page) => feedbackCard(page),
+ },
+ {
+ name: 'the install-failed notice',
+ host: 'desktop',
+ show: emitInstallFailed,
+ },
+ {
+ name: 'the newsletter card',
+ host: 'desktop',
+ show: async (page) => {
+ await emitWhatsNew(page);
+ const card = newsletterCard(page);
+ await expect(card).toBeVisible();
+ return card;
+ },
+ },
+];
+
+test.describe('axe over the corner stack', () => {
+ for (const { name, host, show } of SCANNED_CARDS) {
+ test(`with ${name} showing, axe reports no serious or critical violation`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const slug = `axe-${name.replaceAll(/[^a-z]+/g, '-')}`;
+ if (host === 'web') await openWithFeedbackShowing(page, api, slug);
+ else await openDesktop(page, api, workerServer, slug);
+ const card = await show(page);
+ await expect(card).toBeVisible();
+
+ const blocking = await seriousOrCriticalViolations(page);
+ expect(blocking.map((violation) => `${violation.id}: ${violation.help}`)).toEqual([]);
+ });
+ }
+
+ test('with the plain Updated to Version X notice showing, color contrast is recorded and nothing else is serious or critical', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await seedNewsletterStateBeforeLoad(page, NEWSLETTER_USED_UP);
+ await openDesktop(page, api, workerServer, 'axe-updated-notice');
+ await emitWhatsNew(page);
+ const notice = noticeWithText(page, `Updated to Version ${VERSION}`);
+ await expect(notice).toBeVisible();
+
+ const blocking = await seriousOrCriticalViolations(page);
+ const contrast = blocking.filter((violation) => violation.id === 'color-contrast');
+ const others = blocking.filter((violation) => violation.id !== 'color-contrast');
+ expect(others.map((violation) => `${violation.id}: ${violation.help}`)).toEqual([]);
+
+ const pair = await readContrastPair(
+ notice.getByText(`Updated to Version ${VERSION}`, { exact: true }),
+ notice,
+ );
+ await test.info().attach('updated-notice color contrast (pre-existing, not gated)', {
+ body: JSON.stringify(
+ {
+ measuredRatio: Math.round(contrastRatioOf(pair) * 100) / 100,
+ axe: contrast.flatMap((violation) =>
+ violation.nodes.map((node) => node.failureSummary ?? ''),
+ ),
+ },
+ null,
+ 2,
+ ),
+ contentType: 'application/json',
+ });
+ });
+});
diff --git a/packages/app/tests/foundation/production-shell-readiness.node.test.ts b/packages/app/tests/foundation/production-shell-readiness.node.test.ts
new file mode 100644
index 000000000..fc64ad656
--- /dev/null
+++ b/packages/app/tests/foundation/production-shell-readiness.node.test.ts
@@ -0,0 +1,199 @@
+import { type ChildProcess, spawn } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ assertProductionShellIdentity,
+ type ProductionShellStartup,
+ productionShellLockPath,
+ waitForProductionShellEndpoint,
+ waitForProductionShellReady,
+} from '../stress/_helpers/production-shell-readiness.ts';
+import { waitForHttpReady } from '../stress/_helpers/server-process.ts';
+
+const children: ChildProcess[] = [];
+const servers: Server[] = [];
+const dirs: string[] = [];
+
+afterEach(async () => {
+ for (const child of children.splice(0)) {
+ if (child.exitCode === null && child.signalCode === null) {
+ const exited = new Promise((resolve) => child.once('exit', resolve));
+ child.kill('SIGKILL');
+ await exited;
+ }
+ }
+ await Promise.all(
+ servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))),
+ );
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function contentDir(): string {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-shell-ready-')));
+ dirs.push(dir);
+ return dir;
+}
+
+function command(script: string, ...args: string[]): ChildProcess {
+ const child = spawn(process.execPath, ['-e', script, ...args], { stdio: 'ignore' });
+ children.push(child);
+ return child;
+}
+
+const WRITES_LOCK = `
+const { mkdirSync, writeFileSync } = require('node:fs');
+const { dirname } = require('node:path');
+const [lockPath, port, pid] = process.argv.slice(1);
+mkdirSync(dirname(lockPath), { recursive: true });
+const draining = process.argv[4] === 'draining';
+writeFileSync(lockPath, JSON.stringify({ pid: pid === undefined || pid === 'self' ? process.pid : Number(pid), port: Number(port), draining }));
+setInterval(() => {}, 1000);
+`;
+
+const FAILS_TO_BIND = 'setTimeout(() => process.exit(1), 300);';
+
+const STAYS_UNBOUND = 'setInterval(() => {}, 1000);';
+
+async function foreignListener(): Promise<number> {
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ port: 0, collabUrl: null }));
+ });
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (typeof address !== 'object' || address === null) throw new Error('no foreign port');
+ return address.port;
+}
+
+function startup(
+ proc: ChildProcess,
+ dir: string,
+ port: number,
+ host: ProductionShellStartup['host'] = '127.0.0.1',
+): ProductionShellStartup {
+ return { host, port, contentDir: dir, proc, commandPid: () => proc.pid, startedAt: Date.now() };
+}
+
+describe('production-shell readiness', () => {
+ test('a foreign listener on the requested port does not pass for the command that failed to bind it', async () => {
+ const port = await foreignListener();
+ await waitForHttpReady(`http://127.0.0.1:${port}`, 2_000);
+ const dir = contentDir();
+
+ await expect(
+ waitForProductionShellEndpoint(startup(command(FAILS_TO_BIND), dir, port), 10_000),
+ ).rejects.toThrow(
+ new RegExp(`exited with code 1 before its server lock in ${dir} named port ${port}`),
+ );
+ });
+
+ test('the command whose own lock names the requested port is the endpoint', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50123');
+
+ await expect(
+ waitForProductionShellEndpoint(startup(proc, dir, 50123), 10_000),
+ ).resolves.toEqual({ port: 50123, baseURL: 'http://127.0.0.1:50123' });
+ });
+
+ test('an IPv6 endpoint is bracketed the way the Vite endpoint is', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50124');
+
+ await expect(
+ waitForProductionShellEndpoint(startup(proc, dir, 50124, '::1'), 10_000),
+ ).resolves.toEqual({ port: 50124, baseURL: 'http://[::1]:50124' });
+ });
+
+ test('a lock that names another pid is refused', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50125', String(process.pid));
+
+ await expect(waitForProductionShellEndpoint(startup(proc, dir, 50125), 10_000)).rejects.toThrow(
+ `names pid ${process.pid}, not the pid ${proc.pid} this worker spawned`,
+ );
+ });
+
+ test('a command whose own lock is draining is refused as shutting down', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '0', 'self', 'draining');
+
+ await expect(waitForProductionShellEndpoint(startup(proc, dir, 50128), 10_000)).rejects.toThrow(
+ /shutting down before it served 127\.0\.0\.1:50128: the server lock at .* is draining/,
+ );
+ });
+
+ test('a command that never binds the requested port times out naming what it saw', async () => {
+ const dir = contentDir();
+
+ await expect(
+ waitForProductionShellEndpoint(startup(command(STAYS_UNBOUND), dir, 50126), 600),
+ ).rejects.toThrow(/did not bind 127\.0\.0\.1:50126 within 600ms: no server lock at /);
+ });
+
+ test('identity is withdrawn once the lock no longer names the command', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50127');
+ const started = startup(proc, dir, 50127);
+ await waitForProductionShellEndpoint(started, 10_000);
+ expect(() => assertProductionShellIdentity(started)).not.toThrow();
+
+ rmSync(productionShellLockPath(dir));
+
+ expect(() => assertProductionShellIdentity(started)).toThrow(/no server lock at /);
+ });
+
+ test('a lock that names this command on another port is not the requested endpoint', async () => {
+ const dir = contentDir();
+ const proc = command(STAYS_UNBOUND);
+ const lockPath = productionShellLockPath(dir);
+ mkdirSync(dirname(lockPath), { recursive: true });
+ writeFileSync(lockPath, JSON.stringify({ pid: proc.pid, port: 50129, draining: false }));
+
+ await expect(waitForProductionShellEndpoint(startup(proc, dir, 50130), 600)).rejects.toThrow(
+ /did not bind 127\.0\.0\.1:50130 within 600ms: the server lock at .* names port 50129, not the requested 50130/,
+ );
+ });
+
+ test('readiness resolves to the endpoint the probes ran against while the command still holds it', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50131');
+ const probed: unknown[] = [];
+
+ await expect(
+ waitForProductionShellReady(startup(proc, dir, 50131), 10_000, async (endpoint) => {
+ probed.push(endpoint);
+ }),
+ ).resolves.toEqual({ port: 50131, baseURL: 'http://127.0.0.1:50131' });
+ expect(probed).toEqual([{ port: 50131, baseURL: 'http://127.0.0.1:50131' }]);
+ });
+
+ test('readiness fails when the command gives up the endpoint while the probes run', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50132');
+
+ await expect(
+ waitForProductionShellReady(startup(proc, dir, 50132), 10_000, async () => {
+ rmSync(productionShellLockPath(dir));
+ }),
+ ).rejects.toThrow(/no longer holds the endpoint this worker spawned it on: no server lock at /);
+ });
+
+ test('readiness fails when the command moves to another port while the probes run', async () => {
+ const dir = contentDir();
+ const proc = command(WRITES_LOCK, productionShellLockPath(dir), '50133');
+
+ await expect(
+ waitForProductionShellReady(startup(proc, dir, 50133), 10_000, async () => {
+ writeFileSync(
+ productionShellLockPath(dir),
+ JSON.stringify({ pid: proc.pid, port: 50134, draining: false }),
+ );
+ }),
+ ).rejects.toThrow(/no longer holds the endpoint .* names port 50134, not the requested 50133/);
+ });
+});
diff --git a/packages/app/tests/foundation/worker-serving.node.test.ts b/packages/app/tests/foundation/worker-serving.node.test.ts
new file mode 100644
index 000000000..1e8232dfd
--- /dev/null
+++ b/packages/app/tests/foundation/worker-serving.node.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from 'vitest';
+import {
+ E2E_SERVING_ENV,
+ PREBUILT_APP_ENV,
+ workerServingFor,
+ workerServingKind,
+} from '../stress/_helpers/prebuilt/prebuilt-serving.ts';
+import { PRODUCTION_SHELL_ENV } from '../stress/_helpers/production-shell-server.ts';
+
+const ENDPOINT = { host: '127.0.0.1', candidatePort: 41234 } as const;
+const PREBUILT_INVOCATION = { [E2E_SERVING_ENV]: 'prebuilt', [PREBUILT_APP_ENV]: '/tmp/prebuilt' };
+
+describe('the serving a worker starts', () => {
+ test('a production-shell opt-in in the worker env wins over an invocation that serves the prebuilt DEV app', () => {
+ const serving = workerServingFor(
+ { [PRODUCTION_SHELL_ENV]: '1' },
+ PREBUILT_INVOCATION,
+ ENDPOINT,
+ );
+ expect(serving.kind).toBe('production-shell');
+ expect(workerServingKind({ [PRODUCTION_SHELL_ENV]: '1' }, PREBUILT_INVOCATION)).toBe(
+ 'production-shell',
+ );
+ });
+
+ test('a production-shell opt-in in the invocation env applies when the worker env names none', () => {
+ expect(workerServingFor({}, { [PRODUCTION_SHELL_ENV]: '1' }, ENDPOINT).kind).toBe(
+ 'production-shell',
+ );
+ });
+
+ test('the production shell launches ok start on the endpoint the worker requested', () => {
+ const serving = workerServingFor({ [PRODUCTION_SHELL_ENV]: '1' }, {}, ENDPOINT);
+ if (serving.kind !== 'production-shell') throw new Error(`served ${serving.kind}`);
+ const { args } = serving.launch;
+ expect(args[1]).toBe('start');
+ expect(args[args.indexOf('--port') + 1]).toBe('41234');
+ expect(args[args.indexOf('--bind') + 1]).toBe('127.0.0.1');
+ });
+
+ test('without the opt-in the worker serves what the invocation names', () => {
+ expect(workerServingFor({}, PREBUILT_INVOCATION, ENDPOINT)).toEqual({
+ kind: 'prebuilt',
+ outputDir: '/tmp/prebuilt',
+ });
+ expect(workerServingFor({ [PRODUCTION_SHELL_ENV]: '0' }, {}, ENDPOINT)).toEqual({
+ kind: 'dev-server',
+ });
+ expect(workerServingKind({}, PREBUILT_INVOCATION)).toBe('prebuilt');
+ });
+});
diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.ts
index d95365dc9..768f17aa8 100644
--- a/packages/app/tests/integration/e2e-stop-rules.test.ts
+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts
@@ -117,6 +117,7 @@ const NON_DEV_SERVER_SPAWN_SITES = [
'packages/app/tests/stress/_helpers/port-ownership/owner-loss.test-helper.ts',
'packages/app/tests/stress/_helpers/port-ownership/run-case.test-helper.ts',
'packages/app/tests/stress/_helpers/prebuilt/prebuilt-dev-build.ts',
+ 'packages/app/tests/stress/_helpers/production-shell-server.ts',
'packages/app/tests/stress/_helpers/reuse/reuse-run.test-helper.ts',
'packages/app/tests/stress/okf-generated-index-settings.e2e.ts',
'packages/app/tests/stress/prebuilt-dev-serving.e2e.ts',
diff --git a/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts b/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts
index 4febfe553..7bd10a293 100644
--- a/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts
+++ b/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts
@@ -25,8 +25,8 @@ const CLASS_PATTERNS: readonly ClassPattern[] = [
},
{
id: 'P3-top-banner',
- regex: /fixed\s+top-0\s+inset-x-0\b/,
- description: 'full-width top banner (fixed top-0 inset-x-0)',
+ regex: /fixed\s+top-(?:0|\[[^\]]*\])\s+inset-x-0\b/,
+ description: 'full-width top banner (fixed top-0 / top-[…] inset-x-0)',
},
];
@@ -129,7 +129,7 @@ function isAllowlisted(hit: PatternHit): AllowlistEntry | undefined {
}
describe('Fullscreen-overlay safe-area class invariant (Electron + macOS)', () => {
- test('every fixed inset-0 / w-[Nvw] / fixed top-0 inset-x-0 site is on the allowlist OR adopts a safe-area marker', () => {
+ test('every fixed inset-0 / w-[Nvw] / fixed top-pinned inset-x-0 site is on the allowlist OR adopts a safe-area marker', () => {
const hits = findHits();
const offenders: Array<{
hit: PatternHit;
diff --git a/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts b/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts
index 8df4273f7..7621161b1 100644
--- a/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts
+++ b/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts
@@ -852,8 +852,8 @@ describe('worker cache rule self-test', () => {
missingEnv: 0,
nonUnique: 0,
missingCleanup: 0,
- spawns: 2,
- teardowns: 4,
+ spawns: 3,
+ teardowns: 6,
});
const command = resolve(APP_PACKAGE_ROOT, 'tests/stress/_helpers/worker-server-command.ts');
const adapter = resolve(APP_PACKAGE_ROOT, 'tests/stress/_helpers/worker-server-lifetime.ts');
@@ -862,7 +862,7 @@ describe('worker cache rule self-test', () => {
expect(absentKey).not.toBe(graph[command]);
expect(
inspectWorkerCache(source, { ...graph, [command]: absentKey }, WORKER_FIXTURES).missingEnv,
- ).toBe(2);
+ ).toBe(3);
const noOwnerCache = graph[owner].replace('launch.viteCacheDir,', '');
const noFailureCache = source.replace(
'releaseSetupResources.push(() => removeAllDuringTeardown(viteCacheDir));',
@@ -873,7 +873,7 @@ describe('worker cache rule self-test', () => {
expect(
inspectWorkerCache(noFailureCache, { ...graph, [owner]: noOwnerCache }, WORKER_FIXTURES)
.missingCleanup,
- ).toBe(2);
+ ).toBe(3);
const missing = { ...graph };
delete missing[owner];
expect(inspectWorkerCache(source, missing, WORKER_FIXTURES).census).not.toEqual([]);
@@ -896,7 +896,7 @@ describe('worker cache rule self-test', () => {
},
WORKER_FIXTURES,
).nonUnique,
- ).toBe(2);
+ ).toBe(3);
expect(
inspectWorkerCache(
source,
@@ -906,7 +906,7 @@ describe('worker cache rule self-test', () => {
},
WORKER_FIXTURES,
).nonUnique,
- ).toBe(2);
+ ).toBe(3);
});
test('accepts a unique reclaimed cache and rejects the adjacent shared cache', () => {
expect(inspectWorkerCache(workerFixture)).toEqual({
diff --git a/packages/app/tests/stress/_helpers/app-header-host.ts b/packages/app/tests/stress/_helpers/app-header-host.ts
new file mode 100644
index 000000000..1d4791b82
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/app-header-host.ts
@@ -0,0 +1,230 @@
+import { realpathSync } from 'node:fs';
+import type { Page } from '@playwright/test';
+import { installHandoffMocks } from '../fixtures/handoff-mocks';
+import { expect } from './fixtures.ts';
+import { waitForActiveProviderSynced } from './provider.ts';
+
+export type DesktopHeaderPlatform = 'darwin' | 'win32' | 'linux';
+
+export const DESKTOP_HEADER_PLATFORMS = [
+ 'darwin',
+ 'win32',
+ 'linux',
+] as const satisfies readonly DesktopHeaderPlatform[];
+
+export const DESKTOP_HEADER_PLATFORM_NAMES = {
+ darwin: 'macOS',
+ win32: 'Windows',
+ linux: 'Linux',
+} as const satisfies Record<DesktopHeaderPlatform, string>;
+
+export const MAC_WINDOW_BUTTONS_X_PX = 16;
+export const MAC_WINDOW_BUTTONS_WIDTH_PX = 60;
+const WINDOWS_CAPTION_WIDTH_PX = 138;
+const LINUX_CAPTION_WIDTH_PX = 96;
+
+export interface DesktopHeaderHost {
+ readonly projectName?: string;
+ readonly instanceLabel?: string;
+ readonly channel?: 'latest' | 'beta';
+ readonly platform?: DesktopHeaderPlatform;
+ readonly captionWidth?: number;
+}
+
+export type WindowControls =
+ | { readonly corner: 'top-left'; readonly offset: number; readonly width: number }
+ | { readonly corner: 'top-right'; readonly width: number };
+
+function captionWidthFor(platform: Exclude<DesktopHeaderPlatform, 'darwin'>): number {
+ switch (platform) {
+ case 'win32':
+ return WINDOWS_CAPTION_WIDTH_PX;
+ case 'linux':
+ return LINUX_CAPTION_WIDTH_PX;
+ }
+}
+
+function captionWidthOf(host: DesktopHeaderHost): number | null {
+ const platform = host.platform ?? 'darwin';
+ return host.captionWidth ?? (platform === 'darwin' ? null : captionWidthFor(platform));
+}
+
+export function windowControlsOf(host: DesktopHeaderHost): WindowControls {
+ const captionWidth = captionWidthOf(host);
+ if (captionWidth === null) {
+ return {
+ corner: 'top-left',
+ offset: MAC_WINDOW_BUTTONS_X_PX,
+ width: MAC_WINDOW_BUTTONS_WIDTH_PX,
+ };
+ }
+ return { corner: 'top-right', width: captionWidth };
+}
+
+export async function openDesktopHeader(
+ page: Page,
+ workerServer: { baseURL: string; contentDir: string },
+ docName: string,
+ host: DesktopHeaderHost,
+ search = '',
+) {
+ let contentDir = workerServer.contentDir;
+ try {
+ contentDir = realpathSync(contentDir);
+ } catch {}
+ await installHandoffMocks(page, {
+ host: 'electron',
+ install: { claude: false, codex: false, cursor: false },
+ workerBaseURL: workerServer.baseURL,
+ workerContentDir: contentDir,
+ });
+ await page.addInitScript(
+ ({
+ overrides,
+ captionWidth,
+ }: {
+ overrides: DesktopHeaderHost;
+ captionWidth: number | null;
+ }) => {
+ const bridge = (
+ window as unknown as {
+ okDesktop: {
+ config: { projectName: string };
+ instanceLabel: string | null;
+ platform: string;
+ state: { query: () => Promise<unknown> };
+ };
+ }
+ ).okDesktop;
+ if (overrides.platform !== undefined) bridge.platform = overrides.platform;
+ if (overrides.projectName !== undefined) bridge.config.projectName = overrides.projectName;
+ if (overrides.instanceLabel !== undefined) bridge.instanceLabel = overrides.instanceLabel;
+ const channel = overrides.channel;
+ if (channel !== undefined) {
+ bridge.state.query = async () => ({ channel, schemaIncompatibility: null });
+ }
+ if (captionWidth !== null) {
+ new MutationObserver((_records, observer) => {
+ if (document.documentElement == null) return;
+ observer.disconnect();
+ document.documentElement.style.setProperty(
+ '--ok-titlebar-reserve-right',
+ `${captionWidth}px`,
+ );
+ }).observe(document, { childList: true });
+ }
+ },
+ { overrides: host, captionWidth: captionWidthOf(host) },
+ );
+ await page.goto(`/${search}#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.getByTestId('project-switcher-trigger')).toBeVisible();
+ if ((host.platform ?? 'darwin') !== 'darwin') {
+ await expect(page.getByTestId('app-menubar')).toBeVisible();
+ }
+ if (host.channel === 'beta') await expect(page.getByTestId('beta-badge')).toBeVisible();
+ if (host.instanceLabel !== undefined) {
+ await expect(page.getByTestId('instance-badge')).toBeVisible();
+ }
+}
+
+export async function settleFrames(page: Page) {
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }),
+ );
+}
+
+export interface HeaderFit {
+ readonly top: number;
+ readonly height: number;
+ readonly controls: number;
+ readonly outsideRow: readonly string[];
+ readonly overlapping: readonly string[];
+ readonly underWindowControls: readonly string[];
+ readonly layout: string;
+}
+
+async function probeHeaderFit(
+ page: Page,
+ windowControls: WindowControls | null,
+): Promise<HeaderFit> {
+ return await page.evaluate((corner) => {
+ const header = document.querySelector('header[data-app-header]');
+ if (!(header instanceof HTMLElement)) throw new Error('header fit: the app header is missing');
+ const box = header.getBoundingClientRect();
+ const cornerRect =
+ corner === null
+ ? null
+ : corner.corner === 'top-left'
+ ? { left: corner.offset, right: corner.offset + corner.width }
+ : { left: window.innerWidth - corner.width, right: window.innerWidth };
+ const labelOf = (el: Element) =>
+ el.getAttribute('aria-label') ??
+ el.getAttribute('data-testid') ??
+ (el.textContent?.trim() || el.tagName);
+ const controls = Array.from(
+ header.querySelectorAll(
+ 'button, a, [data-testid$="-badge"], [data-testid="header-pane-divider"]',
+ ),
+ ).filter((el): el is HTMLElement => el instanceof HTMLElement && el.checkVisibility());
+ const rects = controls.map((el) => el.getBoundingClientRect());
+ const outsideRow: string[] = [];
+ const underWindowControls: string[] = [];
+ const overlapping: string[] = [];
+ controls.forEach((el, i) => {
+ const r = rects[i];
+ if (r === undefined) return;
+ if (r.top < box.top - 0.5 || r.bottom > box.bottom + 0.5) outsideRow.push(labelOf(el));
+ if (
+ cornerRect !== null &&
+ r.left < cornerRect.right - 0.5 &&
+ r.right > cornerRect.left + 0.5 &&
+ r.top < box.bottom
+ ) {
+ underWindowControls.push(labelOf(el));
+ }
+ controls.forEach((other, j) => {
+ const o = rects[j];
+ if (j <= i || o === undefined || el.contains(other) || other.contains(el)) return;
+ if (
+ r.left < o.right - 0.5 &&
+ o.left < r.right - 0.5 &&
+ r.top < o.bottom - 0.5 &&
+ o.top < r.bottom - 0.5
+ ) {
+ overlapping.push(`${labelOf(el)} | ${labelOf(other)}`);
+ }
+ });
+ });
+ return {
+ top: box.top,
+ height: box.height,
+ controls: controls.length,
+ outsideRow,
+ overlapping,
+ underWindowControls,
+ layout: controls
+ .map((el, i) => `${labelOf(el)}@${Math.round(rects[i]?.left ?? -1)}`)
+ .join(','),
+ };
+ }, windowControls);
+}
+
+export async function settledHeaderFit(
+ page: Page,
+ windowControls: WindowControls | null,
+): Promise<HeaderFit> {
+ await page.evaluate(() => document.fonts.ready);
+ await settleFrames(page);
+ let fit = await probeHeaderFit(page, windowControls);
+ for (let pass = 0; pass < 20; pass += 1) {
+ await settleFrames(page);
+ const next = await probeHeaderFit(page, windowControls);
+ if (next.layout === fit.layout) return next;
+ fit = next;
+ }
+ throw new Error(`header fit: the header layout never settled (last: ${fit.layout})`);
+}
diff --git a/packages/app/tests/stress/_helpers/card-surface.ts b/packages/app/tests/stress/_helpers/card-surface.ts
new file mode 100644
index 000000000..dd5c3b8cd
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/card-surface.ts
@@ -0,0 +1,261 @@
+import type { Locator, Page } from '@playwright/test';
+
+export type RgbaBytes = readonly [number, number, number, number];
+
+export type BorderSideName = 'top' | 'right' | 'bottom' | 'left';
+
+export interface BorderSide {
+ readonly widthPx: number;
+ readonly style: string;
+ readonly colorAlpha: number;
+}
+
+export interface CardSurface {
+ readonly backgroundAlpha: number;
+ readonly borders: Readonly<Record<BorderSideName, BorderSide>>;
+ readonly borderRadius: string;
+ readonly boxShadow: string;
+}
+
+export interface ContrastPair {
+ readonly foreground: RgbaBytes;
+ readonly background: RgbaBytes;
+}
+
+export interface ScreenClip {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export const BORDER_SIDES: readonly BorderSideName[] = ['top', 'right', 'bottom', 'left'];
+
+const OPAQUE = 255;
+
+const ANTIALIAS_MARGIN_PX = 1;
+
+async function rgbaBytesOf(page: Page, colors: readonly string[]): Promise<RgbaBytes[]> {
+ return await page.evaluate((list) => {
+ const context = new OffscreenCanvas(1, 1).getContext('2d', { willReadFrequently: true });
+ if (!context) throw new Error('Could not create a color conversion context');
+ return list.map((color): [number, number, number, number] => {
+ context.fillStyle = '#000001';
+ context.fillStyle = color;
+ const parsed = context.fillStyle;
+ context.fillStyle = '#000002';
+ context.fillStyle = color;
+ if (context.fillStyle !== parsed) {
+ throw new Error(`the canvas could not parse the computed color "${color}"`);
+ }
+ context.clearRect(0, 0, 1, 1);
+ context.fillRect(0, 0, 1, 1);
+ const [red = 0, green = 0, blue = 0, alpha = 0] = context.getImageData(0, 0, 1, 1).data;
+ return [red, green, blue, alpha];
+ });
+ }, colors);
+}
+
+async function alphaOf(page: Page, color: string): Promise<number> {
+ const [bytes] = await rgbaBytesOf(page, [color]);
+ if (bytes === undefined) throw new Error(`expected color bytes for "${color}"`);
+ return bytes[3] / OPAQUE;
+}
+
+export async function readCardSurface(card: Locator): Promise<CardSurface> {
+ const computed = await card.evaluate((el) => {
+ const style = getComputedStyle(el);
+ const border = (side: string) => ({
+ widthPx: Number.parseFloat(style.getPropertyValue(`border-${side}-width`)),
+ style: style.getPropertyValue(`border-${side}-style`),
+ color: style.getPropertyValue(`border-${side}-color`),
+ });
+ return {
+ background: style.backgroundColor,
+ borders: {
+ top: border('top'),
+ right: border('right'),
+ bottom: border('bottom'),
+ left: border('left'),
+ },
+ borderRadius: style.borderRadius,
+ boxShadow: style.boxShadow,
+ };
+ });
+ const page = card.page();
+ const sideOf = async ({ widthPx, style, color }: (typeof computed.borders)['top']) => ({
+ widthPx,
+ style,
+ colorAlpha: await alphaOf(page, color),
+ });
+ const [backgroundAlpha, top, right, bottom, left] = await Promise.all([
+ alphaOf(page, computed.background),
+ sideOf(computed.borders.top),
+ sideOf(computed.borders.right),
+ sideOf(computed.borders.bottom),
+ sideOf(computed.borders.left),
+ ]);
+ return {
+ backgroundAlpha,
+ borders: { top, right, bottom, left },
+ borderRadius: computed.borderRadius,
+ boxShadow: computed.boxShadow,
+ };
+}
+
+export async function readBorderColors(
+ card: Locator,
+): Promise<Readonly<Record<BorderSideName, RgbaBytes>>> {
+ const computed = await card.evaluate((el) => {
+ const style = getComputedStyle(el);
+ return [
+ style.borderTopColor,
+ style.borderRightColor,
+ style.borderBottomColor,
+ style.borderLeftColor,
+ ];
+ });
+ const [top, right, bottom, left] = await rgbaBytesOf(card.page(), computed);
+ if (top === undefined || right === undefined || bottom === undefined || left === undefined) {
+ throw new Error('expected a border color on every side');
+ }
+ return { top, right, bottom, left };
+}
+
+export async function readRootColor(page: Page, customProperty: string): Promise<RgbaBytes> {
+ const value = await page.evaluate(
+ (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim(),
+ customProperty,
+ );
+ if (value === '') throw new Error(`the document root defines no ${customProperty}`);
+ const [bytes] = await rgbaBytesOf(page, [value]);
+ if (bytes === undefined) throw new Error(`expected color bytes for ${customProperty}`);
+ return bytes;
+}
+
+function blendOver(top: RgbaBytes, bottom: RgbaBytes): RgbaBytes {
+ const alpha = top[3] / OPAQUE;
+ const channel = (index: 0 | 1 | 2): number => top[index] * alpha + bottom[index] * (1 - alpha);
+ return [channel(0), channel(1), channel(2), OPAQUE];
+}
+
+export async function readContrastPair(
+ foreground: Locator,
+ background: Locator,
+): Promise<ContrastPair> {
+ const backgroundElement = await background.elementHandle();
+ if (!backgroundElement) throw new Error('the contrast background locator resolved to no element');
+ try {
+ const computed = await foreground.evaluate((foregroundElement, backgroundNode) => {
+ const layers: string[] = [];
+ for (let current: Element | null = backgroundNode; current; current = current.parentElement) {
+ layers.push(getComputedStyle(current).backgroundColor);
+ }
+ return { foreground: getComputedStyle(foregroundElement).color, layers };
+ }, backgroundElement);
+ const [foregroundColor, ...layers] = await rgbaBytesOf(foreground.page(), [
+ computed.foreground,
+ ...computed.layers,
+ ]);
+ if (foregroundColor === undefined) throw new Error('expected the foreground color bytes');
+ const opaqueIndex = layers.findIndex((layer) => layer[3] === OPAQUE);
+ const base = layers[opaqueIndex];
+ if (base === undefined) throw new Error('the contrast background has no opaque ancestor');
+ const composite = layers.slice(0, opaqueIndex).reduceRight(blendOver, base);
+ return { foreground: foregroundColor, background: composite };
+ } finally {
+ await backgroundElement.dispose();
+ }
+}
+
+function linearChannel(channel: number): number {
+ const normalized = channel / OPAQUE;
+ return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
+}
+
+function relativeLuminance([red, green, blue]: RgbaBytes): number {
+ return 0.2126 * linearChannel(red) + 0.7152 * linearChannel(green) + 0.0722 * linearChannel(blue);
+}
+
+export function contrastRatioOf({ foreground, background }: ContrastPair): number {
+ const text = relativeLuminance(blendOver(foreground, background));
+ const surface = relativeLuminance(background);
+ return (Math.max(text, surface) + 0.05) / (Math.min(text, surface) + 0.05);
+}
+
+export async function innerClipsOf(card: Locator): Promise<readonly ScreenClip[]> {
+ const geometry = await card.evaluate((el) => {
+ const rect = el.getBoundingClientRect();
+ const style = getComputedStyle(el);
+ const largest = (...values: string[]) =>
+ Math.max(...values.map((value) => Number.parseFloat(value)));
+ return {
+ left: rect.left,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom,
+ radius: largest(
+ style.borderTopLeftRadius,
+ style.borderTopRightRadius,
+ style.borderBottomRightRadius,
+ style.borderBottomLeftRadius,
+ ),
+ border: largest(
+ style.borderTopWidth,
+ style.borderRightWidth,
+ style.borderBottomWidth,
+ style.borderLeftWidth,
+ ),
+ };
+ });
+ const band = (insetX: number, insetY: number): ScreenClip => {
+ const x = Math.ceil(geometry.left + insetX + ANTIALIAS_MARGIN_PX);
+ const y = Math.ceil(geometry.top + insetY + ANTIALIAS_MARGIN_PX);
+ const right = Math.floor(geometry.right - insetX - ANTIALIAS_MARGIN_PX);
+ const bottom = Math.floor(geometry.bottom - insetY - ANTIALIAS_MARGIN_PX);
+ if (right <= x || bottom <= y)
+ throw new Error('the card is too small to clip inside its corners');
+ return { x, y, width: right - x, height: bottom - y };
+ };
+ return [band(geometry.radius, geometry.border), band(geometry.border, geometry.radius)];
+}
+
+export async function countDifferingPixels(
+ page: Page,
+ first: Buffer,
+ second: Buffer,
+): Promise<number> {
+ if (first.equals(second)) return 0;
+ return await page.evaluate(
+ async ([firstBase64, secondBase64]) => {
+ const decode = async (base64: string): Promise<ImageData> => {
+ const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
+ const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/png' }), {
+ colorSpaceConversion: 'none',
+ premultiplyAlpha: 'none',
+ });
+ const context = new OffscreenCanvas(bitmap.width, bitmap.height).getContext('2d', {
+ willReadFrequently: true,
+ });
+ if (!context) throw new Error('Could not create an image decoding context');
+ context.drawImage(bitmap, 0, 0);
+ return context.getImageData(0, 0, bitmap.width, bitmap.height);
+ };
+ const [a, b] = await Promise.all([decode(firstBase64), decode(secondBase64)]);
+ if (a.width !== b.width || a.height !== b.height) return Number.POSITIVE_INFINITY;
+ let differing = 0;
+ for (let offset = 0; offset < a.data.length; offset += 4) {
+ if (
+ a.data[offset] !== b.data[offset] ||
+ a.data[offset + 1] !== b.data[offset + 1] ||
+ a.data[offset + 2] !== b.data[offset + 2] ||
+ a.data[offset + 3] !== b.data[offset + 3]
+ ) {
+ differing += 1;
+ }
+ }
+ return differing;
+ },
+ [first.toString('base64'), second.toString('base64')] as const,
+ );
+}
diff --git a/packages/app/tests/stress/_helpers/corner-stack.ts b/packages/app/tests/stress/_helpers/corner-stack.ts
new file mode 100644
index 000000000..208759f4d
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/corner-stack.ts
@@ -0,0 +1,105 @@
+import { type ElementHandle, expect, type Locator, type Page } from '@playwright/test';
+
+export const CORNER_STACK_TEST_ID = 'corner-card-stack';
+
+const DOCUMENT_OPEN_TIMEOUT_MS = 30_000;
+
+export interface CardPlacement {
+ readonly inFileSidebar: boolean;
+ readonly inEditorCard: boolean;
+ readonly inInertSubtree: boolean;
+ readonly centerHitsCard: boolean;
+}
+
+export const FLOATING_AND_HIT_TESTABLE: CardPlacement = {
+ inFileSidebar: false,
+ inEditorCard: false,
+ inInertSubtree: false,
+ centerHitsCard: true,
+};
+
+export function cornerStack(page: Page): Locator {
+ return page.getByRole('region', { name: 'Updates and feedback', exact: true });
+}
+
+export function sidebarTrigger(page: Page): Locator {
+ return page.locator('[data-sidebar="trigger"]').first();
+}
+
+export function cornerStackColumn(page: Page): Locator {
+ return cornerStack(page).getByTestId('corner-card-stack-column');
+}
+
+export interface ControlReach {
+ readonly belowHeader: boolean;
+ readonly insideViewport: boolean;
+ readonly centerHitsControl: boolean;
+}
+
+export const REACHABLE: ControlReach = {
+ belowHeader: true,
+ insideViewport: true,
+ centerHitsControl: true,
+};
+
+export async function reachOf(control: Locator): Promise<ControlReach> {
+ return await control.evaluate((el) => {
+ const rect = el.getBoundingClientRect();
+ const headerBottom = document.querySelector('header')?.getBoundingClientRect().bottom ?? 0;
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ return {
+ belowHeader: rect.top >= headerBottom,
+ insideViewport:
+ rect.left >= 0 &&
+ rect.right <= window.innerWidth &&
+ rect.top >= 0 &&
+ rect.bottom <= window.innerHeight,
+ centerHitsControl: hit !== null && el.contains(hit),
+ };
+ });
+}
+
+export function feedbackCard(page: Page): Locator {
+ return cornerStack(page).getByRole('region', { name: 'Share feedback', exact: true });
+}
+
+export function noticeList(page: Page): Locator {
+ return cornerStack(page).getByTestId('update-notices-list');
+}
+
+export function newsletterCard(page: Page): Locator {
+ return noticeList(page).getByRole('region', { name: 'Stay in the loop', exact: true });
+}
+
+export function noticeWithText(page: Page, text: string): Locator {
+ return noticeList(page).getByRole('status').filter({ hasText: text });
+}
+
+export async function placementOf(card: Locator): Promise<CardPlacement> {
+ return await card.evaluate((el) => {
+ const rect = el.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ return {
+ inFileSidebar: el.closest('nav#app-file-sidebar') !== null,
+ inEditorCard: el.closest('[data-slot="pane-card"][data-pane="editor"]') !== null,
+ inInertSubtree: el.closest('[inert]') !== null,
+ centerHitsCard: hit !== null && el.contains(hit),
+ };
+ });
+}
+
+export async function identityOf(before: ElementHandle<Element>, current: Locator) {
+ const now = await current.elementHandle();
+ return await before.evaluate(
+ (el, other) => ({ connected: el.isConnected, sameNode: el === other }),
+ now,
+ );
+}
+
+export const SAME_NODE = { connected: true, sameNode: true };
+
+export async function expectDocumentOpen(page: Page, docName: string): Promise<void> {
+ await expect(page.locator('.tiptap-editor .ProseMirror').first()).toContainText(docName, {
+ timeout: DOCUMENT_OPEN_TIMEOUT_MS,
+ });
+}
diff --git a/packages/app/tests/stress/_helpers/editor-focus-sync.ts b/packages/app/tests/stress/_helpers/editor-focus-sync.ts
new file mode 100644
index 000000000..d521696b3
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/editor-focus-sync.ts
@@ -0,0 +1,13 @@
+import type { Page } from '@playwright/test';
+
+export const PROSEMIRROR_FOCUS_SYNC_DELAY_MS = 20;
+
+export async function afterEditorFocusSync(page: Page): Promise<void> {
+ await page.evaluate(
+ (delayMs) =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, delayMs);
+ }),
+ PROSEMIRROR_FOCUS_SYNC_DELAY_MS,
+ );
+}
diff --git a/packages/app/tests/stress/_helpers/feedback-nudge.ts b/packages/app/tests/stress/_helpers/feedback-nudge.ts
new file mode 100644
index 000000000..465c14fc0
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/feedback-nudge.ts
@@ -0,0 +1,42 @@
+import type { Page } from '@playwright/test';
+import type { FeedbackNudgeState } from '@/lib/feedback-nudge-store';
+
+export const FEEDBACK_NUDGE_KEY = 'ok-feedback-nudge-v1';
+
+const FEEDBACK_NUDGE_DOC_COUNT = 10;
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function eligibleFeedbackNudgeState(now = Date.now()): FeedbackNudgeState {
+ return { firstSeenAt: now - 15 * DAY_MS, shownAt: null, dismissed: false };
+}
+
+interface SeedDocsApi {
+ seedDocs(docs: Array<{ name: string; markdown: string }>): Promise<void>;
+}
+
+export async function seedFeedbackEligibleDocs(api: SeedDocsApi, prefix: string): Promise<string> {
+ const docNameAt = (index: number) => `${prefix}-${index + 1}`;
+ await api.seedDocs(
+ Array.from({ length: FEEDBACK_NUDGE_DOC_COUNT }, (_, index) => {
+ const name = docNameAt(index);
+ return {
+ name,
+ markdown: `---\ntitle: "${name}"\n---\n\n# ${name}\n\nSeeded so the feedback card counts ten documents.\n`,
+ };
+ }),
+ );
+ return docNameAt(0);
+}
+
+export async function seedFeedbackNudgeStateBeforeLoad(
+ page: Page,
+ state: FeedbackNudgeState = eligibleFeedbackNudgeState(),
+): Promise<void> {
+ await page.addInitScript(
+ ({ key, value }) => {
+ if (localStorage.getItem(key) === null) localStorage.setItem(key, value);
+ },
+ { key: FEEDBACK_NUDGE_KEY, value: JSON.stringify(state) },
+ );
+}
diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.ts
index 431f68972..5f05eea95 100644
--- a/packages/app/tests/stress/_helpers/fixtures.ts
+++ b/packages/app/tests/stress/_helpers/fixtures.ts
@@ -5,7 +5,15 @@ import type { ProblemType } from '@inkeep/open-knowledge-core';
import { test as base } from '@playwright/test';
import { resetContentToFixtureBaseline } from './content-reset.ts';
import { gotoWhileLoadProgresses, requireDeadlineAt } from './load-progress.ts';
-import { type WorkerServing, workerServingFromEnv } from './prebuilt/prebuilt-serving.ts';
+import { type WorkerServing, workerServingFor } from './prebuilt/prebuilt-serving.ts';
+import {
+ type ProductionShellStartup,
+ waitForProductionShellReady,
+} from './production-shell-readiness.ts';
+import {
+ initProductionShellContent,
+ type ProductionShellLaunch,
+} from './production-shell-server.ts';
import { checkServerLease, leaseWorkerServer, type ServerLease } from './reuse/lease-fixture.ts';
import {
type BoundViteEndpoint,
@@ -30,6 +38,7 @@ import {
completeWorkerServerRelease,
stopWorkerServer,
type WorkerServerProcess,
+ workerServerCommandPid,
} from './worker-server-lifetime.ts';
interface ProblemError extends Error {
@@ -64,6 +73,7 @@ export interface WorkerServer {
port: number;
baseURL: string;
contentDir: string;
+ launch?: ProductionShellLaunch;
}
export interface AgentIdentity {
@@ -268,21 +278,46 @@ export async function checkApiConfig(baseURL: string, timeoutMs: number): Promis
}
}
+function productionShellStartupOf(started: StartedWorkerServer): ProductionShellStartup {
+ const { pending, proc, contentDir } = started;
+ return {
+ host: pending.request.host,
+ port: pending.request.candidatePort,
+ contentDir,
+ proc,
+ commandPid: () => workerServerCommandPid(proc),
+ startedAt: pending.startedAt,
+ };
+}
+
export async function waitForServerReady(started: StartedWorkerServer): Promise<BoundViteEndpoint> {
- const { pending } = started;
- const { baseURL, port } = await waitForBoundViteEndpoint(
- pending,
- WORKER_SERVER_READINESS_BUDGET_MS,
- );
- await waitForHttpReady(
- baseURL,
- WORKER_SERVER_READINESS_BUDGET_MS,
- pending.proc,
- pending.startedAt,
- );
- await checkApiConfig(baseURL, WORKER_SERVER_BUDGET_RESERVES.apiConfig);
- await checkCollabSync(port, WORKER_SERVER_BUDGET_RESERVES.collabSync);
- return { baseURL, port };
+ const { pending, serving } = started;
+ const probeServedEndpoint = async ({ baseURL, port }: BoundViteEndpoint): Promise<void> => {
+ await waitForHttpReady(
+ baseURL,
+ WORKER_SERVER_READINESS_BUDGET_MS,
+ pending.proc,
+ pending.startedAt,
+ );
+ await checkApiConfig(baseURL, WORKER_SERVER_BUDGET_RESERVES.apiConfig);
+ await checkCollabSync(port, WORKER_SERVER_BUDGET_RESERVES.collabSync, pending.request.host);
+ };
+ switch (serving.kind) {
+ case 'production-shell':
+ return waitForProductionShellReady(
+ productionShellStartupOf(started),
+ WORKER_SERVER_READINESS_BUDGET_MS,
+ probeServedEndpoint,
+ );
+ case 'dev-server':
+ case 'prebuilt': {
+ const endpoint = await waitForBoundViteEndpoint(pending, WORKER_SERVER_READINESS_BUDGET_MS);
+ await probeServedEndpoint(endpoint);
+ return endpoint;
+ }
+ default:
+ return serving satisfies never;
+ }
}
async function settleBeforeDeadline<T>(
@@ -451,7 +486,7 @@ export function spawnWorkerDevServer(
contentDir: string,
viteCacheDir: string,
serverLog: ServerLog,
- serving: WorkerServing = workerServingFromEnv(process.env),
+ serving: WorkerServing,
): WorkerServerProcess {
return acquireWorkerServer(
request,
@@ -470,6 +505,7 @@ export interface StartedWorkerServer {
viteCacheDir: string;
serverLog: ServerLog;
proc: WorkerServerProcess;
+ serving: WorkerServing;
}
function setupResidueOf(started: StartedWorkerServer): string {
@@ -509,6 +545,8 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
releaseSetupResources.push(() => removeAllDuringTeardown(viteCacheDir));
seedRequiredFixtureFiles(contentDir);
+ const serving = workerServingFor(workerServerEnv, process.env, request);
+ if (serving.kind === 'production-shell') initProductionShellContent(contentDir);
const serverLog = openServerLog(`w${workerInfo.workerIndex}`);
openedServerLog = serverLog;
@@ -520,6 +558,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
contentDir,
viteCacheDir,
serverLog,
+ serving,
);
ownedProc = proc;
releaseSetupResources.push(() =>
@@ -536,6 +575,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
viteCacheDir,
serverLog,
proc,
+ serving,
};
});
@@ -582,9 +622,13 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
);
}
- const { contentDir, viteCacheDir, serverLog, proc, pending } = started;
+ const { contentDir, viteCacheDir, serverLog, proc, pending, serving } = started;
- await use({ ...endpoint, contentDir });
+ await use({
+ ...endpoint,
+ contentDir,
+ ...(serving.kind === 'production-shell' ? { launch: serving.launch } : {}),
+ });
const teardown = openBudgetPhase(TEARDOWN_PHASE_NAME, WORKER_SERVER_BUDGET_RESERVES.teardown);
await completeWorkerServerRelease(proc, async () => {
diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.ts
index e78a8cdd2..432d14743 100644
--- a/packages/app/tests/stress/_helpers/index.ts
+++ b/packages/app/tests/stress/_helpers/index.ts
@@ -1,10 +1,58 @@
export { acpCatalogBody } from './acp-catalog.ts';
+export {
+ DESKTOP_HEADER_PLATFORM_NAMES,
+ DESKTOP_HEADER_PLATFORMS,
+ type DesktopHeaderHost,
+ MAC_WINDOW_BUTTONS_WIDTH_PX,
+ MAC_WINDOW_BUTTONS_X_PX,
+ openDesktopHeader,
+ settledHeaderFit,
+ settleFrames,
+ type WindowControls,
+ windowControlsOf,
+} from './app-header-host.ts';
export {
AUDIT_CONSOLE_RECORD_CASES,
chromiumResourceFailureRecord,
} from './audit-console-records.test-helper.ts';
+export {
+ BORDER_SIDES,
+ type BorderSide,
+ type BorderSideName,
+ type CardSurface,
+ type ContrastPair,
+ contrastRatioOf,
+ countDifferingPixels,
+ innerClipsOf,
+ type RgbaBytes,
+ readBorderColors,
+ readCardSurface,
+ readContrastPair,
+ readRootColor,
+ type ScreenClip,
+} from './card-surface.ts';
export { simulateCopyAndRead, simulateCutAndRead } from './clipboard.ts';
export { resetContentToFixtureBaseline } from './content-reset.ts';
+export {
+ type CardPlacement,
+ CORNER_STACK_TEST_ID,
+ type ControlReach,
+ cornerStack,
+ cornerStackColumn,
+ expectDocumentOpen,
+ FLOATING_AND_HIT_TESTABLE,
+ feedbackCard,
+ identityOf,
+ newsletterCard,
+ noticeList,
+ noticeWithText,
+ placementOf,
+ REACHABLE,
+ reachOf,
+ SAME_NODE,
+ sidebarTrigger,
+} from './corner-stack.ts';
+export { afterEditorFocusSync, PROSEMIRROR_FOCUS_SYNC_DELAY_MS } from './editor-focus-sync.ts';
export {
type CaretPlacement,
focusEditor,
@@ -20,6 +68,11 @@ export {
externalLinkCueSnapshot,
hasExternalCue,
} from './external-link-cue.ts';
+export {
+ FEEDBACK_NUDGE_KEY,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+} from './feedback-nudge.ts';
export {
type AgentIdentity,
type ApiHelpers,
@@ -43,6 +96,23 @@ export {
toggleMode,
waitForLandingSettled,
} from './landing.ts';
+export {
+ arrangeTerminalAlone,
+ CHAT_PANE_CARD,
+ type DesktopLayoutOptions,
+ EDITOR_PANE_CARD,
+ expectEditorHidden,
+ type HeaderPane,
+ headerPaneButton,
+ type LayoutViewport,
+ openDesktopLayout,
+ openWebLayout,
+ presetTerminalPlacement,
+ runPaletteCommand,
+ setHeaderPane,
+ stubAgentCatalog,
+ terminalPaneCard,
+} from './pane-layout.ts';
export {
appSourcesIn,
servedEntryScriptRoute,
@@ -94,6 +164,12 @@ export {
waitForSlashMenuFirstOption,
waitForSlashMenuOpen,
} from './slash-menu.ts';
+export {
+ NEWSLETTER_KEY,
+ NEWSLETTER_USED_UP,
+ type NewsletterState,
+ seedNewsletterStateBeforeLoad,
+} from './subscribe-card.ts';
export { blockMarker, generateTallDoc } from './tall-doc-fixture.ts';
export { removeAllDuringTeardown } from './teardown-fs.ts';
export {
diff --git a/packages/app/tests/stress/_helpers/pane-layout.ts b/packages/app/tests/stress/_helpers/pane-layout.ts
new file mode 100644
index 000000000..5e6c212d1
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/pane-layout.ts
@@ -0,0 +1,114 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ TERMINAL_PLACEMENT_KEY,
+ type TerminalPlacement,
+} from '../../../src/lib/terminal-placement-store';
+import { acpCatalogBody } from './acp-catalog.ts';
+import { openDesktopHeader } from './app-header-host.ts';
+import { expect } from './fixtures.ts';
+import { waitForActiveProviderSynced } from './provider.ts';
+
+export type HeaderPane = 'editor' | 'agents' | 'terminal';
+
+export interface LayoutViewport {
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface DesktopLayoutOptions {
+ readonly viewport: LayoutViewport;
+ readonly terminalPlacement: TerminalPlacement;
+}
+
+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 function terminalPaneCard(placement: TerminalPlacement): string {
+ return `[data-slot="pane-card"][data-pane="terminal"][data-placement="${placement}"]`;
+}
+
+export function headerPaneButton(page: Page, pane: HeaderPane): Locator {
+ return page.getByTestId(`header-pane-button-${pane}`);
+}
+
+export async function stubAgentCatalog(page: Page): Promise<void> {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+}
+
+export async function presetTerminalPlacement(
+ page: Page,
+ placement: TerminalPlacement,
+): Promise<void> {
+ await page.addInitScript(({ key, value }) => window.localStorage.setItem(key, value), {
+ key: TERMINAL_PLACEMENT_KEY,
+ value: placement,
+ });
+}
+
+export async function openWebLayout(
+ page: Page,
+ docName: string,
+ viewport: LayoutViewport,
+): Promise<void> {
+ await stubAgentCatalog(page);
+ await page.setViewportSize(viewport);
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(headerPaneButton(page, 'editor')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+}
+
+export async function openDesktopLayout(
+ page: Page,
+ workerServer: { baseURL: string; contentDir: string },
+ docName: string,
+ { viewport, terminalPlacement }: DesktopLayoutOptions,
+): Promise<void> {
+ await stubAgentCatalog(page);
+ await presetTerminalPlacement(page, terminalPlacement);
+ await page.setViewportSize(viewport);
+ await openDesktopHeader(page, workerServer, docName, {});
+ await expect(headerPaneButton(page, 'terminal')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+}
+
+export async function setHeaderPane(page: Page, pane: HeaderPane, on: boolean): Promise<void> {
+ const button = headerPaneButton(page, pane);
+ if ((await button.getAttribute('aria-pressed')) !== String(on)) await button.click();
+ await expect(button).toHaveAttribute('aria-pressed', String(on));
+}
+
+export async function runPaletteCommand(
+ page: Page,
+ query: string,
+ commandId: string,
+): Promise<void> {
+ await page.evaluate(() => {
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ });
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await expect(input).toBeFocused();
+ await input.fill(query);
+ const row = page.getByTestId(`command-palette-${commandId}`);
+ await expect(row).toBeVisible();
+ await row.click();
+ await expect(page.locator('[data-slot="command-list"]')).toBeHidden();
+}
+
+export async function expectEditorHidden(page: Page): Promise<void> {
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'false');
+ await expect(page.locator(EDITOR_PANE_CARD)).toHaveAttribute('inert', '');
+ await expect(page.locator(EDITOR_PANE_CARD)).toHaveCSS('visibility', 'hidden');
+}
+
+export async function arrangeTerminalAlone(
+ page: Page,
+ placement: TerminalPlacement,
+): Promise<void> {
+ await setHeaderPane(page, 'agents', false);
+ await setHeaderPane(page, 'terminal', true);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect(page.locator(terminalPaneCard(placement))).toBeVisible();
+}
diff --git a/packages/app/tests/stress/_helpers/prebuilt/prebuilt-serving.ts b/packages/app/tests/stress/_helpers/prebuilt/prebuilt-serving.ts
index 6526be647..bab022f86 100644
--- a/packages/app/tests/stress/_helpers/prebuilt/prebuilt-serving.ts
+++ b/packages/app/tests/stress/_helpers/prebuilt/prebuilt-serving.ts
@@ -8,6 +8,11 @@ import {
prebuiltManifest,
prebuiltServingDecision,
} from '../../../foundation/test-server-inputs.ts';
+import {
+ PRODUCTION_SHELL_ENV,
+ type ProductionShellLaunch,
+ productionShellLaunch,
+} from '../production-shell-server.ts';
export const E2E_SERVING_ENV = 'OK_TEST_E2E_SERVING';
export const PREBUILT_APP_ENV = 'OK_TEST_PREBUILT_APP';
@@ -24,7 +29,10 @@ export const PREBUILT_BUILD_OPTIONS = {
export type WorkerServing =
| { readonly kind: 'dev-server' }
- | { readonly kind: 'prebuilt'; readonly outputDir: string };
+ | { readonly kind: 'prebuilt'; readonly outputDir: string }
+ | { readonly kind: 'production-shell'; readonly launch: ProductionShellLaunch };
+
+export type ModuleServing = Exclude<WorkerServing, { readonly kind: 'production-shell' }>;
export type PrebuiltServing = Extract<WorkerServing, { readonly kind: 'prebuilt' }>;
@@ -49,7 +57,7 @@ export function e2eServingMode(env: Env): E2eServingMode {
return mode;
}
-export function workerServingFromEnv(env: Env): WorkerServing {
+export function workerServingFromEnv(env: Env): ModuleServing {
if (e2eServingMode(env) === 'dev-server') return { kind: 'dev-server' };
const outputDir = env[PREBUILT_APP_ENV];
if (outputDir === undefined || outputDir === '') {
@@ -60,6 +68,33 @@ export function workerServingFromEnv(env: Env): WorkerServing {
return { kind: 'prebuilt', outputDir };
}
+export function workerServingKind(
+ workerServerEnv: Readonly<Record<string, string>>,
+ env: Env,
+): WorkerServing['kind'] {
+ if ((workerServerEnv[PRODUCTION_SHELL_ENV] ?? env[PRODUCTION_SHELL_ENV]) === '1') {
+ return 'production-shell';
+ }
+ return e2eServingMode(env);
+}
+
+export function workerServingFor(
+ workerServerEnv: Readonly<Record<string, string>>,
+ env: Env,
+ endpoint: { readonly host: string; readonly candidatePort: number },
+): WorkerServing {
+ const kind = workerServingKind(workerServerEnv, env);
+ switch (kind) {
+ case 'production-shell':
+ return { kind, launch: productionShellLaunch(endpoint.host, endpoint.candidatePort) };
+ case 'dev-server':
+ case 'prebuilt':
+ return workerServingFromEnv(env);
+ default:
+ return kind satisfies never;
+ }
+}
+
function stringRecord(value: unknown): Readonly<Record<string, string>> | undefined {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
const entries = Object.entries(value);
diff --git a/packages/app/tests/stress/_helpers/prebuilt/served-modules.ts b/packages/app/tests/stress/_helpers/prebuilt/served-modules.ts
index fef362d40..4dc500097 100644
--- a/packages/app/tests/stress/_helpers/prebuilt/served-modules.ts
+++ b/packages/app/tests/stress/_helpers/prebuilt/served-modules.ts
@@ -5,7 +5,7 @@ import {
PREBUILT_MODULE_MANIFEST,
} from '../../../../src/build/prebuilt-dev-contract.ts';
import { APP_PACKAGE_ROOT } from '../seed-key.ts';
-import { type WorkerServing, workerServingFromEnv } from './prebuilt-serving.ts';
+import { type ModuleServing, workerServingFromEnv } from './prebuilt-serving.ts';
type ModuleLocator = {
readonly moduleUrl: (source: string) => string;
@@ -145,7 +145,7 @@ function prebuiltModuleLocator(outputDir: string): ModuleLocator {
}
export function resolveServedModules(
- serving: WorkerServing,
+ serving: ModuleServing,
appRoot: string = APP_PACKAGE_ROOT,
): ServedModules {
const locator =
diff --git a/packages/app/tests/stress/_helpers/production-shell-readiness.ts b/packages/app/tests/stress/_helpers/production-shell-readiness.ts
new file mode 100644
index 000000000..25e8a3da9
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/production-shell-readiness.ts
@@ -0,0 +1,149 @@
+import type { ChildProcess } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { TEST_SERVER_HOST_FAMILY } from '../../../src/build/test-server-startup-contract.ts';
+import {
+ type BoundViteEndpoint,
+ describeExit,
+ endpointBaseURL,
+ requireBoundMs,
+ type ViteStartupRequest,
+} from './server-process.ts';
+
+const LOCK_POLL_INTERVAL_MS = 100;
+
+export interface ProductionShellStartup {
+ readonly host: ViteStartupRequest['host'];
+ readonly port: number;
+ readonly contentDir: string;
+ readonly proc: ChildProcess;
+ readonly commandPid: () => number | undefined;
+ readonly startedAt: number;
+}
+
+type LockVerdict =
+ | { readonly kind: 'bound' }
+ | { readonly kind: 'pending'; readonly reason: string }
+ | { readonly kind: 'foreign'; readonly reason: string }
+ | { readonly kind: 'stopping'; readonly reason: string };
+
+export function productionShellLockPath(contentDir: string): string {
+ return join(contentDir, '.ok', 'local', 'server.lock');
+}
+
+function readLock(path: string): Record<string, unknown> | string {
+ let text: string;
+ try {
+ text = readFileSync(path, 'utf8');
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return `no server lock at ${path}`;
+ throw err;
+ }
+ try {
+ const value: unknown = JSON.parse(text);
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
+ return value as Record<string, unknown>;
+ }
+ } catch {}
+ return `the server lock at ${path} is not a JSON object yet`;
+}
+
+function lockVerdict(startup: ProductionShellStartup): LockVerdict {
+ const path = productionShellLockPath(startup.contentDir);
+ const lock = readLock(path);
+ if (typeof lock === 'string') return { kind: 'pending', reason: lock };
+ const pid = startup.commandPid();
+ if (pid === undefined) {
+ return { kind: 'pending', reason: 'the worker has not learned its command pid yet' };
+ }
+ if (lock.pid !== pid) {
+ return {
+ kind: 'foreign',
+ reason: `the server lock at ${path} names pid ${String(lock.pid)}, not the pid ${pid} this worker spawned`,
+ };
+ }
+ if (lock.draining === true) {
+ return { kind: 'stopping', reason: `the server lock at ${path} is draining` };
+ }
+ if (lock.port !== startup.port) {
+ return {
+ kind: 'pending',
+ reason: `the server lock at ${path} names port ${String(lock.port)}, not the requested ${startup.port}`,
+ };
+ }
+ return { kind: 'bound' };
+}
+
+function commandExited(proc: ChildProcess): boolean {
+ return proc.exitCode !== null || proc.signalCode !== null;
+}
+
+function endpointOf(startup: ProductionShellStartup): BoundViteEndpoint {
+ return {
+ port: startup.port,
+ baseURL: endpointBaseURL({
+ address: startup.host,
+ family: TEST_SERVER_HOST_FAMILY[startup.host],
+ port: startup.port,
+ }),
+ };
+}
+
+export async function waitForProductionShellEndpoint(
+ startup: ProductionShellStartup,
+ timeoutMs: number,
+): Promise<BoundViteEndpoint> {
+ requireBoundMs(timeoutMs, 'waitForProductionShellEndpoint');
+ const deadlineAt = startup.startedAt + timeoutMs;
+ while (true) {
+ const verdict = lockVerdict(startup);
+ if (verdict.kind === 'bound') return endpointOf(startup);
+ if (verdict.kind === 'foreign') {
+ throw new Error(
+ `production-shell server for ${startup.host}:${startup.port} is not the one this worker spawned: ${verdict.reason}`,
+ );
+ }
+ if (verdict.kind === 'stopping') {
+ throw new Error(
+ `production-shell server command is shutting down before it served ${startup.host}:${startup.port}: ${verdict.reason}`,
+ );
+ }
+ if (commandExited(startup.proc)) {
+ throw new Error(
+ `production-shell server command exited ${describeExit(startup.proc)} before its server lock in ${startup.contentDir} named port ${startup.port}: ${verdict.reason}`,
+ );
+ }
+ if (Date.now() >= deadlineAt) {
+ throw new Error(
+ `production-shell server did not bind ${startup.host}:${startup.port} within ${timeoutMs}ms: ${verdict.reason}`,
+ );
+ }
+ await wait(Math.min(LOCK_POLL_INTERVAL_MS, Math.max(0, deadlineAt - Date.now())));
+ }
+}
+
+export function assertProductionShellIdentity(startup: ProductionShellStartup): void {
+ if (commandExited(startup.proc)) {
+ throw new Error(
+ `production-shell server command exited ${describeExit(startup.proc)} after its readiness checks`,
+ );
+ }
+ const verdict = lockVerdict(startup);
+ if (verdict.kind !== 'bound') {
+ throw new Error(
+ `production-shell server for ${startup.host}:${startup.port} no longer holds the endpoint this worker spawned it on: ${verdict.reason}`,
+ );
+ }
+}
+
+export async function waitForProductionShellReady(
+ startup: ProductionShellStartup,
+ timeoutMs: number,
+ probe: (endpoint: BoundViteEndpoint) => Promise<void>,
+): Promise<BoundViteEndpoint> {
+ const endpoint = await waitForProductionShellEndpoint(startup, timeoutMs);
+ await probe(endpoint);
+ assertProductionShellIdentity(startup);
+ return endpoint;
+}
diff --git a/packages/app/tests/stress/_helpers/production-shell-server.ts b/packages/app/tests/stress/_helpers/production-shell-server.ts
new file mode 100644
index 000000000..83935510d
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/production-shell-server.ts
@@ -0,0 +1,46 @@
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+import { APP_PACKAGE_ROOT } from './seed-key.ts';
+
+export const PRODUCTION_SHELL_ENV = 'OK_TEST_PRODUCTION_SHELL';
+
+const CLI_ENTRY = join(APP_PACKAGE_ROOT, '../cli/dist/cli.mjs');
+
+export interface ProductionShellLaunch {
+ mode: 'production';
+ command: string;
+ args: readonly string[];
+}
+
+export function productionShellLaunch(host: string, port: number): ProductionShellLaunch {
+ return {
+ mode: 'production',
+ command: process.execPath,
+ args: [
+ CLI_ENTRY,
+ 'start',
+ '--port',
+ String(port),
+ '--bind',
+ host,
+ '--no-open-browser',
+ '--mode',
+ 'browser',
+ '--react-shell-dist-dir',
+ join(APP_PACKAGE_ROOT, 'dist'),
+ '--idle-shutdown',
+ 'off',
+ ],
+ };
+}
+
+export function initProductionShellContent(contentDir: string): void {
+ const initialized = spawnSync(
+ process.execPath,
+ [CLI_ENTRY, 'init', '--no-mcp', '--no-skills', '--content-dir', '.', '--json'],
+ { cwd: contentDir, encoding: 'utf8' },
+ );
+ if (initialized.status !== 0) {
+ throw new Error(`production-shell ok init failed: ${initialized.stderr}`);
+ }
+}
diff --git a/packages/app/tests/stress/_helpers/reuse/lease-fixture.ts b/packages/app/tests/stress/_helpers/reuse/lease-fixture.ts
index 467a6f296..52f7b561d 100644
--- a/packages/app/tests/stress/_helpers/reuse/lease-fixture.ts
+++ b/packages/app/tests/stress/_helpers/reuse/lease-fixture.ts
@@ -11,7 +11,7 @@ import {
type WorkerServer,
warmupAppFirstLoad,
} from '../fixtures.ts';
-import { e2eServingMode } from '../prebuilt/prebuilt-serving.ts';
+import { workerServingKind } from '../prebuilt/prebuilt-serving.ts';
import { APP_PACKAGE_ROOT } from '../seed-key.ts';
import { checkCollabSync } from '../server-process.ts';
import { declareSetupNonResult } from '../setup-non-result.ts';
@@ -115,11 +115,22 @@ export async function leaseWorkerServer(
currentLease = undefined;
}
};
- if (e2eServingMode(process.env) === 'prebuilt') {
- await startFresh(
- `slot ${slot}: server reuse leases dev servers, and this invocation serves the prebuilt DEV app, so this worker starts its own server`,
- );
- return;
+ const servingKind = workerServingKind(workerServerEnv, process.env);
+ switch (servingKind) {
+ case 'production-shell':
+ await startFresh(
+ `slot ${slot}: server reuse leases dev servers, and this worker serves the production shell, so this worker starts its own server`,
+ );
+ return;
+ case 'prebuilt':
+ await startFresh(
+ `slot ${slot}: server reuse leases dev servers, and this invocation serves the prebuilt DEV app, so this worker starts its own server`,
+ );
+ return;
+ case 'dev-server':
+ break;
+ default:
+ servingKind satisfies never;
}
const run = process.env[REUSE_RUN_ENV];
if (run === undefined || run === '') {
diff --git a/packages/app/tests/stress/_helpers/reuse/owned-dev-server.ts b/packages/app/tests/stress/_helpers/reuse/owned-dev-server.ts
index 8af073b39..01e1e0c1b 100644
--- a/packages/app/tests/stress/_helpers/reuse/owned-dev-server.ts
+++ b/packages/app/tests/stress/_helpers/reuse/owned-dev-server.ts
@@ -8,7 +8,7 @@ import {
WORKER_SERVER_BUDGET_RESERVES,
waitForServerReady,
} from '../fixtures.ts';
-import type { WorkerServing } from '../prebuilt/prebuilt-serving.ts';
+import type { ModuleServing } from '../prebuilt/prebuilt-serving.ts';
import {
beginViteStartup,
closeServerLog,
@@ -34,7 +34,7 @@ export async function launchOwnedWorkerServer({
}: {
readonly label: string;
readonly workerServerEnv: WorkerServerEnv;
- readonly serving: WorkerServing;
+ readonly serving: ModuleServing;
}): Promise<OwnedServer> {
const teardown: Array<() => void | Promise<void>> = [];
let ownedProc: WorkerServerProcess | undefined;
@@ -76,6 +76,7 @@ export async function launchOwnedWorkerServer({
viteCacheDir,
serverLog,
proc,
+ serving,
}),
lifetimeLost,
]);
diff --git a/packages/app/tests/stress/_helpers/server-process.ts b/packages/app/tests/stress/_helpers/server-process.ts
index 15fb3cd23..b1831de56 100644
--- a/packages/app/tests/stress/_helpers/server-process.ts
+++ b/packages/app/tests/stress/_helpers/server-process.ts
@@ -319,7 +319,9 @@ export async function waitForBoundViteEndpoint(
return { port: receipt.port, baseURL };
}
-function endpointBaseURL(receipt: TestServerStartupReceipt): string {
+export function endpointBaseURL(
+ receipt: Pick<TestServerStartupReceipt, 'address' | 'family' | 'port'>,
+): string {
return `http://${receipt.family === 'IPv6' ? `[${receipt.address}]` : receipt.address}:${receipt.port}`;
}
@@ -369,7 +371,7 @@ async function assertViteStartupIdentity(
}
}
-function describeExit(proc: ChildProcess): string {
+export function describeExit(proc: ChildProcess): string {
return proc.signalCode === null ? `with code ${proc.exitCode}` : `on ${proc.signalCode}`;
}
diff --git a/packages/app/tests/stress/_helpers/subscribe-card.ts b/packages/app/tests/stress/_helpers/subscribe-card.ts
new file mode 100644
index 000000000..7cdb778a9
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/subscribe-card.ts
@@ -0,0 +1,25 @@
+import type { Page } from '@playwright/test';
+
+export const NEWSLETTER_KEY = 'ok-subscribe-card-v1';
+
+export interface NewsletterState {
+ readonly subscribed: boolean;
+ readonly dismissed: boolean;
+ readonly shownVersions: readonly string[];
+}
+
+export const NEWSLETTER_USED_UP: NewsletterState = {
+ subscribed: true,
+ dismissed: false,
+ shownVersions: [],
+};
+
+export async function seedNewsletterStateBeforeLoad(
+ page: Page,
+ state: NewsletterState,
+): Promise<void> {
+ await page.addInitScript(({ key, value }) => window.localStorage.setItem(key, value), {
+ key: NEWSLETTER_KEY,
+ value: JSON.stringify(state),
+ });
+}
diff --git a/packages/app/tests/stress/_helpers/worker-server-command.ts b/packages/app/tests/stress/_helpers/worker-server-command.ts
index 1465b03b0..5cda43da6 100644
--- a/packages/app/tests/stress/_helpers/worker-server-command.ts
+++ b/packages/app/tests/stress/_helpers/worker-server-command.ts
@@ -22,39 +22,61 @@ export function spawnWorkerServerCommand({
serving,
command,
}: WorkerServerLaunch): ChildProcess {
- if (serving.kind === 'prebuilt') {
- if (command === null) throw new Error('prebuilt worker server has no admitted command');
- return spawn('pnpm', [...command.args], {
- cwd: APP_PACKAGE_ROOT,
- detached: true,
- env: {
- ...process.env,
- ...workerServerEnv,
- ...request.environment,
- ...command.env,
- OK_TEST_CONTENT_DIR: contentDir,
- OK_TEST_VITE_CACHE_DIR: viteCacheDir,
- OK_TEST_SKIP_I18N_COMPILE: '1',
- OK_TEST_GIT_ENABLED: '1',
- NO_COLOR: process.env.NO_COLOR ?? '1',
- },
- stdio: ['ignore', serverLog.fd, 'inherit'],
- });
+ switch (serving.kind) {
+ case 'prebuilt': {
+ if (command === null) throw new Error('prebuilt worker server has no admitted command');
+ return spawn('pnpm', [...command.args], {
+ cwd: APP_PACKAGE_ROOT,
+ detached: true,
+ env: {
+ ...process.env,
+ ...workerServerEnv,
+ ...request.environment,
+ ...command.env,
+ OK_TEST_CONTENT_DIR: contentDir,
+ OK_TEST_VITE_CACHE_DIR: viteCacheDir,
+ OK_TEST_SKIP_I18N_COMPILE: '1',
+ OK_TEST_GIT_ENABLED: '1',
+ NO_COLOR: process.env.NO_COLOR ?? '1',
+ },
+ stdio: ['ignore', serverLog.fd, 'inherit'],
+ });
+ }
+ case 'production-shell':
+ return spawn(serving.launch.command, [...serving.launch.args], {
+ cwd: contentDir,
+ detached: true,
+ env: {
+ ...process.env,
+ ...workerServerEnv,
+ ...request.environment,
+ OK_TEST_CONTENT_DIR: contentDir,
+ OK_TEST_VITE_CACHE_DIR: viteCacheDir,
+ OK_TEST_SKIP_I18N_COMPILE: '1',
+ OK_TEST_GIT_ENABLED: '1',
+ NO_COLOR: process.env.NO_COLOR ?? '1',
+ },
+ stdio: ['ignore', serverLog.fd, 'inherit'],
+ });
+ case 'dev-server':
+ return spawn('pnpm', ['run', 'dev', '--host', request.host], {
+ cwd: APP_PACKAGE_ROOT,
+ detached: true,
+ env: {
+ ...process.env,
+ ...workerServerEnv,
+ ...request.environment,
+ OK_TEST_CONTENT_DIR: contentDir,
+ OK_TEST_VITE_CACHE_DIR: viteCacheDir,
+ OK_TEST_SKIP_I18N_COMPILE: '1',
+ OK_TEST_GIT_ENABLED: '1',
+ NO_COLOR: process.env.NO_COLOR ?? '1',
+ },
+ stdio: ['ignore', serverLog.fd, 'inherit'],
+ });
+ default:
+ throw new Error(
+ `worker server names no serving kind it can spawn: ${JSON.stringify(serving satisfies never)}`,
+ );
}
- const proc = spawn('pnpm', ['run', 'dev', '--host', request.host], {
- cwd: APP_PACKAGE_ROOT,
- detached: true,
- env: {
- ...process.env,
- ...workerServerEnv,
- ...request.environment,
- OK_TEST_CONTENT_DIR: contentDir,
- OK_TEST_VITE_CACHE_DIR: viteCacheDir,
- OK_TEST_SKIP_I18N_COMPILE: '1',
- OK_TEST_GIT_ENABLED: '1',
- NO_COLOR: process.env.NO_COLOR ?? '1',
- },
- stdio: ['ignore', serverLog.fd, 'inherit'],
- });
- return proc;
}
diff --git a/packages/app/tests/stress/_helpers/worker-server-lifetime.cjs b/packages/app/tests/stress/_helpers/worker-server-lifetime.cjs
index 253f59df3..8228a4a9a 100644
--- a/packages/app/tests/stress/_helpers/worker-server-lifetime.cjs
+++ b/packages/app/tests/stress/_helpers/worker-server-lifetime.cjs
@@ -110,7 +110,7 @@ else {
terminal = { code, signal };
send({ type: 'command-close', code, signal });
});
- send({ type: 'started' });
+ send({ type: 'started', pid: proc.pid ?? null });
} catch (error) {
send({ type: 'launch-error', message: describe(error) });
void stop().catch(() => finish());
diff --git a/packages/app/tests/stress/_helpers/worker-server-lifetime.ts b/packages/app/tests/stress/_helpers/worker-server-lifetime.ts
index 4901c7542..59d9c3cf7 100644
--- a/packages/app/tests/stress/_helpers/worker-server-lifetime.ts
+++ b/packages/app/tests/stress/_helpers/worker-server-lifetime.ts
@@ -20,6 +20,7 @@ interface Lifetime {
readonly released: Promise<void>;
readonly exited: Promise<void>;
readonly ownerExited: () => boolean;
+ readonly commandPid: () => number | undefined;
readonly reapMs: number;
}
@@ -52,7 +53,7 @@ const commandErrorSchema = z.object({
});
const lifetimeMessageSchema = z.discriminatedUnion('type', [
- z.object({ type: z.literal('started') }),
+ z.object({ type: z.literal('started'), pid: z.number().int().positive().nullable() }),
z.object({ type: z.literal('command-exit'), ...commandStatusSchema.shape }),
z.object({ type: z.literal('command-close'), ...commandStatusSchema.shape }),
z.object({
@@ -99,6 +100,7 @@ export function acquireWorkerServer(
},
);
let commandStatus: z.infer<typeof commandStatusSchema> | undefined;
+ let commandPid: number | undefined;
let nativeExitCode = proc.exitCode;
let nativeSignalCode = proc.signalCode;
Object.defineProperties(proc, {
@@ -188,6 +190,7 @@ export function acquireWorkerServer(
const message = result.data;
switch (message.type) {
case 'started':
+ commandPid = message.pid ?? undefined;
return;
case 'command-exit':
commandStatus = { code: message.code, signal: message.signal };
@@ -239,11 +242,16 @@ export function acquireWorkerServer(
released,
exited,
ownerExited: () => nativeExitCode !== null || nativeSignalCode !== null,
+ commandPid: () => commandPid,
reapMs,
});
return proc as WorkerServerProcess;
}
+export function workerServerCommandPid(proc: WorkerServerProcess): number | undefined {
+ return lifetimeOf(proc).commandPid();
+}
+
export async function stopWorkerServer(
proc: WorkerServerProcess,
timeoutMs: number,
diff --git a/packages/app/tests/stress/agent-follow-scroll.e2e.ts b/packages/app/tests/stress/agent-follow-scroll.e2e.ts
index 1c0eaf340..4320183ea 100644
--- a/packages/app/tests/stress/agent-follow-scroll.e2e.ts
+++ b/packages/app/tests/stress/agent-follow-scroll.e2e.ts
@@ -215,3 +215,38 @@ test('an agent write below the fold is still followed toward', async ({ page, ap
})
.toBeLessThanOrEqual(LANDING_TOLERANCE_BLOCKS);
});
+
+test('activating a document soon after an agent wrote below its fold follows the write', async ({
+ page,
+ api,
+}) => {
+ const name = docName('activation');
+ const { markdown } = await openTallDoc(page, api, name);
+ await drainFlash(page, 'the document under test');
+
+ await scrollWysiwygBlockToTop(page, blockMarker(0));
+ expect(await topReadableMarker(page), 'setup did not park the reader at the top').toBe(
+ blockMarker(0),
+ );
+
+ await page.evaluate((warm) => {
+ window.location.hash = `#/${warm}`;
+ }, `${name}-warm`);
+ await waitForActiveProviderSynced(page);
+ await expect
+ .poll(() => topReadableMarker(page), { message: 'the warm document never became active' })
+ .toBeNull();
+
+ const edited = bumpBlock(markdown, blockMarker(OFFSCREEN_EDIT_AT));
+ await api.writeAsAgent(name, edited, { agentId: 'follow-probe', agentName: 'FollowProbe' });
+ await page.evaluate((doc) => {
+ window.location.hash = `#/${doc}`;
+ }, name);
+
+ await expect
+ .poll(async () => Math.abs(markerIndex(await topReadableMarker(page)) - OFFSCREEN_EDIT_AT), {
+ message:
+ 'activating the document did not follow the recent off-screen agent write; the received value is how many blocks it missed by',
+ })
+ .toBeLessThanOrEqual(LANDING_TOLERANCE_BLOCKS);
+});
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 8734514d1..a3b08425e 100644
--- a/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
+++ b/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
@@ -2,20 +2,35 @@ 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 { HISTORY_PANEL_WIDTH_PX } from '../../src/hooks/use-history-presentation-mode';
+import {
+ HISTORY_DOCKED_MIN_PANE_WIDTH_PX,
+ HISTORY_PANEL_WIDTH_PX,
+} from '../../src/hooks/use-history-presentation-mode';
import { AGENTS_PANEL_WIDTH_KEY } from '../../src/lib/agents-panel-width-store';
-import { expect, servedModuleRoute, switchColorThemeAndSettleFade, test } from './_helpers';
+import {
+ contrastRatioOf,
+ expect,
+ readContrastPair,
+ servedModuleRoute,
+ stubAgentCatalog,
+ switchColorThemeAndSettleFade,
+ test,
+} from './_helpers';
const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';
-const AGENTS_REVEAL_TAB = '[data-terminal-reveal="right"]';
-const COLLAPSE_AGENT_PANEL_BUTTON = 'Collapse agent panel';
const SESSIONS_HOST_SOURCE = 'src/components/SessionsHost.tsx';
const CONFIG_RESPONSE_GLOB = '**/api/config';
const AGENTS_ORDER_STORAGE_KEY = 'ok-agent-session-order-v1';
const SEED_AGENT_ID = 'panel-level-fixture-agent';
+const SEED_AGENT_NAME = 'Panel Level Fixture';
+const REGISTERED_AGENTS_KEY = 'ok-acp-registered-agents-v1';
const BOOT_TIMEOUT_MS = 30_000;
const ROSTER_TIMEOUT_MS = 30_000;
-const EMPTY_AGENT_CATALOG = { agents: [], stale: false, maxThreads: 8 };
+const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
+const STORED_AGENTS_PANEL_WIDTH_PX = 400;
+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.';
interface ThreadFrame {
op: string;
@@ -38,91 +53,16 @@ interface RouteMark {
at: number;
}
-function relativeLuminance(channels: readonly number[]): number {
- const [red, green, blue] = channels.map((channel) => {
- const normalized = channel / 255;
- return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
- });
- return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
-}
-
-interface ContrastPair {
- foreground: readonly [number, number, number, number];
- background: readonly [number, number, number, number];
-}
-
-async function readContrastPair(foreground: Locator, background: Locator): Promise<ContrastPair> {
- const backgroundElement = await background.elementHandle();
- if (!backgroundElement) throw new Error('the contrast background locator resolved to no element');
- try {
- return await foreground.evaluate((foregroundElement, backgroundNode) => {
- const canvas = new OffscreenCanvas(1, 1);
- const context = canvas.getContext('2d', { willReadFrequently: true });
- if (!context) throw new Error('Could not create a color conversion context');
- const toBytes = (color: string): [number, number, number, number] => {
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return Array.from(context.getImageData(0, 0, 1, 1).data) as [
- number,
- number,
- number,
- number,
- ];
- };
- const foregroundColor = toBytes(getComputedStyle(foregroundElement).color);
- const layers: Array<[number, number, number, number]> = [];
- let current: Element | null = backgroundNode;
- while (current !== null) {
- const layer = toBytes(getComputedStyle(current).backgroundColor);
- layers.push(layer);
- if (layer[3] === 255) break;
- current = current.parentElement;
- }
- const base = layers.at(-1);
- if (base === undefined || base[3] !== 255) {
- throw new Error('Contrast background has no opaque ancestor');
- }
- const composite = [...base] as [number, number, number, number];
- for (let index = layers.length - 2; index >= 0; index -= 1) {
- const layer = layers[index];
- if (layer === undefined) continue;
- const alpha = layer[3] / 255;
- for (let channel = 0; channel < 3; channel += 1) {
- composite[channel] = layer[channel] * alpha + composite[channel] * (1 - alpha);
- }
- }
- return { foreground: foregroundColor, background: composite };
- }, backgroundElement);
- } finally {
- await backgroundElement.dispose();
- }
-}
-
async function expectContrast(
foreground: Locator,
background: Locator,
minimum: number,
): Promise<void> {
- const { foreground: foregroundColor, background: backgroundColor } = await readContrastPair(
- foreground,
- background,
- );
- const foregroundAlpha = foregroundColor[3] / 255;
- const composite = foregroundColor
- .slice(0, 3)
- .map(
- (channel, index) =>
- channel * foregroundAlpha + backgroundColor[index] * (1 - foregroundAlpha),
- );
- const foregroundLuminance = relativeLuminance(composite);
- const backgroundLuminance = relativeLuminance(backgroundColor.slice(0, 3));
- const ratio =
- (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) /
- (Math.min(foregroundLuminance, backgroundLuminance) + 0.05);
+ const pair = await readContrastPair(foreground, background);
+ const ratio = contrastRatioOf(pair);
expect(
ratio,
- `contrast ${ratio.toFixed(4)} is below the required ${minimum} for foreground rgba(${foregroundColor.join(', ')}) composited over background rgba(${backgroundColor.join(', ')})`,
+ `contrast ${ratio.toFixed(4)} is below the required ${minimum} for foreground rgba(${pair.foreground.join(', ')}) composited over background rgba(${pair.background.join(', ')})`,
).toBeGreaterThanOrEqual(minimum);
}
@@ -265,17 +205,41 @@ async function purgeLiveThreads(port: number): Promise<void> {
}
}
-async function seedLiveThread(port: number, contentDir: string): Promise<void> {
+function writeSeedAgentFile(contentDir: string): void {
const agentsFile = join(contentDir, '.ok', 'local', 'acp-agents.json');
mkdirSync(dirname(agentsFile), { recursive: true });
writeFileSync(
agentsFile,
`${JSON.stringify(
- [{ id: SEED_AGENT_ID, name: 'Panel Level Fixture', command: '/bin/false' }],
+ [{ id: SEED_AGENT_ID, name: SEED_AGENT_NAME, command: '/bin/false' }],
null,
2,
)}\n`,
);
+}
+
+async function registerSeedAgentAsDefault(page: Page): Promise<void> {
+ await page.addInitScript(
+ ({ key, agent }) => {
+ window.localStorage.setItem(
+ key,
+ JSON.stringify({ agents: [agent], defaultKey: `${agent.source}:${agent.id}` }),
+ );
+ },
+ {
+ key: REGISTERED_AGENTS_KEY,
+ agent: { source: 'custom', id: SEED_AGENT_ID, name: SEED_AGENT_NAME },
+ },
+ );
+}
+
+async function liveThreadCount(port: number): Promise<number> {
+ const roster = await withThreadSocket(port, latestRoster);
+ return roster.filter((thread) => thread.archived !== true).length;
+}
+
+async function seedLiveThread(port: number, contentDir: string): Promise<void> {
+ writeSeedAgentFile(contentDir);
await withThreadSocket(port, async (send, frames) => {
send({ op: 'create', reqId: 'e2e-seed-1', agent: { source: 'custom', id: SEED_AGENT_ID } });
@@ -293,10 +257,6 @@ async function seedLiveThread(port: number, contentDir: string): Promise<void> {
});
}
-async function stubAgentCatalog(page: Page): Promise<void> {
- await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: EMPTY_AGENT_CATALOG }));
-}
-
function nextRosterDelivery(page: Page, marks?: RouteMark[]): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(
@@ -327,9 +287,9 @@ function settleAfterRoster(page: Page): Promise<void> {
);
}
-async function openAppWithRoster(page: Page): Promise<void> {
+async function openAppWithRoster(page: Page, path = '/'): Promise<void> {
const roster = nextRosterDelivery(page);
- await page.goto('/');
+ await page.goto(path);
await page.waitForFunction(() => Boolean(window.__acpThreadHarness), null, {
timeout: BOOT_TIMEOUT_MS,
});
@@ -337,28 +297,67 @@ async function openAppWithRoster(page: Page): Promise<void> {
await settleAfterRoster(page);
}
-async function openAgentsPanel(page: Page): Promise<void> {
- const mount = page.locator(AGENTS_PANEL_MOUNT);
- const revealTab = page.locator(AGENTS_REVEAL_TAB);
+function agentsHeaderButton(page: Page): Locator {
+ return page.getByTestId(AGENTS_HEADER_BUTTON);
+}
+
+async function expectAgentsPanelShown(page: Page, shown: boolean): Promise<void> {
+ await expect(agentsHeaderButton(page)).toHaveAttribute('aria-pressed', String(shown), {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ if (shown) await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
+ else await expect(page.locator(AGENTS_PANEL_MOUNT)).not.toBeVisible();
+}
+
+async function expectFocusInsideAgentsPanel(page: Page): Promise<void> {
await expect
- .poll(async () => (await mount.isVisible()) || (await revealTab.isVisible()), {
- timeout: BOOT_TIMEOUT_MS,
- })
+ .poll(
+ () =>
+ page.evaluate(
+ (mount) => document.activeElement?.closest(mount) != null,
+ AGENTS_PANEL_MOUNT,
+ ),
+ { timeout: 10_000 },
+ )
.toBe(true);
- const revealed = await revealTab.isVisible();
- if (revealed) {
- await revealTab.click({ timeout: 5_000 }).catch(() => {});
- }
+}
+
+async function openInjectedThread(page: Page, title: string): Promise<void> {
+ await page.evaluate((threadTitle) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ harness.openThread({
+ agent: { id: 'header-agents-button', name: 'Header Agent', source: 'registry' },
+ title: threadTitle,
+ });
+ }, title);
+}
+
+async function showChatWithInjectedThread(page: Page, title: string): Promise<Locator> {
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, true);
+ await waitForAgentsHostSettled(page);
+ await openInjectedThread(page, title);
+ const composer = page.locator(AGENTS_PANEL_MOUNT).locator(THREAD_COMPOSER);
+ await expect(composer).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ return composer;
+}
+
+async function storeAgentsPanelWidth(page: Page, widthPx: number): Promise<void> {
+ await page.addInitScript(({ key, value }) => window.localStorage.setItem(key, value), {
+ key: AGENTS_PANEL_WIDTH_KEY,
+ value: String(widthPx),
+ });
+}
+
+async function openAgentsPanel(page: Page): Promise<void> {
+ const mount = page.locator(AGENTS_PANEL_MOUNT);
+ const button = agentsHeaderButton(page);
+ await expect(button).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ const revealed = (await button.getAttribute('aria-pressed')) !== 'true';
+ if (revealed) await button.click({ timeout: 5_000 });
await expect(mount).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
- if (revealed) {
- await expect
- .poll(
- () =>
- page.evaluate(() => document.activeElement?.closest('[data-agents-panel-mount]') != null),
- { timeout: 10_000 },
- )
- .toBe(true);
- }
+ if (revealed) await expectFocusInsideAgentsPanel(page);
await settleAfterRoster(page);
}
@@ -442,11 +441,12 @@ async function settleAgentsHostAfterReload(page: Page): Promise<void> {
await waitForAgentsHostSettled(page);
}
-async function collapseAgentsPanel(page: Page): Promise<void> {
- await page
- .getByRole('button', { name: COLLAPSE_AGENT_PANEL_BUTTON })
- .click({ timeout: BOOT_TIMEOUT_MS });
- await expect(page.locator(AGENTS_REVEAL_TAB)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+async function closeAgentsPanel(page: Page): Promise<void> {
+ await expect(agentsHeaderButton(page)).toHaveAttribute('aria-pressed', 'true', {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await agentsHeaderButton(page).click({ timeout: BOOT_TIMEOUT_MS });
+ await expectAgentsPanelShown(page, false);
await settleAfterRoster(page);
}
@@ -547,35 +547,18 @@ test.describe('agents panel resize', () => {
await settleAfterRoster(page);
const mount = page.locator(AGENTS_PANEL_MOUNT);
- const revealTab = page.locator(AGENTS_REVEAL_TAB);
- await expect
- .poll(async () => (await mount.isVisible()) || (await revealTab.isVisible()), {
- timeout: BOOT_TIMEOUT_MS,
- })
- .toBe(true);
- if (await revealTab.isVisible()) await revealTab.click();
- await expect(mount).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
- await waitForAgentsHostSettled(page);
- await expect(mount.getByRole('tab')).toHaveCount(0);
-
- 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();
- await page.keyboard.press('Home');
- await expect(mount).not.toBeVisible();
- await expect(revealTab).toBeVisible();
+ const button = agentsHeaderButton(page);
+ await expect(button).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ if ((await button.getAttribute('aria-pressed')) === 'true') await button.click();
+ await expectAgentsPanelShown(page, false);
- await revealTab.focus();
- await expect(revealTab).toBeFocused();
+ await button.focus();
+ await expect(button).toBeFocused();
await page.keyboard.press('Enter');
- await expect(mount).toBeVisible();
- await expect(revealTab).not.toBeVisible();
- await expect
- .poll(() =>
- page.evaluate(() => document.activeElement?.closest('[data-agents-panel-mount]') != null),
- )
- .toBe(true);
+ await expectAgentsPanelShown(page, true);
+ await waitForAgentsHostSettled(page);
+ await expect(mount.getByRole('tab')).toHaveCount(0);
+ await expectFocusInsideAgentsPanel(page);
});
test('release bands, cancellation, keyboard resizing, reveal, and reload preserve the settled contract', async ({
@@ -626,8 +609,7 @@ test.describe('agents panel resize', () => {
const closeTransientWidth = await dragAgentsPanel(page, 100);
expect(closeTransientWidth).toBeLessThan(160);
- await expect(mount).not.toBeVisible();
- await expect(page.locator(AGENTS_REVEAL_TAB)).toBeVisible();
+ await expectAgentsPanelShown(page, false);
await expect.poll(() => persistedAgentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
await openAgentsPanel(page);
@@ -638,6 +620,121 @@ test.describe('agents panel resize', () => {
});
});
+test.describe('header Agents button', () => {
+ test.afterEach(async ({ page, workerServer }) => {
+ await page.evaluate(() => window.__acpThreadHarness?.reset());
+ await purgeLiveThreads(workerServer.port);
+ });
+
+ test('clicking Agents while chat is hidden shows it at its stored width with focus inside it', async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await storeAgentsPanelWidth(page, STORED_AGENTS_PANEL_WIDTH_PX);
+ await stubAgentCatalog(page);
+ await openAppWithRoster(page);
+ await expectAgentsPanelShown(page, false);
+
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, true);
+ await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(STORED_AGENTS_PANEL_WIDTH_PX, -1);
+ await expectFocusInsideAgentsPanel(page);
+ });
+
+ test('an empty chat shown from Agents starts exactly one conversation', async ({
+ page,
+ workerServer,
+ }) => {
+ await purgeLiveThreads(workerServer.port);
+ writeSeedAgentFile(workerServer.contentDir);
+ await registerSeedAgentAsDefault(page);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await stubAgentCatalog(page);
+ await openAppWithRoster(page);
+ await expectAgentsPanelShown(page, false);
+ const tabs = page.locator(AGENTS_PANEL_MOUNT).getByRole('tab');
+
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, true);
+ await expect(tabs).toHaveCount(1, { timeout: ROSTER_TIMEOUT_MS });
+ await expect
+ .poll(() => liveThreadCount(workerServer.port), { timeout: ROSTER_TIMEOUT_MS })
+ .toBe(1);
+
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, false);
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, true);
+ await expect(tabs).toHaveCount(1);
+ expect(await liveThreadCount(workerServer.port)).toBe(1);
+ });
+
+ test('hiding from Agents keeps focus on the button and the chat draft, by click, Enter or Space', async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await stubAgentCatalog(page);
+ await openAppWithRoster(page);
+ const button = agentsHeaderButton(page);
+ const composer = await showChatWithInjectedThread(page, 'Header draft conversation');
+ await composer.click();
+ await page.keyboard.type(HEADER_DRAFT);
+ await expect(composer).toHaveText(HEADER_DRAFT);
+
+ await button.click();
+ await expectAgentsPanelShown(page, false);
+ await expect(button).toBeFocused();
+ await button.click();
+ await expectAgentsPanelShown(page, true);
+ await expect(composer).toHaveText(HEADER_DRAFT);
+
+ for (const key of ['Enter', 'Space'] as const) {
+ await button.focus();
+ await page.keyboard.press(key);
+ await expectAgentsPanelShown(page, false);
+ await expect(button).toBeFocused();
+ await page.keyboard.press(key);
+ await expectAgentsPanelShown(page, true);
+ await expectFocusInsideAgentsPanel(page);
+ await expect(composer).toHaveText(HEADER_DRAFT);
+ }
+ });
+
+ test('with text selected, Agents only toggles chat while Cmd/Ctrl+L stages the selection', async ({
+ page,
+ api,
+ }) => {
+ const docName = `header-agents-selection-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${docName}\n\n${SELECTION_DOC_TEXT}\n` }]);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await stubAgentCatalog(page);
+ await openAppWithRoster(page, `/#/${docName}`);
+ const button = agentsHeaderButton(page);
+ const composer = await showChatWithInjectedThread(page, 'Selection destination');
+ const paragraph = page
+ .locator('.ProseMirror:not(.composer-prosemirror) p')
+ .filter({ hasText: SELECTION_DOC_TEXT });
+ const selectionPublished = page.getByTestId('editor-footer-selected-label');
+ await expect(composer).toHaveText('');
+ await button.click();
+ await expectAgentsPanelShown(page, false);
+
+ await paragraph.selectText();
+ await expect(selectionPublished).toBeVisible();
+ await button.click();
+ await expectAgentsPanelShown(page, true);
+ await expect(composer).toHaveText('');
+ await button.click();
+ await expectAgentsPanelShown(page, false);
+
+ await paragraph.selectText();
+ await expect(selectionPublished).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+l');
+ await expectAgentsPanelShown(page, true);
+ await expect(composer).toContainText(SELECTION_DOC_TEXT);
+ });
+});
+
test.describe('chat history navigation', () => {
test.afterEach(async ({ page }) => {
await page.evaluate(() => window.__acpThreadHarness?.reset());
@@ -699,6 +796,11 @@ test.describe('chat history navigation', () => {
.include('[data-testid="agent-thread-history-panel"]')
.analyze();
expect(solarizedAccessibility.violations).toEqual([]);
+ await switchColorThemeAndSettleFade(page, 'monokai');
+ const monokaiAccessibility = await new AxeBuilder({ page })
+ .include('[data-testid="agent-thread-history-panel"]')
+ .analyze();
+ expect(monokaiAccessibility.violations).toEqual([]);
await alphaRow.click();
await expect(panel.getByRole('tab', { name: /Alpha planning conversation/ })).toHaveAttribute(
@@ -906,10 +1008,7 @@ test.describe('chat history navigation', () => {
});
});
const mount = page.locator(AGENTS_PANEL_MOUNT);
- if (await page.locator(AGENTS_REVEAL_TAB).isVisible()) {
- await page.locator(AGENTS_REVEAL_TAB).click();
- }
- await expect(mount).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await openAgentsPanel(page);
await mount.getByTestId('agent-thread-history').click();
const historyPanel = page.getByTestId('agent-thread-history-panel');
await expect(historyPanel).toBeVisible();
@@ -1014,7 +1113,7 @@ test.describe('chat history navigation', () => {
).toHaveAttribute('aria-selected', 'true');
});
- test('dragging a covered agent pane closed leaves the reveal control available', async ({
+ test('a covered agent pane dragged to zero width reads off and one Agents click brings it back at its width', async ({
page,
}) => {
await page.setViewportSize({ width: 1600, height: 900 });
@@ -1030,7 +1129,8 @@ test.describe('chat history navigation', () => {
});
});
await openAgentsPanel(page);
- await resizeAgentsPanel(page, 500);
+ await dragAgentsPanel(page, 500);
+ expect(await agentsPanelWidth(page)).toBeLessThan(HISTORY_DOCKED_MIN_PANE_WIDTH_PX);
const mount = page.locator(AGENTS_PANEL_MOUNT);
await mount.getByRole('button', { name: 'Chat history' }).click();
@@ -1075,17 +1175,18 @@ test.describe('chat history navigation', () => {
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 reveal = page.locator(AGENTS_REVEAL_TAB);
- await expect(reveal).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
- await reveal.click();
- await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
- await expect(page.getByTestId('agent-thread-history-panel')).toBeVisible();
+ 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();
});
});
@@ -1094,7 +1195,7 @@ test.describe('agents panel reload visibility level', () => {
await purgeLiveThreads(workerServer.port);
});
- test('a panel closed before a roster-delayed reload stays closed after it (level written by real open and collapse clicks and asserted in localStorage before reload; storage-coercion edge cases are pinned by the co-located DOM suites)', async ({
+ test('a panel closed before a roster-delayed reload stays closed after it (level written by real open and close clicks on the header Agents button and asserted in localStorage before reload; storage-coercion edge cases are pinned by the co-located DOM suites)', async ({
page,
workerServer,
}) => {
@@ -1105,7 +1206,7 @@ test.describe('agents panel reload visibility level', () => {
await openAgentsPanel(page);
await expectPersistedPanelLevel(page, true);
- await collapseAgentsPanel(page);
+ await closeAgentsPanel(page);
await expectPersistedPanelLevel(page, false);
const marks: RouteMark[] = [];
@@ -1131,11 +1232,10 @@ test.describe('agents panel reload visibility level', () => {
await settleAgentsHostAfterReload(page);
- await expect(page.locator(AGENTS_REVEAL_TAB)).toBeVisible();
- await expect(page.locator(AGENTS_PANEL_MOUNT)).not.toBeVisible();
+ await expectAgentsPanelShown(page, false);
});
- test('a panel closed before a roster-first reload stays closed and a later thread still reveals (level written by real open and collapse clicks and asserted in localStorage before reload; storage-coercion edge cases are pinned by the co-located DOM suites)', async ({
+ test('a panel closed before a roster-first reload stays closed and a later thread still reveals (level written by real open and close clicks on the header Agents button and asserted in localStorage before reload; storage-coercion edge cases are pinned by the co-located DOM suites)', async ({
page,
workerServer,
}) => {
@@ -1146,7 +1246,7 @@ test.describe('agents panel reload visibility level', () => {
await openAgentsPanel(page);
await expectPersistedPanelLevel(page, true);
- await collapseAgentsPanel(page);
+ await closeAgentsPanel(page);
await expectPersistedPanelLevel(page, false);
const marks: RouteMark[] = [];
@@ -1168,8 +1268,7 @@ test.describe('agents panel reload visibility level', () => {
await settleAgentsHostAfterReload(page);
- await expect(page.locator(AGENTS_REVEAL_TAB)).toBeVisible();
- await expect(page.locator(AGENTS_PANEL_MOUNT)).not.toBeVisible();
+ await expectAgentsPanelShown(page, false);
await page.evaluate(() => {
const harness = window.__acpThreadHarness;
@@ -1197,8 +1296,50 @@ test.describe('agents panel reload visibility level', () => {
await reloadAndSettle(page);
- await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
- await expect(page.locator(AGENTS_REVEAL_TAB)).not.toBeVisible();
+ await expectAgentsPanelShown(page, true);
+ });
+
+ test('a panel hidden with the header Agents button stays hidden after a reload, with the button not pressed', async ({
+ page,
+ workerServer,
+ }) => {
+ await purgeLiveThreads(workerServer.port);
+ await seedLiveThread(workerServer.port, workerServer.contentDir);
+ await stubAgentCatalog(page);
+ await openAppWithRoster(page);
+ await expectAgentsPanelShown(page, false);
+
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, true);
+ await expectPersistedPanelLevel(page, true);
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, false);
+ await expectPersistedPanelLevel(page, false);
+
+ await reloadAndSettle(page);
+ await settleAgentsHostAfterReload(page);
+
+ await expectAgentsPanelShown(page, false);
+ });
+
+ test('a panel shown with the header Agents button stays shown after a reload, with the button pressed', async ({
+ page,
+ workerServer,
+ }) => {
+ await purgeLiveThreads(workerServer.port);
+ await seedLiveThread(workerServer.port, workerServer.contentDir);
+ await stubAgentCatalog(page);
+ await openAppWithRoster(page);
+ await expectAgentsPanelShown(page, false);
+
+ await agentsHeaderButton(page).click();
+ await expectAgentsPanelShown(page, true);
+ await expectPersistedPanelLevel(page, true);
+
+ await reloadAndSettle(page);
+ await settleAgentsHostAfterReload(page);
+
+ await expectAgentsPanelShown(page, true);
});
test('a panel open before a roster-first reload stays open after it (level written by a real open click and asserted in localStorage before reload; storage-coercion edge cases are pinned by the co-located DOM suites)', async ({
@@ -1232,7 +1373,6 @@ test.describe('agents panel reload visibility level', () => {
await settleAgentsHostAfterReload(page);
- await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
- await expect(page.locator(AGENTS_REVEAL_TAB)).not.toBeVisible();
+ await expectAgentsPanelShown(page, true);
});
});
diff --git a/packages/app/tests/stress/app-header-fit.e2e.ts b/packages/app/tests/stress/app-header-fit.e2e.ts
new file mode 100644
index 000000000..9b8a11bcd
--- /dev/null
+++ b/packages/app/tests/stress/app-header-fit.e2e.ts
@@ -0,0 +1,140 @@
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PICKER_LOCALES } from '@inkeep/open-knowledge-core';
+import {
+ acpCatalogBody,
+ DESKTOP_HEADER_PLATFORM_NAMES,
+ DESKTOP_HEADER_PLATFORMS,
+ type DesktopHeaderHost,
+ expect,
+ openDesktopHeader,
+ settledHeaderFit,
+ test,
+ windowControlsOf,
+} from './_helpers';
+
+const ISOLATED_HOME = mkdtempSync(join(tmpdir(), 'ok-header-fit-home-'));
+
+test.use({ workerServerEnv: { HOME: ISOLATED_HOME } });
+
+const APP_HEADER_PX = 44;
+const DESKTOP_MINIMUM_WINDOW = { width: 720, height: 480 } as const;
+const ONE_ZOOM_STEP_IN = 1.2 ** 0.5;
+const DESKTOP_MINIMUM_WINDOW_ONE_ZOOM_STEP_IN = {
+ width: Math.floor(DESKTOP_MINIMUM_WINDOW.width / ONE_ZOOM_STEP_IN),
+ height: Math.floor(DESKTOP_MINIMUM_WINDOW.height / ONE_ZOOM_STEP_IN),
+} as const;
+
+const BUILD_BADGES = '[data-testid="beta-badge"], [data-testid="instance-badge"]';
+
+const BUILDS = [
+ { key: 'stable', label: 'the stable build', host: {}, badges: false },
+ {
+ key: 'beta',
+ label: 'the Beta build with an instance badge',
+ host: { channel: 'beta', instanceLabel: 'wt-layout-header-buttons' },
+ badges: true,
+ },
+] as const;
+
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
+for (const locale of PICKER_LOCALES) {
+ test.describe(`in ${locale}`, () => {
+ test.use({ locale });
+
+ for (const platform of DESKTOP_HEADER_PLATFORMS) {
+ for (const build of BUILDS) {
+ test(`on ${DESKTOP_HEADER_PLATFORM_NAMES[platform]}, ${build.label} at the 720px minimum keeps one ${APP_HEADER_PX}px header row with the pane buttons in view`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-fit-${platform}-${build.key}-${locale.toLowerCase()}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ const host: DesktopHeaderHost = { platform, ...build.host };
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, host);
+ await expect(page.locator('html')).toHaveAttribute('lang', locale, { timeout: 15_000 });
+
+ await page.setViewportSize(DESKTOP_MINIMUM_WINDOW);
+ const fit = await settledHeaderFit(page, windowControlsOf(host));
+ expect(fit.controls).toBeGreaterThan(0);
+ expect(fit).toMatchObject({
+ top: 0,
+ height: APP_HEADER_PX,
+ outsideRow: [],
+ overlapping: [],
+ underWindowControls: [],
+ });
+
+ const header = page.locator('header[data-app-header]');
+ await expect(header.getByTestId('header-pane-divider')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-agents')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-terminal')).toBeVisible();
+
+ const leadingBadges = header.locator('[data-app-header-leading]').locator(BUILD_BADGES);
+ const trigger = header.getByTestId('header-overflow-actions-trigger');
+ const folded = (await trigger.count()) > 0;
+ if (build.badges && platform !== 'darwin') expect(folded).toBe(true);
+ const badgesFold = build.badges && folded && platform !== 'darwin';
+ if (build.badges && !badgesFold) {
+ await expect(leadingBadges).toHaveCount(2);
+ } else {
+ await expect(leadingBadges).toHaveCount(0);
+ }
+ if (!folded) return;
+
+ await trigger.click();
+ const panel = page.locator('[data-header-overflow-actions]');
+ await expect(panel).toBeVisible();
+ await expect(panel.locator('[data-testid^="header-pane-"]')).toHaveCount(0);
+ if (badgesFold) {
+ await expect(panel.getByTestId('beta-badge')).toBeVisible();
+ await expect(panel.getByTestId('instance-badge')).toBeVisible();
+ } else {
+ await expect(panel.locator(BUILD_BADGES)).toHaveCount(0);
+ }
+ });
+ }
+ }
+ });
+}
+
+test.describe('in en, zoomed in one step', () => {
+ test.use({ locale: 'en', deviceScaleFactor: ONE_ZOOM_STEP_IN });
+
+ for (const platform of DESKTOP_HEADER_PLATFORMS) {
+ for (const build of BUILDS) {
+ test(`on ${DESKTOP_HEADER_PLATFORM_NAMES[platform]}, ${build.label} at the 720px minimum zoomed in one step keeps one ${APP_HEADER_PX}px header row with the pane buttons in view`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-fit-zoom-${platform}-${build.key}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ const host: DesktopHeaderHost = { platform, ...build.host };
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, host);
+
+ await page.setViewportSize(DESKTOP_MINIMUM_WINDOW_ONE_ZOOM_STEP_IN);
+ const fit = await settledHeaderFit(page, windowControlsOf(host));
+ expect(fit.controls).toBeGreaterThan(0);
+ expect(fit).toMatchObject({
+ top: 0,
+ height: APP_HEADER_PX,
+ outsideRow: [],
+ overlapping: [],
+ underWindowControls: [],
+ });
+
+ const header = page.locator('header[data-app-header]');
+ await expect(header.getByTestId('header-pane-divider')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-agents')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-terminal')).toBeVisible();
+ });
+ }
+ }
+});
diff --git a/packages/app/tests/stress/app-header-layout.e2e.ts b/packages/app/tests/stress/app-header-layout.e2e.ts
new file mode 100644
index 000000000..8cd7a5ac1
--- /dev/null
+++ b/packages/app/tests/stress/app-header-layout.e2e.ts
@@ -0,0 +1,980 @@
+import { basename } from 'node:path';
+import type { Page } from '@playwright/test';
+import {
+ acpCatalogBody,
+ contrastRatioOf,
+ DESKTOP_HEADER_PLATFORM_NAMES,
+ DESKTOP_HEADER_PLATFORMS,
+ type DesktopHeaderHost,
+ expect,
+ MAC_WINDOW_BUTTONS_WIDTH_PX,
+ MAC_WINDOW_BUTTONS_X_PX,
+ openDesktopHeader,
+ readContrastPair,
+ settledHeaderFit,
+ settleFrames,
+ test,
+ waitForActiveProviderSynced,
+ windowControlsOf,
+} from './_helpers';
+
+const APP_HEADER_PX = 44;
+
+async function measureShell(page: Page) {
+ return await page.evaluate(() => {
+ const rectOf = (selector: string) => {
+ const el = document.querySelector(selector);
+ if (el == null) throw new Error(`measureShell: ${selector} is not in the document`);
+ const r = el.getBoundingClientRect();
+ return { top: r.top, bottom: r.bottom, right: r.right, height: r.height };
+ };
+ return {
+ innerWidth: window.innerWidth,
+ innerHeight: window.innerHeight,
+ scrollHeight: document.documentElement.scrollHeight,
+ clientHeight: document.documentElement.clientHeight,
+ header: rectOf('header[data-app-header]'),
+ shell: rectOf('[data-slot="sidebar-wrapper"]'),
+ fileList: rectOf('[data-slot="sidebar-container"]'),
+ editorCard: rectOf('[data-slot="pane-card"][data-pane="editor"]'),
+ tabRow: rectOf('header[data-editor-header]'),
+ filesCover: document.querySelector('[data-files-cover]')
+ ? rectOf('[data-files-cover]')
+ : null,
+ };
+ });
+}
+
+async function expectHeaderClaimsTheTop(page: Page, filesPresentation: 'cover' | 'none') {
+ const m = await measureShell(page);
+ expect(m.header).toMatchObject({ top: 0, height: APP_HEADER_PX, right: m.innerWidth });
+ expect(m.shell.top).toBe(APP_HEADER_PX);
+ expect(m.shell.bottom).toBe(m.innerHeight);
+ expect(m.editorCard.top).toBe(APP_HEADER_PX);
+ if (filesPresentation === 'none') {
+ expect(m.filesCover).toBeNull();
+ expect(m.fileList.top).toBe(APP_HEADER_PX);
+ expect(m.fileList.bottom).toBe(m.editorCard.bottom);
+ } else {
+ expect(m.filesCover).toEqual(m.editorCard);
+ }
+ expect(m.editorCard.bottom).toBeLessThanOrEqual(m.innerHeight);
+ expect(m.tabRow.top).toBe(APP_HEADER_PX);
+ expect(m.scrollHeight).toBeLessThanOrEqual(m.clientHeight);
+}
+
+async function toggleFileList(page: Page) {
+ const sidebar = page.locator('[data-slot="sidebar"]').first();
+ const before = await sidebar.getAttribute('data-state');
+ const filesCover = page.locator('[data-files-cover]');
+ if ((await filesCover.count()) > 0) await filesCover.locator('[data-files-back]').click();
+ else await page.locator('[data-sidebar="trigger"]').first().click();
+ await expect(sidebar).not.toHaveAttribute('data-state', before ?? '');
+}
+
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
+for (const viewport of [
+ { width: 1280, height: 800, filesSteps: ['none', 'none', 'none'] as const },
+ { width: 393, height: 852, filesSteps: ['none', 'cover', 'none'] as const },
+]) {
+ test(`the application header sits above the file list and the tab row at ${viewport.width}x${viewport.height}, with nothing overflowing`, async ({
+ page,
+ api,
+ }) => {
+ const name = `app-header-layout-${viewport.width}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: viewport.width, height: viewport.height });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.getByRole('banner', { name: 'Application' })).toBeVisible();
+
+ await expectHeaderClaimsTheTop(page, viewport.filesSteps[0]);
+ await toggleFileList(page);
+ await expectHeaderClaimsTheTop(page, viewport.filesSteps[1]);
+ await toggleFileList(page);
+ await expectHeaderClaimsTheTop(page, viewport.filesSteps[2]);
+ });
+}
+
+const TAB_ROW_PX = 44;
+
+test('the file list starts with its project row, which lines up with the 44px tab row', async ({
+ page,
+ api,
+}) => {
+ const name = 'app-header-project-row';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('[data-sidebar-project-row]')).toBeVisible();
+
+ const m = await page.evaluate(() => {
+ const rectOf = (selector: string) => {
+ const el = document.querySelector(selector);
+ if (el == null) throw new Error(`project row probe: ${selector} is not in the document`);
+ const r = el.getBoundingClientRect();
+ return { top: r.top, height: r.height };
+ };
+ return {
+ topBars: document.querySelectorAll(
+ '[data-slot="sidebar-container"] [data-slot="sidebar-header"]',
+ ).length,
+ fileListTop: rectOf('[data-slot="sidebar-inner"]').top,
+ projectRow: rectOf('[data-sidebar-project-row]'),
+ tabRow: rectOf('header[data-editor-header]'),
+ paneTabs: rectOf('[data-editor-pane-tabs]'),
+ };
+ });
+
+ expect(m.topBars).toBe(0);
+ expect(m.projectRow.top).toBe(m.fileListTop);
+ expect(m.projectRow.height).toBe(TAB_ROW_PX);
+ expect(m.tabRow.height).toBe(TAB_ROW_PX);
+ expect(m.paneTabs.height).toBe(TAB_ROW_PX);
+ expect(Math.abs(m.projectRow.top - m.tabRow.top)).toBeLessThanOrEqual(1);
+ expect(m.tabRow.top).toBeGreaterThanOrEqual(APP_HEADER_PX);
+});
+
+async function measureTabsAgainstEditorColumn(page: Page) {
+ return await page.evaluate(() => {
+ const find = (selector: string) => {
+ const el = document.querySelector<HTMLElement>(selector);
+ if (el == null) throw new Error(`tabs probe: ${selector} is not in the document`);
+ return el;
+ };
+ const column = find('[data-editor-workspace-column]').getBoundingClientRect();
+ const host = find('[data-editor-header-tabs]').getBoundingClientRect();
+ const strips = Array.from(document.querySelectorAll<HTMLElement>('[data-editor-pane-tabs]'));
+ const visibleStrip = strips.find((strip) =>
+ strip.checkVisibility({ visibilityProperty: true, opacityProperty: true }),
+ );
+ if (visibleStrip == null) throw new Error('tabs probe: no editor tab strip is visible');
+ const toggleElement = visibleStrip.querySelector<HTMLElement>('[data-sidebar="trigger"]');
+ const firstTab = visibleStrip.querySelector<HTMLElement>('[data-editor-tab-sortable]');
+ if (toggleElement == null || firstTab == null) {
+ throw new Error('tabs probe: the visible strip has no Files toggle or tab');
+ }
+ const toggle = toggleElement.getBoundingClientRect();
+ const chat = document.querySelector('[data-agents-panel-mount]')?.getBoundingClientRect();
+ const probeX = column.right + 4;
+ const hitPastColumn =
+ probeX < window.innerWidth
+ ? document.elementFromPoint(probeX, host.top + host.height / 2)
+ : null;
+ return {
+ columnLeft: column.left,
+ columnRight: column.right,
+ columnWidth: column.width,
+ property: Number.parseFloat(
+ find('[data-editor-area-header]').style.getPropertyValue('--editor-header-tabs-width'),
+ ),
+ hostRight: host.right,
+ stripCount: strips.length,
+ tabsPaintPastColumn: hitPastColumn?.closest('[data-editor-header-tabs]') != null,
+ toggleRight: toggle.right,
+ firstTabLeft: firstTab.getBoundingClientRect().left,
+ chatLeft: chat && chat.width > 0 ? chat.left : null,
+ };
+ });
+}
+
+function expectTabsInsideEditorColumn(
+ m: Awaited<ReturnType<typeof measureTabsAgainstEditorColumn>>,
+) {
+ expect(Math.abs(m.property - m.columnWidth)).toBeLessThanOrEqual(1);
+ expect(m.hostRight).toBeLessThanOrEqual(m.columnRight + 1);
+ expect(m.tabsPaintPastColumn).toBe(false);
+ expect(m.firstTabLeft).toBeGreaterThanOrEqual(m.toggleRight);
+ if (m.chatLeft !== null) expect(m.hostRight).toBeLessThanOrEqual(m.chatLeft + 1);
+}
+
+test('the tabs stop at the editor column edge with the chat panel open and with the editor split', async ({
+ page,
+ api,
+}) => {
+ const first = 'app-header-tabs-bound-a';
+ const second = 'app-header-tabs-bound-b';
+ await api.seedDocs([
+ { name: first, markdown: `# ${first}\n\nbody\n` },
+ { name: second, markdown: `# ${second}\n\nbody\n` },
+ ]);
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+
+ const chat = page.locator('[data-agents-panel-mount]');
+ const agentsButton = page.getByTestId('header-pane-button-agents');
+ await expect(agentsButton).toBeVisible({ timeout: 30_000 });
+ if ((await agentsButton.getAttribute('aria-pressed')) !== 'true') await agentsButton.click();
+ await expect(agentsButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(chat).toBeVisible({ timeout: 30_000 });
+ await settleFrames(page);
+
+ const withChat = await measureTabsAgainstEditorColumn(page);
+ expect(withChat.chatLeft).not.toBeNull();
+ expectTabsInsideEditorColumn(withChat);
+
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${second}.md`, exact: true })
+ .click();
+ await waitForActiveProviderSynced(page);
+ const secondTab = page.locator(
+ `[data-editor-pane-focused] [data-editor-tab-sortable][data-editor-tab-id="${second}"]`,
+ );
+ if ((await secondTab.getAttribute('data-preview-tab')) === 'true') {
+ await secondTab.click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-keep-open').click();
+ }
+ await secondTab.focus();
+ await secondTab.press('Shift+F10');
+ await page.getByTestId('editor-tab-context-split-right').click();
+ await expect(page.locator('[data-editor-pane-tabs]')).toHaveCount(2);
+ await settleFrames(page);
+
+ const split = await measureTabsAgainstEditorColumn(page);
+ expect(split.stripCount).toBe(2);
+ expectTabsInsideEditorColumn(split);
+ await expect(
+ page.locator('[data-editor-pane-tabs] [data-sidebar="trigger"]'),
+ 'only the first pane tab row carries the file list toggle',
+ ).toHaveCount(1);
+
+ await page.setViewportSize({ width: 1100, height: 900 });
+ await expect(async () => {
+ expectTabsInsideEditorColumn(await measureTabsAgainstEditorColumn(page));
+ }).toPass({ timeout: 5_000 });
+});
+
+test('a connection banner paints below the application header', async ({ page, api }) => {
+ const name = 'app-header-layout-banner';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.route('**/api/config*', (route) => route.fulfill({ status: 503, body: 'down' }));
+ await page.goto(`/#/${name}`);
+
+ const banner = page.getByRole('status').filter({ hasText: 'waiting for collab server' });
+ await expect(banner).toBeVisible();
+ const header = await page.locator('header[data-app-header]').boundingBox();
+ const bannerBox = await banner.boundingBox();
+ expect(header?.y).toBe(0);
+ expect(bannerBox?.y).toBeGreaterThanOrEqual((header?.y ?? 0) + (header?.height ?? 0));
+});
+
+test('the application header takes the shell chrome surface on web and under Electron vibrancy', async ({
+ page,
+ api,
+}) => {
+ const name = 'app-header-layout-surface';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ const surfaces = () =>
+ page.evaluate(() => {
+ const bg = (selector: string) => {
+ const el = document.querySelector(selector);
+ if (el == null) throw new Error(`surfaces: ${selector} is not in the document`);
+ return getComputedStyle(el).backgroundColor;
+ };
+ return {
+ header: bg('header[data-app-header]'),
+ shell: bg('[data-slot="sidebar-wrapper"]'),
+ };
+ });
+
+ const web = await surfaces();
+ expect(web.header).toBe(web.shell);
+
+ await page.evaluate(() => document.documentElement.classList.add('electron-mode'));
+ const electron = await surfaces();
+ expect(electron.header).toBe(electron.shell);
+ expect(electron.header).not.toBe(web.header);
+});
+
+test('every application header control is hit-testable at its own top edge', async ({
+ page,
+ api,
+}) => {
+ const name = 'app-header-layout-hit-test';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.getByRole('banner').getByRole('button', { name: 'Search' })).toBeVisible();
+
+ const probes = await page.evaluate(() =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>(
+ 'header[data-app-header] :is(button:not(:disabled), a[href])',
+ ),
+ ).map((control) => {
+ const rect = control.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + 0.5);
+ return {
+ name: control.getAttribute('aria-label') ?? control.textContent ?? '',
+ hitsItself: hit !== null && control.contains(hit),
+ };
+ }),
+ );
+
+ expect(probes.length).toBeGreaterThan(0);
+ expect(probes.filter((probe) => !probe.hitsItself)).toEqual([]);
+});
+
+test('keyboard focus reaches the application header before the file list and the tabs', async ({
+ page,
+ api,
+}) => {
+ const name = 'app-header-layout-tab-order';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.getByRole('banner').getByRole('button', { name: 'Search' })).toBeVisible();
+
+ await page.evaluate(() => {
+ (document.activeElement as HTMLElement | null)?.blur();
+ });
+ const zones: string[] = [];
+ for (let press = 0; press < 40; press += 1) {
+ await page.keyboard.press('Tab');
+ zones.push(
+ await page.evaluate(() => {
+ const focused = document.activeElement;
+ if (focused == null || focused === document.body) return 'none';
+ if (focused.closest('header[data-app-header]')) return 'app-header';
+ if (focused.closest('[data-slot="sidebar"]')) return 'file-list';
+ if (focused.closest('header[data-editor-header]')) return 'tab-row';
+ return 'other';
+ }),
+ );
+ if (zones.includes('file-list') && zones.includes('tab-row')) break;
+ }
+
+ const firstHeader = zones.indexOf('app-header');
+ const lastHeader = zones.lastIndexOf('app-header');
+ expect(firstHeader).toBe(0);
+ expect(zones.indexOf('file-list')).toBeGreaterThan(lastHeader);
+ expect(zones.indexOf('tab-row')).toBeGreaterThan(lastHeader);
+});
+
+async function measureHeaderTracks(page: Page) {
+ return await page.evaluate(() => {
+ const find = (selector: string) => {
+ const el = document.querySelector(selector);
+ if (el == null) throw new Error(`measureHeaderTracks: ${selector} is not in the document`);
+ return el;
+ };
+ const header = find('header[data-app-header]').getBoundingClientRect();
+ const leading = find('[data-app-header-leading]');
+ const trailing = find('[data-app-header-trailing]');
+ const switcherElement = find('[data-testid="project-switcher-trigger"]') as HTMLElement;
+ const switcher = switcherElement.getBoundingClientRect();
+ const name = find('[data-testid="project-switcher-name"]') as HTMLElement;
+ const leadingRights = Array.from(leading.children).map((c) => c.getBoundingClientRect().right);
+ const trailingLefts = Array.from(trailing.children).map((c) => c.getBoundingClientRect().left);
+ return {
+ headerCentre: header.left + header.width / 2,
+ headerRight: header.right,
+ leadingLeft: leading.getBoundingClientRect().left,
+ leadingContentRight: Math.max(...leadingRights),
+ trailingRight: trailing.getBoundingClientRect().right,
+ trailingContentLeft: trailingLefts.length > 0 ? Math.min(...trailingLefts) : header.right,
+ switcher: { left: switcher.left, right: switcher.right, width: switcher.width },
+ switcherCentre: switcher.left + switcher.width / 2,
+ nameTruncated: name.scrollWidth > name.clientWidth,
+ nameOverflow: getComputedStyle(name).textOverflow,
+ switcherIconsSpill: switcherElement.scrollWidth > switcherElement.clientWidth + 1,
+ shareLeft: trailing.querySelector('[data-testid="share-button"]')?.getBoundingClientRect()
+ .left,
+ };
+ });
+}
+
+const LONG_PROJECT_NAME =
+ 'quarterly-planning-archive-with-a-name-far-longer-than-the-header-middle-track';
+
+for (const host of [
+ { label: 'a bare leading group', value: {} },
+ {
+ label: 'the beta tag and a long instance badge',
+ value: { channel: 'beta', instanceLabel: 'wt-app-header-centre-check' },
+ },
+] as const) {
+ test(`the project switcher sits at the header's centre with ${host.label}`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-switcher-centre-${host.label.length}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, host.value);
+
+ const m = await measureHeaderTracks(page);
+ expect(Math.abs(m.switcherCentre - m.headerCentre)).toBeLessThanOrEqual(1);
+ expect(m.switcher.left).toBeGreaterThanOrEqual(m.leadingContentRight);
+ });
+}
+
+test('the header controls sit midway between the window top and the editor panel, clear of the macOS window buttons', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const name = 'app-header-even-spacing';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, {});
+ const header = page.getByRole('banner', { name: 'Application' });
+ const back = header.getByRole('button', { name: 'Back' });
+ await expect(back).toBeVisible();
+ await settleFrames(page);
+
+ const headerBox = await header.boundingBox();
+ const backBox = await back.boundingBox();
+ const panelBox = await page.locator('[data-slot="sidebar-inset"]').first().boundingBox();
+ const fileListBox = await page.locator('[data-slot="sidebar-inner"]').first().boundingBox();
+ const reserve = await page.evaluate(() => {
+ const appHeader = document.querySelector('header[data-app-header]');
+ if (appHeader == null) throw new Error('even-spacing probe: the application header is missing');
+ return Number.parseFloat(
+ getComputedStyle(appHeader).getPropertyValue('--ok-titlebar-reserve-left'),
+ );
+ });
+ if (headerBox == null || backBox == null || panelBox == null || fileListBox == null) {
+ throw new Error('even-spacing probe: a measured element is not rendered');
+ }
+
+ const headerBottom = headerBox.y + headerBox.height;
+ const backCentre = backBox.y + backBox.height / 2;
+ expect(headerBox).toMatchObject({ y: 0, height: APP_HEADER_PX });
+ expect(panelBox.y).toBe(headerBottom);
+ expect(fileListBox.y).toBe(headerBottom);
+ expect(Math.abs(backCentre - headerBox.y - (panelBox.y - backCentre))).toBeLessThanOrEqual(0.5);
+ expect(reserve).toBe(78);
+ expect(backBox.x).toBe(reserve + 10);
+ expect(backBox.x - (MAC_WINDOW_BUTTONS_X_PX + MAC_WINDOW_BUTTONS_WIDTH_PX)).toBe(12);
+});
+
+test('the file list and the header keep the macOS window buttons 16px inset on both edges', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const name = 'app-header-edge-alignment';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, {});
+ await expect(page.locator('[data-sidebar-project-row]')).toBeVisible();
+ await settleFrames(page);
+
+ const m = await page.evaluate(() => {
+ const fileListIcon = document.querySelector('[data-sidebar-project-row] svg');
+ const trailingControls = document.querySelectorAll('[data-app-header-trailing] :is(button, a)');
+ const lastControl = trailingControls[trailingControls.length - 1];
+ const lastIcon = lastControl?.querySelector('svg');
+ if (fileListIcon == null || lastControl == null || lastIcon == null) {
+ throw new Error('edge probe: the file list icon or the last header icon is missing');
+ }
+ const iconBox = lastIcon.getBoundingClientRect();
+ return {
+ innerWidth: window.innerWidth,
+ fileListIconLeft: fileListIcon.getBoundingClientRect().left,
+ lastControl: lastControl.getAttribute('data-testid'),
+ lastIconRight: iconBox.right,
+ lastIconSize: { width: iconBox.width, height: iconBox.height },
+ };
+ });
+
+ expect(m.fileListIconLeft).toBe(MAC_WINDOW_BUTTONS_X_PX);
+ expect(m.lastControl).toBe('header-pane-button-terminal');
+ expect(m.lastIconSize).toEqual({ width: 16, height: 16 });
+ expect(m.innerWidth - m.lastIconRight).toBe(MAC_WINDOW_BUTTONS_X_PX);
+});
+
+test('with the file list closed, the tab row leaves no room for the macOS window buttons', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const name = 'app-header-tab-row-no-reserve';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, {});
+ const sidebar = page.locator('[data-slot="sidebar"]').first();
+ if ((await sidebar.getAttribute('data-state')) !== 'collapsed') await toggleFileList(page);
+ await expect(sidebar).toHaveAttribute('data-state', 'collapsed');
+ await settleFrames(page);
+
+ const m = await page.evaluate(() => {
+ const panel = document.querySelector('[data-slot="sidebar-inset"]');
+ const toggle = document.querySelector('header[data-editor-header] [data-sidebar="trigger"]');
+ if (panel == null || toggle == null) {
+ throw new Error('tab row probe: the editor panel or the tab row file list toggle is missing');
+ }
+ return {
+ offset: toggle.getBoundingClientRect().left - panel.getBoundingClientRect().left,
+ reserve: Number.parseFloat(
+ getComputedStyle(document.documentElement).getPropertyValue('--ok-titlebar-reserve-left'),
+ ),
+ };
+ });
+
+ expect(m.reserve).toBe(78);
+ expect(m.offset).toBeLessThan(MAC_WINDOW_BUTTONS_X_PX);
+});
+
+test('a long project name truncates in the middle track without moving either side group', async ({
+ page,
+ api,
+ workerServer,
+ context,
+}) => {
+ const name = 'app-header-switcher-long-name';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, { instanceLabel: 'wt-long-name' });
+ const short = await measureHeaderTracks(page);
+
+ const longPage = await context.newPage();
+ await longPage.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(longPage, workerServer, name, {
+ instanceLabel: 'wt-long-name',
+ projectName: LONG_PROJECT_NAME,
+ });
+ const long = await measureHeaderTracks(longPage);
+
+ expect(short.nameTruncated).toBe(false);
+ expect(long.nameTruncated).toBe(true);
+ expect(long.nameOverflow).toBe('ellipsis');
+ expect(long.switcher.width).toBeLessThanOrEqual(240);
+ expect(Math.abs(long.switcherCentre - long.headerCentre)).toBeLessThanOrEqual(1);
+ expect(long.leadingLeft).toBe(short.leadingLeft);
+ expect(long.leadingContentRight).toBe(short.leadingContentRight);
+ expect(long.trailingRight).toBe(short.trailingRight);
+ expect(long.shareLeft).toBeDefined();
+ expect(long.shareLeft).toBe(short.shareLeft);
+ await longPage.close();
+});
+
+for (const platform of DESKTOP_HEADER_PLATFORMS) {
+ test(`on ${DESKTOP_HEADER_PLATFORM_NAMES[platform]} at the narrowest editor window the project switcher gives way instead of running under the leading group, with the BETA and instance badges`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-switcher-narrow-${platform}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ const host: DesktopHeaderHost = {
+ platform,
+ channel: 'beta',
+ instanceLabel: 'wt-a-deliberately-wide-instance-badge',
+ projectName: LONG_PROJECT_NAME,
+ };
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, host);
+ await page.setViewportSize({ width: 720, height: 600 });
+
+ const fit = await settledHeaderFit(page, windowControlsOf(host));
+ expect(fit).toMatchObject({ overlapping: [], underWindowControls: [] });
+ const m = await measureHeaderTracks(page);
+ expect(m.switcher.left).toBeGreaterThanOrEqual(m.leadingContentRight);
+ expect(m.switcher.right).toBeLessThanOrEqual(m.trailingContentLeft);
+ expect(m.trailingRight).toBeLessThanOrEqual(m.headerRight);
+ expect(m.nameTruncated).toBe(true);
+
+ const header = page.locator('header[data-app-header]');
+ const leading = header.locator('[data-app-header-leading]');
+ if (platform === 'darwin') {
+ await expect(leading.getByTestId('beta-badge')).toBeVisible();
+ await expect(leading.getByTestId('instance-badge')).toBeVisible();
+ return;
+ }
+ await expect(leading.getByTestId('beta-badge')).toHaveCount(0);
+ await expect(leading.getByTestId('instance-badge')).toHaveCount(0);
+ await header.getByTestId('header-overflow-actions-trigger').click();
+ const panel = page.locator('[data-header-overflow-actions]');
+ await expect(panel.getByTestId('beta-badge')).toBeVisible();
+ await expect(panel.getByTestId('instance-badge')).toBeVisible();
+ });
+}
+
+for (const host of ['web', 'desktop'] as const) {
+ test(`on ${host} the editor footer drops the project name and names no branch outside a git repository, with the file list open and closed`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-footer-branch-${host}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ const projectName =
+ host === 'desktop' ? 'footer-branch-project' : basename(workerServer.contentDir);
+ if (host === 'desktop') {
+ await openDesktopHeader(page, workerServer, name, { projectName });
+ } else {
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ }
+
+ const footer = page.getByRole('region', { name: 'Document statistics' });
+ const states: Array<string | null> = [];
+ for (let pass = 0; pass < 2; pass += 1) {
+ states.push(await page.locator('[data-slot="sidebar"]').first().getAttribute('data-state'));
+ await expect(footer).toBeVisible();
+ await expect(footer.getByTestId('editor-footer-branch')).toHaveCount(0);
+ await expect(footer).not.toContainText(projectName);
+ await toggleFileList(page);
+ }
+ expect(new Set(states)).toEqual(new Set(['expanded', 'collapsed']));
+ });
+}
+
+for (const host of ['web', 'desktop'] as const) {
+ test(`on ${host} the trailing group holds Share, settings, resources, the divider and the pane buttons in that order, and the tab row holds none of them`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-trailing-order-${host}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ if (host === 'desktop') {
+ await openDesktopHeader(page, workerServer, name, {});
+ } else {
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ }
+
+ const trailing = page.locator('header[data-app-header] [data-app-header-trailing]');
+ const paneButtons =
+ host === 'desktop'
+ ? [
+ trailing.getByTestId('header-pane-button-agents'),
+ trailing.getByTestId('header-pane-button-terminal'),
+ ]
+ : [trailing.getByTestId('header-pane-button-agents')];
+ const controls = [
+ trailing.getByTestId('share-button'),
+ trailing.getByTestId('header-settings-button'),
+ trailing.getByRole('button', { name: 'Resources' }),
+ trailing.getByTestId('header-pane-divider'),
+ ...paneButtons,
+ ];
+ const lefts: number[] = [];
+ for (const control of controls) {
+ await expect(control).toBeVisible();
+ lefts.push((await control.boundingBox())?.x ?? Number.NaN);
+ }
+ expect(lefts).toEqual([...lefts].sort((a, b) => a - b));
+ expect(new Set(lefts).size).toBe(lefts.length);
+ if (host === 'web')
+ await expect(page.getByTestId('header-pane-button-terminal')).toHaveCount(0);
+
+ const tabRow = page.locator('header[data-editor-header]');
+ await expect(tabRow.getByTestId('share-button')).toHaveCount(0);
+ await expect(tabRow.getByTestId('header-settings-button')).toHaveCount(0);
+ await expect(tabRow.getByRole('button', { name: 'Resources' })).toHaveCount(0);
+ await expect(tabRow.locator('[data-slot="presence-bar"]')).toHaveCount(0);
+ await expect(tabRow.getByTestId('header-overflow-actions-trigger')).toHaveCount(0);
+ await expect(tabRow.locator('[data-testid^="header-pane-"]')).toHaveCount(0);
+ });
+}
+
+test('Share opens the publish dialog from the application header, clear of the header', async ({
+ page,
+ api,
+}) => {
+ const name = 'app-header-share-dialog';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+
+ await page.locator('header[data-app-header]').getByTestId('share-button').click();
+
+ const dialog = page.getByRole('dialog', { name: 'Publish to GitHub' });
+ await expect(dialog).toBeVisible();
+ const reach = await dialog.evaluate((el) => {
+ const rect = el.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + 4);
+ return {
+ top: rect.top,
+ bottom: rect.bottom,
+ innerHeight: window.innerHeight,
+ topEdgeIsDialog: hit !== null && el.contains(hit),
+ };
+ });
+ expect(reach.top).toBeGreaterThanOrEqual(0);
+ expect(reach.bottom).toBeLessThanOrEqual(reach.innerHeight);
+ expect(reach.topEdgeIsDialog).toBe(true);
+});
+
+test('narrowing the window never runs the trailing group into the project switcher; it collapses first, then comes back', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const name = 'app-header-trailing-collapse';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, {});
+ const header = page.locator('header[data-app-header]');
+ const trigger = header.getByTestId('header-overflow-actions-trigger');
+ await expect(trigger).toHaveCount(0);
+
+ let collapsedAt: number | null = null;
+ for (let width = 1280; width >= 240; width -= 20) {
+ await page.setViewportSize({ width, height: 800 });
+ await settleFrames(page);
+ const m = await measureHeaderTracks(page);
+ expect(
+ m.switcher.left,
+ `${width}px: switcher starts inside the leading group`,
+ ).toBeGreaterThanOrEqual(m.leadingContentRight - 0.5);
+ expect(
+ m.switcher.right,
+ `${width}px: switcher runs into the trailing group`,
+ ).toBeLessThanOrEqual(m.trailingContentLeft + 0.5);
+ expect(m.switcherIconsSpill, `${width}px: switcher squeezed below its icons`).toBe(false);
+ await expect(header.getByTestId('header-pane-divider')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-agents')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-terminal')).toBeVisible();
+ if ((await trigger.count()) > 0) {
+ collapsedAt = width;
+ break;
+ }
+ }
+ expect(collapsedAt, 'the trailing group never collapsed down to 240px').not.toBeNull();
+
+ for (const control of ['Back', 'Forward', 'Search']) {
+ await expect(
+ header.locator('[data-app-header-leading]').getByRole('button', { name: control }),
+ ).toBeVisible();
+ }
+ await expect(header.getByTestId('share-button')).toHaveCount(0);
+ await expect(header.getByTestId('header-settings-button')).toHaveCount(0);
+
+ await trigger.click();
+ const panel = page.locator('[data-header-overflow-actions]');
+ await expect(panel).toBeVisible();
+ await expect(panel.getByTestId('share-button')).toBeVisible();
+ await expect(panel.getByTestId('header-settings-button')).toBeVisible();
+ await expect(panel.getByRole('button', { name: 'Resources' })).toBeVisible();
+ await expect(panel.getByRole('button', { name: 'Search' })).toHaveCount(0);
+ await expect(panel.locator('[data-testid^="header-pane-"]')).toHaveCount(0);
+
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await expect(trigger).toHaveCount(0);
+ await expect(panel).toHaveCount(0);
+ const trailing = header.locator('[data-app-header-trailing]');
+ await expect(trailing.getByTestId('share-button')).toBeVisible();
+ await expect(trailing.getByTestId('header-settings-button')).toBeVisible();
+ await expect(trailing.getByRole('button', { name: 'Resources' })).toBeVisible();
+});
+
+test('on the web, narrowing from 1280px to 240px keeps the divider and the Agents button in the one-row header, outside More actions and clear of every other control', async ({
+ page,
+ api,
+}) => {
+ const name = 'app-header-web-sweep';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ const header = page.locator('header[data-app-header]');
+ const trigger = header.getByTestId('header-overflow-actions-trigger');
+ const panel = page.locator('[data-header-overflow-actions]');
+ await expect(header.getByTestId('header-pane-button-agents')).toBeVisible();
+ await expect(trigger).toHaveCount(0);
+
+ const foldedWidths: number[] = [];
+ for (let width = 1280; width >= 240; width -= 20) {
+ await page.setViewportSize({ width, height: 800 });
+ const fit = await settledHeaderFit(page, null);
+ expect(fit, `${width}px`).toMatchObject({
+ top: 0,
+ height: APP_HEADER_PX,
+ outsideRow: [],
+ overlapping: [],
+ });
+ await expect(header.getByTestId('header-pane-divider')).toBeVisible();
+ await expect(header.getByTestId('header-pane-button-agents')).toBeVisible();
+ await expect(page.getByTestId('header-pane-button-terminal')).toHaveCount(0);
+ if ((await trigger.count()) === 0) continue;
+
+ foldedWidths.push(width);
+ await trigger.click();
+ await expect(panel).toBeVisible();
+ await expect(panel.getByTestId('share-button')).toBeVisible();
+ await expect(panel.locator('[data-testid^="header-pane-"]')).toHaveCount(0);
+ await trigger.click();
+ await expect(panel).toHaveCount(0);
+ }
+ expect(foldedWidths, 'the header never folded on the way down to 240px').toContain(240);
+ expect(foldedWidths.length, 'the sweep stopped at the first fold').toBeGreaterThan(1);
+});
+
+test('a presence avatar joining the trailing group leaves the project switcher at the header centre', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const name = 'app-header-presence-centre';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, {});
+ const before = await measureHeaderTracks(page);
+
+ await api.writeAsAgent(name, `# ${name}\n\nan agent was here\n`, {
+ agentId: `app-header-centre-probe-${Date.now()}`,
+ agentName: 'Centre Probe',
+ clientName: 'claude-code',
+ });
+ await expect(
+ page.locator('header[data-app-header] [data-app-header-trailing] [data-slot="presence-bar"]'),
+ ).toBeVisible({ timeout: 30_000 });
+ await expect
+ .poll(async () => (await measureHeaderTracks(page)).trailingContentLeft, { timeout: 30_000 })
+ .toBeLessThan(before.trailingContentLeft);
+ await settleFrames(page);
+ const after = await measureHeaderTracks(page);
+
+ expect(after.trailingContentLeft).toBeLessThan(before.trailingContentLeft);
+ expect(Math.abs(before.switcherCentre - before.headerCentre)).toBeLessThanOrEqual(1);
+ expect(Math.abs(after.switcherCentre - after.headerCentre)).toBeLessThanOrEqual(1);
+});
+
+const WINDOW_BUTTONS = {
+ darwin: 'the macOS window buttons',
+ win32: 'the Windows caption buttons',
+ linux: 'the Linux window controls',
+} as const;
+
+for (const platform of DESKTOP_HEADER_PLATFORMS) {
+ for (const dir of ['ltr', 'rtl'] as const) {
+ test(`in a ${dir} interface no header control sits under ${WINDOW_BUTTONS[platform]}`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-window-buttons-${platform}-${dir}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ const host: DesktopHeaderHost = {
+ platform,
+ channel: 'beta',
+ instanceLabel: 'wt-window-buttons',
+ };
+ await openDesktopHeader(page, workerServer, name, host);
+ await page.evaluate((direction) => {
+ document.documentElement.dir = direction;
+ }, dir);
+ await expect(page.locator('html')).toHaveAttribute('dir', dir);
+
+ const fit = await settledHeaderFit(page, windowControlsOf(host));
+ expect(fit.controls).toBeGreaterThan(0);
+ expect(fit.underWindowControls).toEqual([]);
+ });
+ }
+}
+
+test('on the web the header names the open project in its centre track', async ({ page, api }) => {
+ const name = 'app-header-web-project-name';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${name}`);
+ await expect(page.locator('header[data-app-header]')).toBeVisible();
+
+ const label = page.getByTestId('web-project-name');
+ await expect(label).toBeVisible();
+ expect((await label.textContent())?.trim().length).toBeGreaterThan(0);
+
+ const centred = await page.evaluate(() => {
+ const header = document.querySelector('header[data-app-header]');
+ const el = document.querySelector('[data-testid="web-project-name"]');
+ if (!header || !el) throw new Error('web project name probe: missing header or label');
+ const h = header.getBoundingClientRect();
+ const r = el.getBoundingClientRect();
+ return {
+ offsetFromCentre: Math.abs((r.left + r.right) / 2 - (h.left + h.right) / 2),
+ insideHeader: r.top >= h.top && r.bottom <= h.bottom,
+ };
+ });
+
+ expect(centred.insideHeader).toBe(true);
+ expect(centred.offsetFromCentre).toBeLessThanOrEqual(1);
+
+ const header = page.locator('header[data-app-header]');
+ const nameText = page.getByTestId('web-project-name-label');
+ for (const colorScheme of ['light', 'dark'] as const) {
+ await page.emulateMedia({ colorScheme });
+ await expect
+ .poll(async () => contrastRatioOf(await readContrastPair(nameText, header)), {
+ message: `the project name against the ${colorScheme} header`,
+ })
+ .toBeGreaterThanOrEqual(4.5);
+ }
+});
+
+test('back, forward and search live only in the header, across collapsing and reopening the file list', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const name = 'app-header-nav-single-home';
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await openDesktopHeader(page, workerServer, name, {});
+
+ const appHeader = page.locator('header[data-app-header]');
+ const fileList = page.locator('[data-slot="sidebar-container"]');
+ const tabRow = page.locator('header[data-editor-header]');
+ const named = (name: string) => ({ name, exact: true }) as const;
+
+ const expectControlsInHeaderOnly = async () => {
+ await expect(appHeader.getByRole('button', named('Back'))).toHaveCount(1);
+ await expect(appHeader.getByRole('button', named('Forward'))).toHaveCount(1);
+ await expect(appHeader.getByRole('button', named('Search'))).toHaveCount(1);
+ await expect(page.getByRole('button', named('Back'))).toHaveCount(1);
+ await expect(page.getByRole('button', named('Forward'))).toHaveCount(1);
+ await expect(page.getByRole('button', { name: /^Search/ })).toHaveCount(1);
+ await expect(fileList.getByRole('button', named('Back'))).toHaveCount(0);
+ await expect(tabRow.getByRole('button', named('Back'))).toHaveCount(0);
+ await expect(tabRow.getByRole('button', { name: /^Search/ })).toHaveCount(0);
+ };
+
+ const controlRects = async () => {
+ const rects: Record<string, { x: number; y: number }> = {};
+ for (const label of ['Back', 'Forward', 'Search']) {
+ const box = await appHeader.getByRole('button', named(label)).boundingBox();
+ expect(box, `${label} must be on screen to compare its position`).not.toBeNull();
+ rects[label] = { x: box?.x ?? -1, y: box?.y ?? -1 };
+ }
+ return rects;
+ };
+
+ await expectControlsInHeaderOnly();
+ const seated = await controlRects();
+
+ const toggle = page.locator('[data-sidebar="trigger"]');
+ await toggle.click();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ await settleFrames(page);
+ await expectControlsInHeaderOnly();
+ expect(await controlRects(), 'closing the file list moved a header control').toEqual(seated);
+
+ await toggle.click();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ await settleFrames(page);
+ await expectControlsInHeaderOnly();
+ expect(await controlRects(), 'reopening the file list moved a header control').toEqual(seated);
+});
diff --git a/packages/app/tests/stress/app-header-locales.e2e.ts b/packages/app/tests/stress/app-header-locales.e2e.ts
new file mode 100644
index 000000000..a56cfdad2
--- /dev/null
+++ b/packages/app/tests/stress/app-header-locales.e2e.ts
@@ -0,0 +1,178 @@
+import { mkdtempSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { Page } from '@playwright/test';
+import {
+ DESKTOP_HEADER_PLATFORM_NAMES,
+ DESKTOP_HEADER_PLATFORMS,
+ type DesktopHeaderHost,
+ expect,
+ openDesktopHeader,
+ settledHeaderFit,
+ test,
+ type WindowControls,
+ waitForActiveProviderSynced,
+ windowControlsOf,
+} from './_helpers';
+
+const ISOLATED_HOME = mkdtempSync(join(tmpdir(), 'ok-header-locale-home-'));
+
+test.use({ workerServerEnv: { HOME: ISOLATED_HOME }, locale: 'pt-BR' });
+
+const APP_HEADER_PX = 44;
+
+function plainMessages(locale: string): Record<string, string> {
+ const path = fileURLToPath(new URL(`../../src/locales/${locale}/messages.json`, import.meta.url));
+ const { messages } = JSON.parse(readFileSync(path, 'utf8')) as {
+ messages: Record<string, unknown[]>;
+ };
+ const plain: Record<string, string> = {};
+ for (const [id, parts] of Object.entries(messages)) {
+ if (parts.length === 1 && typeof parts[0] === 'string') plain[id] = parts[0];
+ }
+ return plain;
+}
+
+const EN = plainMessages('en');
+
+function translate(english: string, target: Record<string, string>): string {
+ const id = Object.keys(EN).find((key) => EN[key] === english);
+ const translated = id === undefined ? undefined : target[id];
+ if (translated === undefined || translated === english) {
+ throw new Error(`"${english}" has no distinct translation in the target catalog`);
+ }
+ return translated;
+}
+
+function untranslatedEnglish(target: Record<string, string>): Set<string> {
+ const english = new Set<string>();
+ for (const [id, text] of Object.entries(EN)) {
+ if (target[id] !== undefined && target[id] !== text) english.add(text);
+ }
+ return english;
+}
+
+const LOCALES = [
+ { label: 'the pseudolocale', search: '?lang=pseudo', messages: plainMessages('pseudo') },
+ { label: 'Brazilian Portuguese', search: '', messages: plainMessages('pt-BR') },
+] as const;
+
+async function headerControlNames(page: Page): Promise<string[]> {
+ const header = page.locator('header[data-app-header]');
+ const snapshot = await header.ariaSnapshot();
+ const controls = Array.from(
+ snapshot.matchAll(/^\s*- (?:button|link)(?: "((?:[^"\\]|\\.)*)")?/gm),
+ (match) => match[1] ?? '',
+ );
+ const badges = await header.locator('[data-testid$="-badge"]').evaluateAll((elements) =>
+ elements.map((el) => {
+ const label = el.getAttribute('aria-label');
+ if (label !== null) return label;
+ const announced = el.cloneNode(true) as Element;
+ for (const hidden of announced.querySelectorAll('[aria-hidden="true"]')) hidden.remove();
+ return announced.textContent?.trim() ?? '';
+ }),
+ );
+ return [...controls, ...badges];
+}
+
+async function measureHeaderFit(page: Page) {
+ return await page.evaluate(() => {
+ const header = document.querySelector('header[data-app-header]');
+ if (!(header instanceof HTMLElement)) throw new Error('the app header is not in the document');
+ const box = header.getBoundingClientRect();
+ const labelOf = (el: Element) =>
+ el.getAttribute('aria-label') ?? el.textContent?.trim() ?? el.tagName;
+ const outside: string[] = [];
+ const wrapped: string[] = [];
+ let controls = 0;
+ for (const el of header.querySelectorAll('button, a, [data-testid$="-badge"]')) {
+ if (!(el instanceof HTMLElement) || !el.checkVisibility()) continue;
+ controls++;
+ const r = el.getBoundingClientRect();
+ if (r.top < box.top - 0.5 || r.bottom > box.bottom + 0.5) outside.push(labelOf(el));
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (!node.textContent?.trim()) continue;
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ const lines = new Set(Array.from(range.getClientRects(), (rect) => Math.round(rect.top)));
+ if (lines.size > 1) wrapped.push(labelOf(el));
+ }
+ }
+ return {
+ top: box.top,
+ height: box.height,
+ overflowsInline: header.scrollWidth > header.clientWidth + 1,
+ controls,
+ outside,
+ wrapped,
+ };
+ });
+}
+
+async function expectHeaderFitsIn(
+ page: Page,
+ messages: Record<string, string>,
+ windowControls: WindowControls | null,
+) {
+ const placement = await settledHeaderFit(page, windowControls);
+ expect(placement).toMatchObject({ overlapping: [], underWindowControls: [] });
+ const fit = await measureHeaderFit(page);
+ expect(fit.controls).toBeGreaterThan(0);
+ expect(fit).toMatchObject({
+ top: 0,
+ height: APP_HEADER_PX,
+ overflowsInline: false,
+ outside: [],
+ wrapped: [],
+ });
+
+ const names = await headerControlNames(page);
+ expect(names.length).toBeGreaterThan(0);
+ expect(names.filter((name) => name === '')).toEqual([]);
+ const english = untranslatedEnglish(messages);
+ expect(names.filter((name) => english.has(name))).toEqual([]);
+}
+
+for (const locale of LOCALES) {
+ test(`on web in ${locale.label} the header stays one ${APP_HEADER_PX}px row with every control named in that language`, async ({
+ page,
+ api,
+ }) => {
+ const name = `app-header-locale-web-${locale.search === '' ? 'pt' : 'pseudo'}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/${locale.search}#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(
+ page.getByRole('banner', { name: translate('Application', locale.messages), exact: true }),
+ ).toBeVisible({ timeout: 15_000 });
+
+ await expectHeaderFitsIn(page, locale.messages, null);
+ await page.setViewportSize({ width: 393, height: 852 });
+ await expectHeaderFitsIn(page, locale.messages, null);
+ });
+
+ for (const platform of DESKTOP_HEADER_PLATFORMS) {
+ test(`on ${DESKTOP_HEADER_PLATFORM_NAMES[platform]} desktop in ${locale.label} the header stays one ${APP_HEADER_PX}px row with every control named in that language and none under the window controls`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `app-header-locale-${platform}-${locale.search === '' ? 'pt' : 'pseudo'}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ const host: DesktopHeaderHost = { platform, channel: 'beta', instanceLabel: 'wt-locale' };
+ await openDesktopHeader(page, workerServer, name, host, locale.search);
+ await expect(
+ page.getByRole('banner', { name: translate('Application', locale.messages), exact: true }),
+ ).toBeVisible({ timeout: 15_000 });
+
+ await expectHeaderFitsIn(page, locale.messages, windowControlsOf(host));
+ await page.setViewportSize({ width: 720, height: 800 });
+ await expectHeaderFitsIn(page, locale.messages, windowControlsOf(host));
+ });
+ }
+}
diff --git a/packages/app/tests/stress/asset-click-dispatch.e2e.ts b/packages/app/tests/stress/asset-click-dispatch.e2e.ts
index ac36b0210..3f54488fa 100644
--- a/packages/app/tests/stress/asset-click-dispatch.e2e.ts
+++ b/packages/app/tests/stress/asset-click-dispatch.e2e.ts
@@ -84,7 +84,7 @@ async function clickLinkAndExpectBoard(
await page.click(linkSelector);
await expect.poll(async () => page.evaluate(() => window.location.hash)).toBe(`#/${board}`);
- await expect(page.getByRole('main', { name: 'Excalidraw canvas' })).toBeVisible({
+ await expect(page.getByRole('region', { name: 'Excalidraw canvas' })).toBeVisible({
timeout: 30_000,
});
await expect(page.getByTestId('asset-preview-open-as-text')).toHaveCount(0);
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
new file mode 100644
index 000000000..6b3838dfb
--- /dev/null
+++ b/packages/app/tests/stress/chat-explicit-hide-late-restore.e2e.ts
@@ -0,0 +1,197 @@
+import { randomUUID } from 'node:crypto';
+import type {
+ ThreadClientFrame,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type { WebSocketRoute } from '@playwright/test';
+import { 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 ({
+ page,
+ context,
+ api,
+ workerServer,
+}) => {
+ const docName = `chat-hidden-restore-${randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: '# Chat late restoration\n' }]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ const heldServerFrames: string[] = [];
+ const observedRosters: string[][] = [];
+ const createRequests: ThreadClientFrame[] = [];
+ const createdThreadIds = new Set<string>();
+ let threadSocket: WebSocketRoute | null = null;
+ let holdInitialFrames = true;
+ let releaseHost: (() => void) | undefined;
+
+ await page.addInitScript((agentId) => {
+ localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({
+ agents: [{ source: 'custom', id: agentId, name: 'Hidden activity fixture' }],
+ defaultKey: `custom:${agentId}`,
+ }),
+ );
+ }, fixture.agentId);
+ await context.routeWebSocket(/\/collab\/thread$/, (socket) => {
+ threadSocket = socket;
+ const server = socket.connectToServer();
+ socket.onMessage((message) => {
+ if (typeof message === 'string') {
+ const frame = JSON.parse(message) as ThreadClientFrame;
+ if (frame.op === 'create') createRequests.push(frame);
+ }
+ server.send(message);
+ });
+ server.onMessage((message) => {
+ if (typeof message !== 'string') {
+ socket.send(message);
+ return;
+ }
+ const frame = JSON.parse(message) as ThreadServerFrame;
+ if (frame.op === 'threads') {
+ const ids = frame.threads.map((thread) => thread.threadId);
+ observedRosters.push(ids);
+ for (const id of ids) {
+ if (id !== fixture.threadId) createdThreadIds.add(id);
+ }
+ }
+ if (frame.op === 'created' && frame.info.threadId !== fixture.threadId)
+ createdThreadIds.add(frame.info.threadId);
+ if (holdInitialFrames && (frame.op === 'threads' || frame.op === 'created'))
+ heldServerFrames.push(message);
+ else socket.send(message);
+ });
+ });
+
+ try {
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await page.goto(`/#/${docName}`);
+ 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);
+
+ await expect
+ .poll(() => observedRosters.some((ids) => ids.includes(fixture.threadId)))
+ .toBe(true);
+ await expect(button).toHaveAttribute('aria-pressed', 'false');
+ await button.click();
+ await expect.poll(panelWidth).toBeGreaterThan(250);
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }),
+ );
+ expect(createRequests).toEqual([]);
+ const initialSocket = threadSocket;
+ if (initialSocket === null) throw new Error('thread route was not established');
+ holdInitialFrames = false;
+ for (const frame of heldServerFrames) initialSocket.send(frame);
+ 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);
+
+ await button.click();
+ await expect.poll(panelWidth).toBe(0);
+ await expect(button).toHaveAttribute('aria-pressed', 'false');
+ await expect(threadTab).toHaveCount(1);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}').agentPanelVisible,
+ ),
+ )
+ .toBe(false);
+
+ let heldRequests = 0;
+ const heldHost = new Promise<void>((resolve) => {
+ releaseHost = resolve;
+ });
+ await page.route('**/src/components/SessionsHost*', async (route) => {
+ heldRequests += 1;
+ await heldHost;
+ await route.continue();
+ });
+
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await expect.poll(() => heldRequests).toBeGreaterThan(0);
+ await expect(button).toBeVisible();
+ await expect(button).toHaveAttribute('aria-pressed', 'false');
+ await expect.poll(panelWidth).toBe(0);
+
+ await page.evaluate(() => {
+ const samples: Array<{ visible: boolean; pressed: boolean }> = [];
+ const recordFrame = () => {
+ const panel = document.querySelector('[data-agents-panel-mount]');
+ const button = document.querySelector('[data-testid="header-pane-button-agents"]');
+ samples.push({
+ visible: (panel?.getBoundingClientRect().width ?? 0) > 0,
+ pressed: button?.getAttribute('aria-pressed') === 'true',
+ });
+ requestAnimationFrame(recordFrame);
+ };
+ (
+ window as Window & {
+ __qa009LateRestoreFrames?: typeof samples;
+ }
+ ).__qa009LateRestoreFrames = samples;
+ requestAnimationFrame(recordFrame);
+ });
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ (
+ window as Window & {
+ __qa009LateRestoreFrames?: Array<{ visible: boolean; pressed: boolean }>;
+ }
+ ).__qa009LateRestoreFrames?.length ?? 0,
+ ),
+ )
+ .toBeGreaterThan(0);
+
+ await button.press('ControlOrMeta+Shift+j');
+ releaseHost();
+ await expect.poll(panelWidth).toBeGreaterThan(250);
+ await expect(button).toHaveAttribute('aria-pressed', 'true');
+ await expect(threadTab).toBeVisible();
+ await threadTab.focus();
+ await expect(threadTab).toBeFocused();
+ await button.press('ControlOrMeta+Shift+j');
+ await expect.poll(panelWidth).toBeGreaterThan(250);
+ await expect(button).toHaveAttribute('aria-pressed', 'true');
+
+ const frames = await page.evaluate(
+ () =>
+ (
+ window as Window & {
+ __qa009LateRestoreFrames?: Array<{ visible: boolean; pressed: boolean }>;
+ }
+ ).__qa009LateRestoreFrames ?? [],
+ );
+ expect(frames.some((frame) => frame.visible)).toBe(true);
+ expect(frames.filter((frame) => frame.visible !== frame.pressed)).toEqual([]);
+ } finally {
+ releaseHost?.();
+ try {
+ for (const id of createdThreadIds) await fixture.closeThread(id);
+ } finally {
+ await fixture.close();
+ }
+ }
+});
diff --git a/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts b/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts
new file mode 100644
index 000000000..0aa2fc0c6
--- /dev/null
+++ b/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts
@@ -0,0 +1,325 @@
+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 { startHiddenChatAgent } from './hidden-chat-transport.test-helper';
+
+async function registerFixtureAgent(page: Page, agentId: string): Promise<void> {
+ await page.addInitScript((id) => {
+ localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({
+ agents: [{ source: 'custom', id, name: 'Hidden activity fixture' }],
+ defaultKey: `custom:${id}`,
+ }),
+ );
+ }, agentId);
+}
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', async (route) => {
+ const response = await route.fetch();
+ const catalog = (await response.json()) as AgentCatalog;
+ await route.fulfill({
+ response,
+ json: { ...catalog, agents: catalog.agents.filter((agent) => agent.source !== 'registry') },
+ });
+ });
+});
+test('Chat shortcut restores a keyboard-collapsed real thread in the same frame', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `chat-shortcut-${randomUUID()}`;
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ await api.seedDocs([{ name: docName, markdown: '# Chat shortcut fixture\n' }]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ await registerFixtureAgent(page, fixture.agentId);
+ const client = await page.context().newCDPSession(page);
+ const frames: string[] = [];
+ client.on('Page.screencastFrame', (event) => {
+ frames.push(event.data);
+ void client.send('Page.screencastFrameAck', { sessionId: event.sessionId });
+ });
+ try {
+ await page.setViewportSize({ width: 1600, height: 900 });
+ 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);
+ 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 expect(button).toHaveAttribute('aria-pressed', 'false');
+ await page.evaluate(() => {
+ const swatch = document.createElement('div');
+ Object.assign(swatch.style, {
+ position: 'fixed',
+ left: '0',
+ top: '0',
+ width: '32px',
+ height: '32px',
+ zIndex: '2147483647',
+ pointerEvents: 'none',
+ });
+ document.body.append(swatch);
+ const panel = document.querySelector('[data-agents-panel-mount]');
+ const button = document.querySelector('[data-testid="header-pane-button-agents"]');
+ const sample = () => {
+ const wide = (panel?.getBoundingClientRect().width ?? 0) > 0;
+ const pressed = button?.getAttribute('aria-pressed') === 'true';
+ swatch.style.backgroundColor = wide
+ ? pressed
+ ? 'rgb(0, 255, 0)'
+ : 'rgb(255, 0, 0)'
+ : pressed
+ ? 'rgb(255, 0, 255)'
+ : 'rgb(0, 0, 255)';
+ };
+ 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);
+ let running = true;
+ const tick = () => {
+ if (!running) return;
+ sample();
+ requestAnimationFrame(tick);
+ };
+ sample();
+ requestAnimationFrame(tick);
+ Object.assign(window, {
+ __qa009Samples: {
+ stop: () => {
+ running = false;
+ mutation.disconnect();
+ resize.disconnect();
+ swatch.remove();
+ },
+ },
+ });
+ });
+ 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(button).toHaveAttribute('aria-pressed', 'true');
+ const firstWidth = (await mount.boundingBox())?.width ?? 0;
+ await page.keyboard.press('ControlOrMeta+Shift+j');
+ await expect
+ .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
+ .toBeGreaterThan(250);
+ await expect(button).toHaveAttribute('aria-pressed', 'true');
+ await expect.poll(() => frames.length).toBeGreaterThan(1);
+ await client.send('Page.stopScreencast');
+ const samples = await page.evaluate(async (paintedFrames) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ const context = canvas.getContext('2d', { willReadFrequently: true });
+ if (!context) throw new Error('Canvas 2D context unavailable');
+ const painted: Array<{ width: number; pressed: boolean }> = [];
+ for (const frame of paintedFrames) {
+ const bytes = Uint8Array.from(atob(frame), (character) => character.charCodeAt(0));
+ const image = await createImageBitmap(new Blob([bytes], { type: 'image/png' }));
+ context.drawImage(image, 8, 8, 1, 1, 0, 0, 1, 1);
+ image.close();
+ const [red, green, blue] = context.getImageData(0, 0, 1, 1).data;
+ if (red > 200 && green < 50 && blue < 50) {
+ painted.push({ width: 1, pressed: false });
+ } else if (green > 200 && red < 50 && blue < 50) {
+ painted.push({ width: 1, pressed: true });
+ } else if (blue > 200 && red < 50 && green < 50) {
+ painted.push({ width: 0, pressed: false });
+ } else if (red > 200 && blue > 200 && green < 50) {
+ painted.push({ width: 0, pressed: true });
+ }
+ }
+ (
+ window as Window & {
+ __qa009Samples?: { stop(): void };
+ }
+ ).__qa009Samples?.stop();
+ return painted;
+ }, frames);
+ expect(samples.length).toBeGreaterThan(0);
+ expect(samples.some((sample) => sample.width > 0)).toBe(true);
+ expect(samples.filter((sample) => sample.pressed !== sample.width > 0)).toEqual([]);
+ await expect(threadTab).toHaveCount(1);
+ await threadTab.focus();
+ await expect(threadTab).toBeFocused();
+ await page.screenshot({ path: test.info().outputPath('chat-shortcut-restored.png') });
+ await test.info().attach('chat-shortcut-observations', {
+ body: JSON.stringify(
+ { docName, threadId: fixture.threadId, firstWidth, samples, pageErrors },
+ null,
+ 2,
+ ),
+ contentType: 'application/json',
+ });
+ expect(pageErrors).toEqual([]);
+ } finally {
+ await client.detach();
+ await fixture.close();
+ }
+});
+
+for (const action of [
+ 'send queued comments',
+ 'open Ask AI in a new tab',
+ '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 ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = `chat-shortcut-${randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: '# Chat reveal fixture\n' }]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ await registerFixtureAgent(page, fixture.agentId);
+ try {
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await page.goto(`/#/${docName}`);
+ 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}"]`);
+ 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(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 expect(button).toHaveAttribute('aria-pressed', 'false');
+ const originalTabIds = await tabs.evaluateAll((elements) =>
+ elements.map((element) => element.getAttribute('data-tab-id')).sort(),
+ );
+ expect(originalTabIds).toContain(fixture.threadId);
+
+ const forwardedCommentThreadId = await page.evaluate(
+ ({ action, agentId, docName }) => {
+ if (action === 'send queued comments') {
+ let forwardedThreadId: string | null = null;
+ window.addEventListener(
+ 'open-knowledge:comments-send-in-thread',
+ (event) => {
+ forwardedThreadId = (event as CustomEvent<{ threadId: string }>).detail.threadId;
+ },
+ { once: true },
+ );
+ window.dispatchEvent(
+ new CustomEvent('open-knowledge:comments-send-to-open-chat', {
+ detail: { threadIds: [] },
+ }),
+ );
+ return forwardedThreadId;
+ } else if (
+ action === 'open Ask AI in a new tab' ||
+ action === 'reuse the active thread with Ask AI'
+ ) {
+ window.dispatchEvent(
+ new CustomEvent('open-knowledge:active-terminal-input', {
+ detail: {
+ text: 'Review this document',
+ newTab: action === 'open Ask AI in a new tab',
+ submit: false,
+ target: 'agents',
+ },
+ }),
+ );
+ } else {
+ window.dispatchEvent(
+ new CustomEvent('open-knowledge:agent-thread-launch', {
+ detail: {
+ agentSource: 'custom',
+ agentId,
+ prompt: null,
+ docName,
+ titleHint: null,
+ attachments: null,
+ },
+ }),
+ );
+ }
+ return null;
+ },
+ { action, agentId: fixture.agentId, docName },
+ );
+
+ if (action === 'send queued comments') {
+ expect(forwardedCommentThreadId).toBe(fixture.threadId);
+ } else if (action === 'open Ask AI in a new tab') {
+ await expect
+ .poll(async () => {
+ const currentTabIds = await tabs.evaluateAll((elements) =>
+ elements.map((element) => element.getAttribute('data-tab-id')),
+ );
+ return {
+ retained: originalTabIds.every((id) => currentTabIds.includes(id)),
+ added: currentTabIds.filter((id) => !originalTabIds.includes(id)).length,
+ };
+ })
+ .toEqual({ retained: true, added: 1 });
+ if (originalTabIds.length === 1) await expect(tabs).toHaveCount(2);
+ } else if (action === 'reuse the active thread with Ask AI') {
+ await expect(
+ mount.getByRole('textbox', { name: 'Message Hidden activity fixture' }),
+ ).toContainText('Review this document');
+ expect(
+ await tabs.evaluateAll((elements) =>
+ elements.map((element) => element.getAttribute('data-tab-id')).sort(),
+ ),
+ ).toEqual(originalTabIds);
+ } else {
+ await expect
+ .poll(async () => {
+ const currentTabIds = await tabs.evaluateAll((elements) =>
+ elements.map((element) => element.getAttribute('data-tab-id')),
+ );
+ return {
+ retained: originalTabIds.every((id) => currentTabIds.includes(id)),
+ added: currentTabIds.filter((id) => !originalTabIds.includes(id)).length,
+ };
+ })
+ .toEqual({ retained: true, added: 1 });
+ if (originalTabIds.length === 1) await expect(tabs).toHaveCount(2);
+ }
+
+ await expect
+ .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
+ .toBeGreaterThan(250);
+ await expect(button).toHaveAttribute('aria-pressed', 'true');
+ await expect(threadTab).toBeVisible();
+ await threadTab.focus();
+ await expect(threadTab).toBeFocused();
+ } finally {
+ await fixture.close();
+ }
+ });
+}
diff --git a/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts b/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts
index 88f29b30c..29f5e0115 100644
--- a/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts
+++ b/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts
@@ -3,7 +3,7 @@ import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Page } from '@playwright/test';
import { DOCUMENT_SCROLL_HOST_SELECTOR } from '../../src/editor/document-scrollports';
-import { expect, test, toggleMode } from './_helpers';
+import { acpCatalogBody, expect, test, toggleMode } from './_helpers';
const COMPOSER_CARD = '[data-testid="bottom-composer"] > div';
const COMPOSER_INPUT = '.composer-prosemirror';
@@ -249,6 +249,9 @@ function assertLastLineStaysAboveCard(surface: Surface, before: Geometry, after:
expect(clearanceOf(after), describeTransition(surface, before, after)).toBeGreaterThan(0);
}
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
test.describe('the Ask AI composer keeps the end-of-document line visible as it grows', () => {
test.setTimeout(CASE_TIMEOUT_MS);
diff --git a/packages/app/tests/stress/composer-open-caret-reveal.e2e.ts b/packages/app/tests/stress/composer-open-caret-reveal.e2e.ts
index 376ffabb3..6308c6881 100644
--- a/packages/app/tests/stress/composer-open-caret-reveal.e2e.ts
+++ b/packages/app/tests/stress/composer-open-caret-reveal.e2e.ts
@@ -10,7 +10,7 @@ import {
type FullPageCmHost,
SCROLL_PIN_SLACK_PX,
} from '../../src/editor/document-scrollports';
-import { expect, test, toggleMode } from './_helpers';
+import { acpCatalogBody, expect, test, toggleMode } from './_helpers';
const COMPOSER_CARD = '[data-testid="bottom-composer"] > div';
const WYSIWYG_SCROLLPORT = '[data-testid="editor-scroll-container"]';
@@ -531,6 +531,9 @@ function assertCaretRevealed(result: CaseResult): void {
).toBeLessThanOrEqual(CARET_REVEAL_GAP_PX + (result.after.bottom - result.after.top));
}
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
test.describe('opening the Ask AI composer reveals the caret it would otherwise bury', () => {
test.setTimeout(CASE_TIMEOUT_MS);
diff --git a/packages/app/tests/stress/constrained-sidebar-request-routes.e2e.ts b/packages/app/tests/stress/constrained-sidebar-request-routes.e2e.ts
new file mode 100644
index 000000000..9d3a043d1
--- /dev/null
+++ b/packages/app/tests/stress/constrained-sidebar-request-routes.e2e.ts
@@ -0,0 +1,94 @@
+import { expect, test, waitForActiveProviderSynced } from './_helpers';
+
+const MARKDOWN = '# Sidebar route probe\n\nThe document survives sidebar switching.\n';
+
+test('header, shortcuts and palette switch constrained sidebars without changing stored state', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docName = `sidebar-routes-${crypto.randomUUID()}`;
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ await api.seedDocs([{ name: docName, markdown: MARKDOWN }]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '600');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const files = page.locator('[data-sidebar="trigger"]');
+ const information = page.locator('[data-doc-panel-toggle]');
+ const filesCover = page.locator('[data-files-cover]');
+ const informationCover = page.locator('[data-doc-panel-cover]');
+ const docColumn = page.locator('[data-editor-workspace-column]');
+
+ const assertDock = async (side: 'files' | 'information' | 'both') => {
+ await expect(files).toHaveAttribute('aria-expanded', String(side !== 'information'));
+ await expect(information).toHaveAttribute('aria-expanded', String(side !== 'files'));
+ await expect(filesCover).toHaveCount(0);
+ await expect(informationCover).toHaveCount(0);
+ await expect
+ .poll(async () => (await docColumn.boundingBox())?.width ?? 0)
+ .toBeGreaterThanOrEqual(300);
+ expect(
+ await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
+ ).toBe(true);
+ };
+
+ const selectFromPalette = async (query: string, testId: string) => {
+ await page.keyboard.press('ControlOrMeta+KeyK');
+ const input = page.locator('[data-slot="command-input"]');
+ await expect(input).toBeVisible();
+ await input.fill(query);
+ await page.getByTestId(testId).click();
+ await expect(input).toBeHidden();
+ };
+
+ await assertDock('both');
+ for (let cycle = 0; cycle < 2; cycle++) {
+ await page.setViewportSize({ width: 1000, height: 800 });
+ await assertDock('files');
+ await selectFromPalette('document panel', 'command-palette-toggle-doc-panel');
+ await assertDock('information');
+ await page.keyboard.press('ControlOrMeta+Alt+KeyS');
+ await assertDock('files');
+ await information.click();
+ await assertDock('information');
+ await files.click();
+ await assertDock('files');
+ await page.keyboard.press('ControlOrMeta+Alt+KeyB');
+ await assertDock('information');
+ await selectFromPalette('sidebar', 'command-palette-toggle-sidebar');
+ await assertDock('files');
+ await page.setViewportSize({ width: 560, height: 800 });
+ await expect(files).toHaveAttribute('aria-expanded', 'false');
+ await expect(information).toHaveAttribute('aria-expanded', 'false');
+ await page.keyboard.press('ControlOrMeta+Alt+KeyS');
+ await expect(filesCover).toBeVisible();
+ await expect(informationCover).toHaveCount(0);
+ await page.keyboard.press('ControlOrMeta+Alt+KeyB');
+ await expect(informationCover).toBeVisible();
+ await expect(filesCover).toHaveCount(0);
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await assertDock('both');
+ }
+
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'The document survives sidebar switching.',
+ );
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe('600');
+ expect(
+ (await page.context().cookies()).find((cookie) => cookie.name === 'sidebar_width')?.value,
+ ).toBe('288px');
+ expect(pageErrors).toEqual([]);
+ await page.screenshot({ path: test.info().outputPath('constrained-sidebar-routes-final.png') });
+});
diff --git a/packages/app/tests/stress/corner-stack-already-seen.e2e.ts b/packages/app/tests/stress/corner-stack-already-seen.e2e.ts
new file mode 100644
index 000000000..43f07fb36
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-already-seen.e2e.ts
@@ -0,0 +1,254 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ CORNER_STACK_TEST_ID,
+ expect,
+ expectDocumentOpen,
+ expectEditorHidden,
+ FEEDBACK_NUDGE_KEY,
+ feedbackCard,
+ NEWSLETTER_KEY,
+ noticeList,
+ noticeWithText,
+ openDesktopLayout,
+ openWebLayout,
+ seedFeedbackEligibleDocs,
+ setHeaderPane,
+ stubAgentCatalog,
+ test,
+ type WorkerServer,
+} from './_helpers';
+import { emitUpdateEvent, installUpdateEventOverlay } from './fixtures/update-event-overlay';
+
+const WEB_EDITOR_VISIBLE_KEY = 'ok-editor-visible-v1';
+const PAGE_LIST_READY_MEASURE = 'ok/startup/page-list-ready';
+const VERSION = '9.9.9';
+const RELEASE_URL = 'https://openknowledge.ai/changelog';
+const WIDE = { width: 1440, height: 900 } as const;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+type EditorLayout = 'editor shown' | 'editor hidden';
+
+const EDITOR_LAYOUTS: readonly EditorLayout[] = ['editor shown', 'editor hidden'];
+
+interface SavedFeedbackState {
+ readonly firstSeenAt: number | null;
+ readonly shownAt: number | null;
+ readonly dismissed: boolean;
+}
+
+interface SavedNewsletterState {
+ readonly subscribed: boolean;
+ readonly dismissed: boolean;
+ readonly shownVersions: readonly string[];
+}
+
+interface SeenFeedback {
+ readonly name: string;
+ readonly saved: (now: number) => SavedFeedbackState;
+}
+
+interface SeenNewsletter {
+ readonly name: string;
+ readonly saved: SavedNewsletterState;
+}
+
+const ELIGIBLE_FEEDBACK = (now: number): SavedFeedbackState => ({
+ firstSeenAt: now - 30 * DAY_MS,
+ shownAt: null,
+ dismissed: false,
+});
+
+const SEEN_FEEDBACK: readonly SeenFeedback[] = [
+ {
+ name: 'already shown',
+ saved: (now) => ({
+ firstSeenAt: now - 30 * DAY_MS,
+ shownAt: now - 20 * DAY_MS,
+ dismissed: false,
+ }),
+ },
+ {
+ name: 'dismissed',
+ saved: (now) => ({ firstSeenAt: now - 30 * DAY_MS, shownAt: null, dismissed: true }),
+ },
+];
+
+const USED_UP_NEWSLETTER: readonly SeenNewsletter[] = [
+ { name: 'subscribed', saved: { subscribed: true, dismissed: false, shownVersions: [] } },
+ { name: 'dismissed', saved: { subscribed: false, dismissed: true, shownVersions: [] } },
+ {
+ name: 'shown for three versions',
+ saved: { subscribed: false, dismissed: false, shownVersions: ['9.6.0', '9.7.0', '9.8.0'] },
+ },
+ {
+ name: 'already shown for this version',
+ saved: { subscribed: false, dismissed: false, shownVersions: [VERSION] },
+ },
+];
+
+function slugOf(...parts: readonly string[]): string {
+ return `corner-seen-${parts.join('-').replace(/[^a-z0-9]+/gi, '-')}-w${test.info().workerIndex}`;
+}
+
+async function seedLocalStorageBeforeLoad(page: Page, key: string, raw: string): Promise<void> {
+ await page.addInitScript(
+ ({ key, raw }) => {
+ if (window.localStorage.getItem(key) === null) window.localStorage.setItem(key, raw);
+ },
+ { key, raw },
+ );
+}
+
+async function readSavedState(page: Page, key: string): Promise<string | null> {
+ return await page.evaluate((key) => window.localStorage.getItem(key), key);
+}
+
+async function pageListSettled(page: Page): Promise<void> {
+ await expect
+ .poll(() =>
+ page.evaluate((name) => performance.getEntriesByName(name).length, PAGE_LIST_READY_MEASURE),
+ )
+ .toBe(1);
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }),
+ );
+}
+
+function anyFeedbackCard(page: Page): Locator {
+ return page.getByRole('region', { name: 'Share feedback', exact: true, includeHidden: true });
+}
+
+function anyNewsletterCard(page: Page): Locator {
+ return page.getByRole('region', { name: 'Stay in the loop', exact: true, includeHidden: true });
+}
+
+async function openWebWithSavedFeedback(
+ page: Page,
+ api: ApiHelpers,
+ slug: string,
+ layout: EditorLayout,
+ savedFeedback: string,
+): Promise<void> {
+ const docName = await seedFeedbackEligibleDocs(api, slug);
+ await seedLocalStorageBeforeLoad(page, FEEDBACK_NUDGE_KEY, savedFeedback);
+ if (layout === 'editor hidden') {
+ await seedLocalStorageBeforeLoad(page, WEB_EDITOR_VISIBLE_KEY, 'false');
+ await stubAgentCatalog(page);
+ await page.setViewportSize(WIDE);
+ await page.goto('/');
+ await expectEditorHidden(page);
+ } else {
+ await openWebLayout(page, docName, WIDE);
+ await expectDocumentOpen(page, docName);
+ }
+ await expect(page.getByTestId(CORNER_STACK_TEST_ID)).toBeAttached();
+ await pageListSettled(page);
+}
+
+async function openDesktopWithSavedNewsletter(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ layout: EditorLayout,
+ savedNewsletter: string | null,
+): Promise<void> {
+ await api.seedDocs([
+ { name: slug, markdown: `# ${slug}\n\nA document under the corner stack.\n` },
+ ]);
+ if (savedNewsletter !== null) {
+ await seedLocalStorageBeforeLoad(page, NEWSLETTER_KEY, savedNewsletter);
+ }
+ await installUpdateEventOverlay(page);
+ await openDesktopLayout(page, workerServer, slug, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ await expectDocumentOpen(page, slug);
+ if (layout === 'editor hidden') {
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ }
+ await emitUpdateEvent(page, 'onWhatsNew', { version: VERSION, releaseUrl: RELEASE_URL });
+}
+
+test.describe('corner stack: feedback already seen stays hidden', () => {
+ for (const layout of EDITOR_LAYOUTS) {
+ test(`an eligible feedback prompt shows by the time the page list is ready, ${layout}`, async ({
+ page,
+ api,
+ }) => {
+ const saved = JSON.stringify(ELIGIBLE_FEEDBACK(Date.now()));
+ await openWebWithSavedFeedback(page, api, slugOf('eligible', layout), layout, saved);
+
+ expect(await feedbackCard(page).isVisible()).toBe(true);
+ const stored = JSON.parse((await readSavedState(page, FEEDBACK_NUDGE_KEY)) ?? 'null');
+ expect(typeof stored?.shownAt).toBe('number');
+ });
+
+ for (const seen of SEEN_FEEDBACK) {
+ test(`feedback ${seen.name} is not shown again, ${layout}`, async ({ page, api }) => {
+ const saved = JSON.stringify(seen.saved(Date.now()));
+ await openWebWithSavedFeedback(page, api, slugOf(seen.name, layout), layout, saved);
+
+ await expect(anyFeedbackCard(page)).toHaveCount(0);
+ expect(await readSavedState(page, FEEDBACK_NUDGE_KEY)).toBe(saved);
+ });
+ }
+ }
+});
+
+test.describe('corner stack: used-up newsletter offers stay hidden', () => {
+ for (const layout of EDITOR_LAYOUTS) {
+ test(`with no saved newsletter state, what's new shows the newsletter card, ${layout}`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktopWithSavedNewsletter(
+ page,
+ api,
+ workerServer,
+ slugOf('fresh-newsletter', layout),
+ layout,
+ null,
+ );
+
+ await expect(
+ noticeList(page).getByRole('region', { name: 'Stay in the loop', exact: true }),
+ ).toBeVisible();
+ await expect(noticeWithText(page, `Updated to Version ${VERSION}`)).toHaveCount(0);
+ await expect
+ .poll(async () => JSON.parse((await readSavedState(page, NEWSLETTER_KEY)) ?? 'null'))
+ .toMatchObject({ shownVersions: [VERSION] });
+ });
+
+ for (const usedUp of USED_UP_NEWSLETTER) {
+ test(`newsletter ${usedUp.name} shows the plain update notice instead, ${layout}`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const saved = JSON.stringify(usedUp.saved);
+ await openDesktopWithSavedNewsletter(
+ page,
+ api,
+ workerServer,
+ slugOf(usedUp.name, layout),
+ layout,
+ saved,
+ );
+
+ const plainNotice = noticeWithText(page, `Updated to Version ${VERSION}`);
+ await expect(plainNotice).toBeVisible();
+ await expect(noticeList(page).locator(':scope > *')).toHaveCount(1);
+ await expect(anyNewsletterCard(page)).toHaveCount(0);
+ expect(await readSavedState(page, NEWSLETTER_KEY)).toBe(saved);
+ });
+ }
+ }
+});
diff --git a/packages/app/tests/stress/corner-stack-feedback.e2e.ts b/packages/app/tests/stress/corner-stack-feedback.e2e.ts
new file mode 100644
index 000000000..aaffab6e8
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-feedback.e2e.ts
@@ -0,0 +1,222 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ cornerStack,
+ cornerStackColumn,
+ EDITOR_PANE_CARD,
+ expect,
+ FLOATING_AND_HIT_TESTABLE,
+ feedbackCard,
+ placementOf,
+ REACHABLE,
+ reachOf,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ sidebarTrigger,
+ stubAgentCatalog,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
+
+const CHROME_VANILLA =
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
+ '(KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36';
+
+const EMBEDDED_HOSTS = [
+ { host: 'Cursor', userAgent: `${CHROME_VANILLA} Cursor/1.2.3` },
+ { host: 'Codex', userAgent: `${CHROME_VANILLA} Codex(Dev)/26.513.31313` },
+ { host: 'Claude', userAgent: `${CHROME_VANILLA} Claude(Canary)/1.0.0` },
+] as const;
+
+const WIDE = { width: 1440, height: 900 } as const;
+const NARROW = { width: 800, height: 900 } as const;
+const SHORT = { width: 720, height: 480 } as const;
+
+const SEND_FAILED_TOAST = 'Something went wrong sending your feedback. Please try again.';
+
+const CORS_HEADERS = {
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-methods': 'POST, OPTIONS',
+ 'access-control-allow-headers': 'content-type',
+};
+
+async function openWithEligibleFeedback(
+ page: Page,
+ api: ApiHelpers,
+ slug: string,
+ viewport: { width: number; height: number },
+): Promise<Locator> {
+ const docName = await seedFeedbackEligibleDocs(api, `${slug}-w${test.info().workerIndex}`);
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await stubAgentCatalog(page);
+ await page.setViewportSize(viewport);
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByRole('region', { name: 'Share feedback', exact: true })).toHaveCount(1);
+ return card;
+}
+
+async function expectFileSidebarCollapsed(page: Page) {
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'false');
+}
+
+test.describe('feedback card in the corner stack, web host', () => {
+ test.use({ userAgent: CHROME_VANILLA });
+
+ test('floats in the corner stack over the panes with the file sidebar open', async ({
+ page,
+ api,
+ }) => {
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-wide', WIDE);
+
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('nav#app-file-sidebar')).toBeVisible();
+ await expect(page.locator(EDITOR_PANE_CARD)).toBeVisible();
+ expect(await placementOf(card)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ });
+
+ test('holds only the feedback card when there is no desktop bridge', async ({ page, api }) => {
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-nobridge', WIDE);
+ const stack = cornerStack(page);
+
+ expect(await page.evaluate(() => 'okDesktop' in window)).toBe(false);
+ await expect(stack.getByTestId('update-notices-list')).toHaveCount(0);
+ expect(
+ await cornerStackColumn(page).evaluate((el) =>
+ Array.from(el.children).map((child) => child.getAttribute('aria-label')),
+ ),
+ ).toEqual(['Share feedback']);
+ await expect(card).toBeVisible();
+ });
+
+ test('shows without opening the file sidebar in an 800px window', async ({ page, api }) => {
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-narrow', NARROW);
+
+ await expectFileSidebarCollapsed(page);
+ expect(await placementOf(card)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ });
+
+ test('picking a rating grows the card upward from the corner', async ({ page, api }) => {
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-grow', WIDE);
+ const before = await card.boundingBox();
+ if (before === null) throw new Error('feedback card has no box before the rating');
+
+ await card.getByRole('radio', { name: 'Not great' }).click();
+ await expect(card.getByPlaceholder('Tell us more (optional)')).toBeVisible();
+
+ const after = await card.boundingBox();
+ if (after === null) throw new Error('feedback card has no box after the rating');
+ expect(Math.abs(after.y + after.height - (before.y + before.height))).toBeLessThanOrEqual(1);
+ expect(after.y).toBeLessThan(before.y);
+ expect(after.x).toBeGreaterThanOrEqual(0);
+ expect(after.y).toBeGreaterThanOrEqual(0);
+ expect(after.x + after.width).toBeLessThanOrEqual(WIDE.width);
+ expect(after.y + after.height).toBeLessThanOrEqual(WIDE.height);
+ });
+
+ test('in the smallest desktop window the expanded card keeps Close below the header and scrolls inside itself to Send', async ({
+ page,
+ api,
+ }) => {
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-short', SHORT);
+ await card.getByRole('radio', { name: 'Not great' }).click();
+ await expect(card.getByPlaceholder('Tell us more (optional)')).toBeVisible();
+
+ expect(await card.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
+ expect(await reachOf(card.getByRole('button', { name: 'Close', exact: true }))).toEqual(
+ REACHABLE,
+ );
+ expect(await reachOf(card.getByRole('radio', { name: 'Not great' }))).toEqual(REACHABLE);
+
+ const box = await card.boundingBox();
+ if (box === null) throw new Error('feedback card has no box in the short window');
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.wheel(0, 200);
+ await expect.poll(() => card.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
+
+ const send = card.getByRole('button', { name: 'Send', exact: true });
+ await send.scrollIntoViewIfNeeded();
+ expect(await reachOf(send)).toEqual(REACHABLE);
+ });
+
+ test('a click just outside the card reaches what is underneath', async ({ page, api }) => {
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-edge', WIDE);
+
+ const hits = await card.evaluate((el) => {
+ const rect = el.getBoundingClientRect();
+ const stack = el.closest('[data-testid="corner-card-stack"]');
+ const probes = {
+ above: [rect.left + rect.width / 2, rect.top - 4],
+ end: [rect.right + 4, rect.top + rect.height / 2],
+ } as const;
+ return Object.fromEntries(
+ Object.entries(probes).map(([side, [x, y]]) => {
+ const hit = document.elementFromPoint(x, y);
+ return [side, hit !== null && stack?.contains(hit) === false];
+ }),
+ );
+ });
+ expect(hits).toEqual({ above: true, end: true });
+ });
+
+ test('a failed send shows the usual error toast bottom-right and keeps the answer', async ({
+ page,
+ api,
+ }) => {
+ const sentBodies: string[] = [];
+ await page.route('**/api/feedback', async (route) => {
+ const request = route.request();
+ if (request.method() === 'OPTIONS') {
+ await route.fulfill({ status: 204, headers: CORS_HEADERS });
+ return;
+ }
+ sentBodies.push(request.postData() ?? '');
+ await route.fulfill({ status: 500, headers: CORS_HEADERS, json: { error: 'unavailable' } });
+ });
+ const card = await openWithEligibleFeedback(page, api, 'corner-feedback-fail', WIDE);
+ const draft = 'The corner card should keep this draft.';
+
+ await card.getByRole('radio', { name: 'Not great' }).click();
+ await card.getByPlaceholder('Tell us more (optional)').fill(draft);
+ await card.getByRole('button', { name: 'Send' }).click();
+
+ await expect(
+ page.locator("[data-sonner-toaster][data-x-position='right']").getByText(SEND_FAILED_TOAST),
+ ).toBeVisible();
+ expect(sentBodies).toHaveLength(1);
+ expect(JSON.parse(sentBodies[0] ?? '{}')).toMatchObject({
+ rating: 'negative',
+ message: draft,
+ source: 'proactive_card',
+ });
+ await expect(card).toBeVisible();
+ await expect(card.getByRole('radio', { name: 'Not great' })).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await expect(card.getByPlaceholder('Tell us more (optional)')).toHaveValue(draft);
+ });
+});
+
+for (const { host, userAgent } of EMBEDDED_HOSTS) {
+ test.describe(`feedback card in the corner stack, ${host} embedded host`, () => {
+ test.use({ userAgent });
+
+ test('shows while the file sidebar stays collapsed', async ({ page, api }) => {
+ const card = await openWithEligibleFeedback(
+ page,
+ api,
+ `corner-feedback-${host.toLowerCase()}`,
+ WIDE,
+ );
+
+ await expectFileSidebarCollapsed(page);
+ expect(await placementOf(card)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ });
+ });
+}
diff --git a/packages/app/tests/stress/corner-stack-geometry.e2e.ts b/packages/app/tests/stress/corner-stack-geometry.e2e.ts
new file mode 100644
index 000000000..dc858a314
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-geometry.e2e.ts
@@ -0,0 +1,392 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ arrangeTerminalAlone,
+ CORNER_STACK_TEST_ID,
+ cornerStack,
+ EDITOR_PANE_CARD,
+ expect,
+ expectDocumentOpen,
+ feedbackCard,
+ type LayoutViewport,
+ openDesktopLayout,
+ openWebLayout,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ sidebarTrigger,
+ terminalPaneCard,
+ test,
+ type WorkerServer,
+} from './_helpers';
+
+const DESK_GUTTER_PX = 8;
+const CARD_MARGIN_PX = 4;
+const STACK_INSET_PX = DESK_GUTTER_PX + CARD_MARGIN_PX;
+const STACK_WIDTH_PX = 352;
+const CORNER_PROBE_PX = STACK_INSET_PX + 12;
+const FEEDBACK_LATCH_TIMEOUT_MS = 15_000;
+
+const WIDE = { width: 1440, height: 900 } as const;
+const NARROW = { width: 800, height: 900 } as const;
+
+type Host = 'web' | 'desktop';
+
+interface Rect {
+ readonly left: number;
+ readonly top: number;
+ readonly right: number;
+ readonly bottom: number;
+ readonly width: number;
+}
+
+interface CornerSurface {
+ readonly name: string;
+ readonly slug: string;
+ readonly host: Host;
+ readonly viewport: LayoutViewport;
+ readonly selector: string;
+ readonly arrange: (page: Page) => Promise<void>;
+ readonly beforeClick: (page: Page) => Promise<void>;
+ readonly afterClick: (page: Page) => Promise<void>;
+}
+
+async function rectOf(locator: Locator): Promise<Rect> {
+ return await locator.evaluate((el) => {
+ const r = el.getBoundingClientRect();
+ return { left: r.left, top: r.top, right: r.right, bottom: r.bottom, width: r.width };
+ });
+}
+
+async function viewportOf(page: Page): Promise<LayoutViewport> {
+ return await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
+}
+
+async function startBottomInsetsOf(page: Page, locator: Locator) {
+ const [rect, viewport] = await Promise.all([rectOf(locator), viewportOf(page)]);
+ return {
+ start: Math.round(rect.left),
+ bottom: Math.round(viewport.height - rect.bottom),
+ width: Math.round(rect.width),
+ };
+}
+
+async function endBottomInsetsOf(page: Page, locator: Locator) {
+ const [rect, viewport] = await Promise.all([rectOf(locator), viewportOf(page)]);
+ return {
+ end: Math.round(viewport.width - rect.right),
+ bottom: Math.round(viewport.height - rect.bottom),
+ width: Math.round(rect.width),
+ };
+}
+
+async function insideViewport(page: Page, locator: Locator) {
+ const [rect, viewport] = await Promise.all([rectOf(locator), viewportOf(page)]);
+ return {
+ start: rect.left >= 0,
+ top: rect.top >= 0,
+ end: rect.right <= viewport.width,
+ bottom: rect.bottom <= viewport.height,
+ };
+}
+
+const INSIDE_VIEWPORT = { start: true, top: true, end: true, bottom: true };
+
+async function openLayout(
+ page: Page,
+ workerServer: WorkerServer,
+ host: Host,
+ docName: string,
+ viewport: LayoutViewport,
+): Promise<void> {
+ if (host === 'web') await openWebLayout(page, docName, viewport);
+ else
+ await openDesktopLayout(page, workerServer, docName, { viewport, terminalPlacement: 'bottom' });
+ await expectDocumentOpen(page, docName);
+}
+
+async function openWithFeedbackShowing(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ host: Host,
+ viewport: LayoutViewport,
+): Promise<Locator> {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-geometry-${slug}-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openLayout(page, workerServer, host, docName, viewport);
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+ return card;
+}
+
+async function openWithNoCard(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ host: Host,
+ viewport: LayoutViewport,
+): Promise<void> {
+ const docName = `corner-geometry-${slug}-w${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${docName}\n\nNothing in the corner.\n` }]);
+ await openLayout(page, workerServer, host, docName, viewport);
+}
+
+async function cornerHit(page: Page, surfaceSelector: string) {
+ return await page.evaluate(
+ ({ surfaceSelector, probe, stackTestId }) => {
+ const hit = document.elementFromPoint(probe, window.innerHeight - probe);
+ return {
+ inStack: hit?.closest(`[data-testid="${stackTestId}"]`) != null,
+ inSurface: hit !== null && document.querySelector(surfaceSelector)?.contains(hit) === true,
+ };
+ },
+ { surfaceSelector, probe: CORNER_PROBE_PX, stackTestId: CORNER_STACK_TEST_ID },
+ );
+}
+
+const CORNER_COVERED = { inStack: true, inSurface: false };
+const CORNER_OPEN = { inStack: false, inSurface: true };
+
+async function clickTheCorner(page: Page, surfaceSelector: string) {
+ await page.evaluate(
+ ({ surfaceSelector, stackTestId }) => {
+ const record = window as Window & { cornerClick?: { inSurface: boolean; inStack: boolean } };
+ record.cornerClick = undefined;
+ window.addEventListener(
+ 'click',
+ (event) => {
+ const target = event.target instanceof Element ? event.target : null;
+ record.cornerClick = {
+ inSurface:
+ target !== null && document.querySelector(surfaceSelector)?.contains(target) === true,
+ inStack: target?.closest(`[data-testid="${stackTestId}"]`) != null,
+ };
+ },
+ { capture: true, once: true },
+ );
+ },
+ { surfaceSelector, stackTestId: CORNER_STACK_TEST_ID },
+ );
+ const viewport = await viewportOf(page);
+ await page.mouse.click(CORNER_PROBE_PX, viewport.height - CORNER_PROBE_PX);
+ return await page.evaluate(
+ () =>
+ (window as Window & { cornerClick?: { inSurface: boolean; inStack: boolean } }).cornerClick ??
+ null,
+ );
+}
+
+async function expectEmptyStackWithoutABox(page: Page): Promise<void> {
+ const stack = page.getByTestId(CORNER_STACK_TEST_ID);
+ await expect(stack).toHaveCount(1);
+ await expect(stack).toBeHidden();
+ expect(
+ await stack.evaluate((el) => ({
+ display: getComputedStyle(el).display,
+ cards: el.querySelector('[data-testid="corner-card-stack-column"]')?.childElementCount,
+ })),
+ ).toEqual({ display: 'none', cards: 0 });
+ expect(await stack.boundingBox()).toBeNull();
+}
+
+async function expectCornerPassesClicksTo(page: Page, surface: CornerSurface): Promise<void> {
+ await expectEmptyStackWithoutABox(page);
+ expect(await cornerHit(page, surface.selector)).toEqual(CORNER_OPEN);
+ await surface.beforeClick(page);
+ expect(await clickTheCorner(page, surface.selector)).toEqual({ inSurface: true, inStack: false });
+ await surface.afterClick(page);
+}
+
+function skillsDock(page: Page): Locator {
+ return page.getByTestId('skills-dock');
+}
+
+async function terminalHoldsFocus(page: Page): Promise<boolean> {
+ return await page.evaluate(
+ (selector) => document.querySelector(selector)?.contains(document.activeElement) === true,
+ terminalPaneCard('bottom'),
+ );
+}
+
+const CORNER_SURFACES: readonly CornerSurface[] = [
+ {
+ name: 'the Skills Studio row at the bottom of the open file sidebar',
+ slug: 'skills-row',
+ host: 'web',
+ viewport: WIDE,
+ selector: '[data-testid="skills-dock"]',
+ arrange: async (page) => {
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'true');
+ await expect(skillsDock(page)).toBeVisible();
+ },
+ beforeClick: async (page) => {
+ await expect(skillsDock(page)).toHaveAttribute('data-state', 'closed');
+ },
+ afterClick: async (page) => {
+ await expect(skillsDock(page)).toHaveAttribute('data-state', 'open');
+ },
+ },
+ {
+ name: 'the editor with the file sidebar collapsed',
+ slug: 'editor',
+ host: 'web',
+ viewport: NARROW,
+ selector: EDITOR_PANE_CARD,
+ arrange: async (page) => {
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator(EDITOR_PANE_CARD)).toBeVisible();
+ },
+ beforeClick: async () => {},
+ afterClick: async () => {},
+ },
+ {
+ name: 'the bottom terminal with the editor hidden',
+ slug: 'terminal',
+ host: 'desktop',
+ viewport: WIDE,
+ selector: terminalPaneCard('bottom'),
+ arrange: (page) => arrangeTerminalAlone(page, 'bottom'),
+ beforeClick: async (page) => {
+ await page.evaluate(() => {
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ });
+ expect(await terminalHoldsFocus(page)).toBe(false);
+ },
+ afterClick: async (page) => {
+ await expect.poll(() => terminalHoldsFocus(page)).toBe(true);
+ },
+ },
+];
+
+const ANCHOR_CASES = [
+ {
+ name: 'a 720x480 desktop window',
+ slug: 'anchor-720',
+ host: 'desktop',
+ viewport: { width: 720, height: 480 },
+ },
+ { name: 'a 1440x900 web window', slug: 'anchor-1440', host: 'web', viewport: WIDE },
+] as const satisfies readonly {
+ name: string;
+ slug: string;
+ host: Host;
+ viewport: LayoutViewport;
+}[];
+
+test.describe('corner stack geometry', () => {
+ for (const { name, slug, host, viewport } of ANCHOR_CASES) {
+ test(`in ${name} the stack sits one card margin inside the desk gutter at the bottom-start corner, 22rem wide`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, slug, host, viewport);
+ const anchored = { start: STACK_INSET_PX, bottom: STACK_INSET_PX, width: STACK_WIDTH_PX };
+
+ const editorCard = await startBottomInsetsOf(page, page.locator(EDITOR_PANE_CARD));
+ expect({ start: editorCard.start, bottom: editorCard.bottom }).toEqual({
+ start: DESK_GUTTER_PX,
+ bottom: DESK_GUTTER_PX,
+ });
+ expect(await startBottomInsetsOf(page, cornerStack(page))).toEqual(anchored);
+ expect(await startBottomInsetsOf(page, card)).toEqual(anchored);
+ });
+ }
+
+ test('in a 393px phone window the card lies entirely inside the viewport', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, 'phone', 'web', {
+ width: 393,
+ height: 852,
+ });
+
+ expect(await insideViewport(page, card)).toEqual(INSIDE_VIEWPORT);
+ });
+
+ test('in a window narrower than 22rem plus both gutters the stack shrinks to stay inside it', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, 'narrowest', 'web', {
+ width: 300,
+ height: 640,
+ });
+ const stack = cornerStack(page);
+
+ expect((await rectOf(stack)).width).toBeLessThan(STACK_WIDTH_PX);
+ expect(await insideViewport(page, stack)).toEqual(INSIDE_VIEWPORT);
+ expect(await insideViewport(page, card)).toEqual(INSIDE_VIEWPORT);
+ });
+
+ test('in a right-to-left document the stack mirrors to the bottom-right corner', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openWithFeedbackShowing(page, api, workerServer, 'rtl', 'web', WIDE);
+ const stack = cornerStack(page);
+ expect((await startBottomInsetsOf(page, stack)).start).toBe(STACK_INSET_PX);
+
+ await page.evaluate(() => {
+ document.documentElement.dir = 'rtl';
+ });
+
+ await expect
+ .poll(() => endBottomInsetsOf(page, stack))
+ .toEqual({ end: STACK_INSET_PX, bottom: STACK_INSET_PX, width: STACK_WIDTH_PX });
+ expect(await page.evaluate(() => document.documentElement.dir)).toBe('rtl');
+ });
+});
+
+test.describe('an empty corner passes clicks through', () => {
+ for (const surface of CORNER_SURFACES) {
+ test(`with no card showing, a click in the corner reaches ${surface.name}`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openWithNoCard(
+ page,
+ api,
+ workerServer,
+ `empty-${surface.slug}`,
+ surface.host,
+ surface.viewport,
+ );
+ await surface.arrange(page);
+
+ await expectCornerPassesClicksTo(page, surface);
+ });
+
+ test(`after the last card is dismissed, a click in the corner reaches ${surface.name}`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(
+ page,
+ api,
+ workerServer,
+ `dismissed-${surface.slug}`,
+ surface.host,
+ surface.viewport,
+ );
+ await surface.arrange(page);
+ expect(await cornerHit(page, surface.selector)).toEqual(CORNER_COVERED);
+
+ await card.getByRole('button', { name: 'Close', exact: true }).click();
+ await expect(card).toHaveCount(0);
+
+ await expectCornerPassesClicksTo(page, surface);
+ });
+ }
+});
diff --git a/packages/app/tests/stress/corner-stack-layering.e2e.ts b/packages/app/tests/stress/corner-stack-layering.e2e.ts
new file mode 100644
index 000000000..2eebb251d
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-layering.e2e.ts
@@ -0,0 +1,247 @@
+import type { ElementHandle, Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ CORNER_STACK_TEST_ID,
+ expect,
+ expectDocumentOpen,
+ expectEditorHidden,
+ FEEDBACK_NUDGE_KEY,
+ feedbackCard,
+ identityOf,
+ openDesktopLayout,
+ openWebLayout,
+ SAME_NODE,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ setHeaderPane,
+ test,
+ type WorkerServer,
+} from './_helpers';
+import { emitOnboardingToast, installUpdateEventOverlay } from './fixtures/update-event-overlay';
+
+const WIDE = { width: 1440, height: 900 } as const;
+const FEEDBACK_LATCH_TIMEOUT_MS = 15_000;
+const SETTINGS_DIALOG_TIMEOUT_MS = 15_000;
+const MENU_OPENS_ABOVE_CARD_PX = 200;
+const MENU_OPENS_INSIDE_CARD_START_PX = 10;
+const CORNER_STACK = `[data-testid="${CORNER_STACK_TEST_ID}"]`;
+const DIALOG_LAYER = '[role="dialog"], [data-slot="dialog-overlay"]';
+const PATH_FAILURE_SUMMARY = 'could not write ~/.zshrc';
+
+type Host = 'web' | 'desktop';
+
+interface Rect {
+ readonly left: number;
+ readonly top: number;
+ readonly right: number;
+ readonly bottom: number;
+}
+
+interface Point {
+ readonly x: number;
+ readonly y: number;
+}
+
+async function rectOf(target: Locator): Promise<Rect> {
+ return await target.evaluate((el) => {
+ const r = el.getBoundingClientRect();
+ return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
+ });
+}
+
+function centerOf(rect: Rect): Point {
+ return { x: (rect.left + rect.right) / 2, y: (rect.top + rect.bottom) / 2 };
+}
+
+function overlapOf(a: Rect, b: Rect): Rect | null {
+ const overlap = {
+ left: Math.max(a.left, b.left),
+ top: Math.max(a.top, b.top),
+ right: Math.min(a.right, b.right),
+ bottom: Math.min(a.bottom, b.bottom),
+ };
+ return overlap.left < overlap.right && overlap.top < overlap.bottom ? overlap : null;
+}
+
+function contains(rect: Rect, point: Point): boolean {
+ return (
+ point.x >= rect.left && point.x <= rect.right && point.y >= rect.top && point.y <= rect.bottom
+ );
+}
+
+async function landsIn(page: Page, point: Point, selector: string): Promise<boolean> {
+ return await page.evaluate(
+ ({ x, y, selector }) => {
+ const hit = document.elementFromPoint(x, y);
+ return hit !== null && hit.closest(selector) !== null;
+ },
+ { ...point, selector },
+ );
+}
+
+async function paintsOnTopAt(page: Page, point: Point, selector: string): Promise<boolean> {
+ return await page.evaluate(
+ ({ x, y, selector }) => {
+ const body = document.body;
+ const pointerLock = body.style.pointerEvents;
+ body.style.pointerEvents = 'auto';
+ const hit = document.elementFromPoint(x, y);
+ body.style.pointerEvents = pointerLock;
+ return hit !== null && hit.closest(selector) !== null;
+ },
+ { ...point, selector },
+ );
+}
+
+async function readFeedbackDismissed(page: Page): Promise<unknown> {
+ return await page.evaluate((key) => {
+ const raw = window.localStorage.getItem(key);
+ return raw === null ? 'missing' : (JSON.parse(raw) as { dismissed?: unknown }).dismissed;
+ }, FEEDBACK_NUDGE_KEY);
+}
+
+async function openWithFeedbackShowing(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ host: Host,
+): Promise<Locator> {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-layering-${slug}-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ if (host === 'web') {
+ await openWebLayout(page, docName, WIDE);
+ } else {
+ await installUpdateEventOverlay(page);
+ await openDesktopLayout(page, workerServer, docName, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ }
+ await expectDocumentOpen(page, docName);
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+ return card;
+}
+
+async function handleOf(card: Locator): Promise<ElementHandle<Element>> {
+ const handle = await card.elementHandle();
+ if (handle === null) throw new Error('expected the showing card to resolve to an element');
+ return handle;
+}
+
+async function closeControlCenterOf(card: Locator): Promise<Point> {
+ return centerOf(await rectOf(card.getByRole('button', { name: 'Close', exact: true })));
+}
+
+test.describe('what draws over a showing card', () => {
+ test("the file sidebar's modal context menu draws over the card, and a click on the card's Close control only closes the menu", async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, 'menu', 'web');
+ const before = await handleOf(card);
+ const cardRect = await rectOf(card);
+ const closeCenter = await closeControlCenterOf(card);
+
+ await page.mouse.click(
+ cardRect.left + MENU_OPENS_INSIDE_CARD_START_PX,
+ cardRect.top - MENU_OPENS_ABOVE_CARD_PX,
+ { button: 'right' },
+ );
+ const menu = page.locator('[role="menu"]');
+ await expect(menu.getByTestId('empty-space-menu-new-file')).toBeVisible();
+ const menuRect = await rectOf(menu);
+ const overlap = overlapOf(menuRect, cardRect);
+ if (overlap === null) throw new Error('expected the context menu to overlap the card');
+ expect(await landsIn(page, centerOf(overlap), '[role="menu"]')).toBe(true);
+ expect(await paintsOnTopAt(page, centerOf(overlap), '[role="menu"]')).toBe(true);
+ expect(contains(menuRect, closeCenter)).toBe(false);
+ expect(await landsIn(page, closeCenter, CORNER_STACK)).toBe(false);
+
+ await page.mouse.click(closeCenter.x, closeCenter.y);
+
+ await expect(menu).toHaveCount(0);
+ await expect(card).toBeVisible();
+ expect(await identityOf(before, card)).toEqual(SAME_NODE);
+ expect(await readFeedbackDismissed(page)).toBe(false);
+ });
+
+ test("Settings draws its dialog layer over the card, and a click at the card's Close control leaves the card in place", async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, 'settings', 'web');
+ const before = await handleOf(card);
+ const cardCenter = centerOf(await rectOf(card));
+ const closeCenter = await closeControlCenterOf(card);
+
+ await page.getByTestId('header-settings-button').click();
+ const dialog = page.getByTestId('settings-dialog');
+ await expect(dialog).toBeVisible({ timeout: SETTINGS_DIALOG_TIMEOUT_MS });
+ expect(await landsIn(page, cardCenter, DIALOG_LAYER)).toBe(true);
+ expect(await paintsOnTopAt(page, cardCenter, DIALOG_LAYER)).toBe(true);
+ expect(await landsIn(page, closeCenter, CORNER_STACK)).toBe(false);
+
+ await page.mouse.click(closeCenter.x, closeCenter.y);
+
+ await expect(dialog).toHaveCount(0);
+ await expect(card).toBeVisible();
+ expect(await identityOf(before, card)).toEqual(SAME_NODE);
+ expect(await readFeedbackDismissed(page)).toBe(false);
+ });
+
+ test('a startup-integrations toast shows bottom-left over the card, and closing it leaves the card in place', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, 'toast', 'desktop');
+ const before = await handleOf(card);
+
+ await emitOnboardingToast(page, {
+ kind: 'startup-reclaim',
+ mcp: { status: 'none' },
+ path: { status: 'failed', summary: PATH_FAILURE_SUMMARY },
+ });
+
+ const toast = page
+ .locator('[data-sonner-toaster][data-x-position="left"][data-y-position="bottom"]')
+ .locator('[data-sonner-toast]')
+ .filter({ hasText: `PATH install failed: ${PATH_FAILURE_SUMMARY}` });
+ await expect(toast).toBeVisible();
+ await expect
+ .poll(async () => {
+ const overlap = overlapOf(await rectOf(toast), await rectOf(card));
+ return overlap !== null && (await landsIn(page, centerOf(overlap), '[data-sonner-toast]'));
+ })
+ .toBe(true);
+
+ await toast.getByRole('button', { name: 'Close toast', exact: true }).click();
+
+ await expect(toast).toHaveCount(0);
+ await expect(card).toBeVisible();
+ expect(await identityOf(before, card)).toEqual(SAME_NODE);
+ });
+});
+
+test.describe('what a showing card draws over', () => {
+ test('the card draws over Nothing open', async ({ page, api, workerServer }) => {
+ const card = await openWithFeedbackShowing(page, api, workerServer, 'nothing-open', 'web');
+
+ await setHeaderPane(page, 'agents', false);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ const nothingOpen = page.getByRole('region', { name: 'Nothing open', exact: true });
+ await expect(nothingOpen).toBeVisible();
+
+ const cardCenter = centerOf(await rectOf(card));
+ expect(contains(await rectOf(nothingOpen), cardCenter)).toBe(true);
+ expect(await landsIn(page, cardCenter, CORNER_STACK)).toBe(true);
+ });
+});
diff --git a/packages/app/tests/stress/corner-stack-layouts.e2e.ts b/packages/app/tests/stress/corner-stack-layouts.e2e.ts
new file mode 100644
index 000000000..46b9b8ac2
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-layouts.e2e.ts
@@ -0,0 +1,179 @@
+import type { Locator, Page } from '@playwright/test';
+import type { TerminalPlacement } from '../../src/lib/terminal-placement-store';
+import {
+ type ApiHelpers,
+ arrangeTerminalAlone,
+ CHAT_PANE_CARD,
+ expect,
+ expectDocumentOpen,
+ expectEditorHidden,
+ FLOATING_AND_HIT_TESTABLE,
+ feedbackCard,
+ headerPaneButton,
+ noticeWithText,
+ openDesktopLayout,
+ openWebLayout,
+ placementOf,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ setHeaderPane,
+ sidebarTrigger,
+ terminalPaneCard,
+ test,
+ type WorkerServer,
+} from './_helpers';
+import {
+ emitUpdateEvent,
+ installUpdateEventOverlay,
+ readRelaunchCalls,
+} from './fixtures/update-event-overlay';
+
+const WIDE = { width: 1440, height: 900 } as const;
+const FEEDBACK_LATCH_TIMEOUT_MS = 15_000;
+const VERSION = '9.9.9';
+
+type Host = 'web' | 'desktop';
+
+interface Layout {
+ readonly name: string;
+ readonly host: Host;
+ readonly terminalPlacement?: TerminalPlacement;
+ readonly arrange: (page: Page) => Promise<void>;
+}
+
+async function openWithFeedbackShowing(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ host: Host,
+ terminalPlacement: TerminalPlacement,
+): Promise<Locator> {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-layouts-${slug}-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ if (host === 'web') await openWebLayout(page, docName, WIDE);
+ else await openDesktopLayout(page, workerServer, docName, { viewport: WIDE, terminalPlacement });
+ await expectDocumentOpen(page, docName);
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+ return card;
+}
+
+const LAYOUTS: readonly Layout[] = [
+ {
+ name: 'web, editor shown with the file sidebar open',
+ host: 'web',
+ arrange: async (page) => {
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('nav#app-file-sidebar')).toBeVisible();
+ },
+ },
+ {
+ name: 'web, editor hidden with chat alone',
+ host: 'web',
+ arrange: async (page) => {
+ await setHeaderPane(page, 'agents', true);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect(page.locator(CHAT_PANE_CARD)).toBeVisible();
+ },
+ },
+ {
+ name: 'web, editor and chat hidden so Nothing open shows',
+ host: 'web',
+ arrange: async (page) => {
+ await setHeaderPane(page, 'agents', false);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect(page.getByRole('region', { name: 'Nothing open', exact: true })).toBeVisible();
+ },
+ },
+ {
+ name: 'desktop, editor hidden with the terminal alone at the bottom',
+ host: 'desktop',
+ terminalPlacement: 'bottom',
+ arrange: (page) => arrangeTerminalAlone(page, 'bottom'),
+ },
+ {
+ name: 'desktop, editor hidden with the terminal alone on the right',
+ host: 'desktop',
+ terminalPlacement: 'right',
+ arrange: (page) => arrangeTerminalAlone(page, 'right'),
+ },
+ {
+ name: 'desktop, editor hidden with chat and the terminal',
+ host: 'desktop',
+ terminalPlacement: 'bottom',
+ arrange: async (page) => {
+ await setHeaderPane(page, 'terminal', true);
+ await setHeaderPane(page, 'agents', true);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeVisible();
+ await expect(page.locator(CHAT_PANE_CARD)).toBeVisible();
+ },
+ },
+];
+
+test.describe('a showing card in every pane layout', () => {
+ for (const { name, host, terminalPlacement = 'bottom', arrange } of LAYOUTS) {
+ test(`${name}: the feedback card stays visible and clickable`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const card = await openWithFeedbackShowing(
+ page,
+ api,
+ workerServer,
+ name.replaceAll(/[^a-z]+/g, '-'),
+ host,
+ terminalPlacement,
+ );
+
+ await arrange(page);
+
+ await expect(card).toBeVisible();
+ expect(await placementOf(card)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ const notGreat = card.getByRole('radio', { name: 'Not great' });
+ await notGreat.click();
+ await expect(notGreat).toHaveAttribute('aria-checked', 'true');
+ await expect(card.getByPlaceholder('Tell us more (optional)')).toBeVisible();
+ });
+ }
+});
+
+test.describe('acting on an update with the editor hidden', () => {
+ test('Relaunch on a ready update, with the terminal alone at the bottom, shows the relaunching state in the corner', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = `corner-layouts-relaunch-w${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${docName}\n\nA terminal session.\n` }]);
+ await installUpdateEventOverlay(page);
+ await openDesktopLayout(page, workerServer, docName, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ await expectDocumentOpen(page, docName);
+ await arrangeTerminalAlone(page, 'bottom');
+
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await expect(ready).toBeVisible();
+ expect(await placementOf(ready)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ await ready.getByRole('button', { name: 'Relaunch', exact: true }).click();
+
+ const relaunching = noticeWithText(page, 'Relaunching to install the update…');
+ await expect(relaunching).toBeVisible();
+ await expect(relaunching.getByRole('button')).toHaveCount(0);
+ expect(await placementOf(relaunching)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ expect(await readRelaunchCalls(page)).toBe(1);
+ await expectEditorHidden(page);
+ });
+});
diff --git a/packages/app/tests/stress/corner-stack-notices.e2e.ts b/packages/app/tests/stress/corner-stack-notices.e2e.ts
new file mode 100644
index 000000000..b4f394a81
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-notices.e2e.ts
@@ -0,0 +1,354 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ cornerStack,
+ EDITOR_PANE_CARD,
+ expect,
+ expectDocumentOpen,
+ FLOATING_AND_HIT_TESTABLE,
+ feedbackCard,
+ identityOf,
+ NEWSLETTER_USED_UP,
+ type NewsletterState,
+ newsletterCard,
+ noticeList,
+ noticeWithText,
+ openDesktopHeader,
+ placementOf,
+ REACHABLE,
+ reachOf,
+ SAME_NODE,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ seedNewsletterStateBeforeLoad,
+ stubAgentCatalog,
+ test,
+ type WorkerServer,
+} from './_helpers';
+import {
+ emitUpdateEvent,
+ installUpdateEventOverlay,
+ readRelaunchCalls,
+ settleHeldRelaunch,
+ type UpdateEventOverlayConfig,
+} from './fixtures/update-event-overlay';
+
+const VERSION = '9.9.9';
+const DOWNLOAD_URL = 'https://openknowledge.ai/download';
+const RELEASE_URL = 'https://openknowledge.ai/changelog';
+const WIDE = { width: 1440, height: 900 } as const;
+const SHORT = { width: 720, height: 480 } as const;
+const UNBROKEN_PATH = `/Users/someone/${'a'.repeat(400)}/OpenKnowledge.app`;
+
+async function seedOneDoc(api: ApiHelpers, slug: string): Promise<string> {
+ const name = `corner-notices-${slug}-w${test.info().workerIndex}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nA document under the corner stack.\n` }]);
+ return name;
+}
+
+async function openDesktopWithUpdateEvents(
+ page: Page,
+ workerServer: WorkerServer,
+ docName: string,
+ overlay: UpdateEventOverlayConfig = {},
+): Promise<void> {
+ await stubAgentCatalog(page);
+ await page.setViewportSize(WIDE);
+ await installUpdateEventOverlay(page, overlay);
+ await openDesktopHeader(page, workerServer, docName, {});
+ await expectDocumentOpen(page, docName);
+ await expect(page.locator('nav#app-file-sidebar')).toBeVisible();
+ await expect(page.locator(EDITOR_PANE_CARD)).toBeVisible();
+}
+
+async function boxOf(locator: Locator) {
+ const box = await locator.boundingBox();
+ if (box === null) throw new Error('expected the card to have a layout box');
+ return box;
+}
+
+interface NoticeKind {
+ readonly kind: string;
+ readonly overlay?: UpdateEventOverlayConfig;
+ readonly newsletter?: NewsletterState;
+ readonly emit?: (page: Page) => Promise<void>;
+ readonly card: (page: Page) => Locator;
+ readonly buttons?: readonly string[];
+}
+
+const NOTICE_KINDS: readonly NoticeKind[] = [
+ {
+ kind: 'ready to install',
+ emit: (page) => emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION }),
+ card: (page) => noticeWithText(page, `Version ${VERSION} ready to install`),
+ buttons: ['Relaunch', 'Dismiss notice'],
+ },
+ {
+ kind: 'getting the latest version',
+ emit: (page) => emitUpdateEvent(page, 'onUpdateFetchingLatest', { version: VERSION }),
+ card: (page) => noticeWithText(page, 'Getting the latest version…'),
+ buttons: [],
+ },
+ {
+ kind: 'install failed',
+ emit: (page) =>
+ emitUpdateEvent(page, 'onUpdateRelaunchFailed', {
+ version: VERSION,
+ downloadUrl: DOWNLOAD_URL,
+ }),
+ card: (page) => noticeWithText(page, `Update to ${VERSION} didn't install.`),
+ buttons: ['Retry', 'Download manually', 'Dismiss notice'],
+ },
+ {
+ kind: 'relaunch failed',
+ emit: (page) =>
+ emitUpdateEvent(page, 'onUpdateRelaunchFailed', { version: VERSION, message: 'disk full' }),
+ card: (page) => noticeWithText(page, 'Relaunch failed — please restart manually: disk full'),
+ buttons: ['Dismiss notice'],
+ },
+ {
+ kind: 'updates paused',
+ emit: (page) => emitUpdateEvent(page, 'onUpdateStuckHint', { downloadUrl: DOWNLOAD_URL }),
+ card: (page) => noticeWithText(page, 'Updates paused'),
+ buttons: ['Download', 'Dismiss notice'],
+ },
+ {
+ kind: 'checking for updates',
+ emit: (page) => emitUpdateEvent(page, 'onUpdateManualCheck', { phase: 'started' }),
+ card: (page) => noticeWithText(page, 'Checking for updates…'),
+ buttons: ['Dismiss notice'],
+ },
+ {
+ kind: 'settings reset',
+ overlay: {
+ schemaIncompatibility: { currentBuild: '0.9.0', persistedSchemaVersion: 7, maxSupported: 6 },
+ },
+ card: (page) =>
+ noticeWithText(
+ page,
+ 'Your settings and recent projects were saved by a newer build than this one (v0.9.0). Reset to defaults to continue.',
+ ),
+ buttons: ['Reset to defaults', 'Dismiss notice'],
+ },
+ {
+ kind: 'updated to version, newsletter used up',
+ newsletter: NEWSLETTER_USED_UP,
+ emit: (page) =>
+ emitUpdateEvent(page, 'onWhatsNew', { version: VERSION, releaseUrl: RELEASE_URL }),
+ card: (page) => noticeWithText(page, `Updated to Version ${VERSION}`),
+ buttons: ['Release notes', 'Dismiss notice'],
+ },
+ {
+ kind: 'newsletter card',
+ emit: (page) =>
+ emitUpdateEvent(page, 'onWhatsNew', { version: VERSION, releaseUrl: RELEASE_URL }),
+ card: (page) => newsletterCard(page).filter({ hasText: `Updated to Version ${VERSION}` }),
+ },
+];
+
+test.describe('update notices in the corner stack, fake desktop host', () => {
+ for (const { kind, overlay, newsletter, emit, card, buttons } of NOTICE_KINDS) {
+ test(`${kind} renders in the corner stack, outside the file sidebar and editor card`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedOneDoc(api, kind.replaceAll(/[^a-z]+/g, '-'));
+ if (newsletter !== undefined) await seedNewsletterStateBeforeLoad(page, newsletter);
+ await openDesktopWithUpdateEvents(page, workerServer, docName, overlay);
+
+ await emit?.(page);
+
+ const notice = card(page);
+ await expect(notice).toBeVisible();
+ await expect(noticeList(page).locator(':scope > *')).toHaveCount(1);
+ expect(await placementOf(notice)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ if (buttons !== undefined) {
+ await expect(notice.getByRole('button')).toHaveCount(buttons.length);
+ for (const name of buttons) {
+ await expect(notice.getByRole('button', { name, exact: true })).toBeVisible();
+ }
+ }
+ });
+ }
+
+ test('Relaunch shows the relaunching state in the stack and a failed relaunch takes its place', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedOneDoc(api, 'relaunch-held');
+ await openDesktopWithUpdateEvents(page, workerServer, docName);
+
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await ready.getByRole('button', { name: 'Relaunch', exact: true }).click();
+
+ const relaunching = noticeWithText(page, 'Relaunching to install the update…');
+ await expect(relaunching).toBeVisible();
+ await expect(relaunching.getByRole('button')).toHaveCount(0);
+ await expect(noticeList(page).locator(':scope > *')).toHaveCount(1);
+ expect(await placementOf(relaunching)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ expect(await readRelaunchCalls(page)).toBe(1);
+
+ await settleHeldRelaunch(page, { kind: 'reject', message: 'disk full' });
+
+ const failed = noticeWithText(page, 'Relaunch failed — please restart manually: disk full');
+ await expect(failed).toBeVisible();
+ await expect(relaunching).toHaveCount(0);
+ await expect(noticeList(page).locator(':scope > *')).toHaveCount(1);
+ expect(await placementOf(failed)).toEqual(FLOATING_AND_HIT_TESTABLE);
+ });
+
+ test('a higher-priority notice replaces the shown one in place', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedOneDoc(api, 'replace-in-place');
+ await openDesktopWithUpdateEvents(page, workerServer, docName);
+
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await expect(ready).toBeVisible();
+ const readyBox = await boxOf(ready);
+
+ await emitUpdateEvent(page, 'onUpdateRelaunchFailed', {
+ version: VERSION,
+ downloadUrl: DOWNLOAD_URL,
+ });
+
+ const failed = noticeWithText(page, `Update to ${VERSION} didn't install.`);
+ await expect(failed).toBeVisible();
+ await expect(ready).toHaveCount(0);
+ await expect(noticeList(page).locator(':scope > *')).toHaveCount(1);
+ const failedBox = await boxOf(failed);
+ expect(Math.abs(failedBox.x - readyBox.x)).toBeLessThanOrEqual(1);
+ expect(
+ Math.abs(failedBox.y + failedBox.height - (readyBox.y + readyBox.height)),
+ ).toBeLessThanOrEqual(1);
+ });
+
+ test('a notice arriving after the feedback card stacks above it, and dismissing it keeps the feedback card', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-notices-feedback-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openDesktopWithUpdateEvents(page, workerServer, docName);
+ const feedback = feedbackCard(page);
+ await expect(feedback).toBeVisible({ timeout: 15_000 });
+ const feedbackNode = await feedback.elementHandle();
+ if (feedbackNode === null) throw new Error('expected the feedback card element');
+
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await expect(ready).toBeVisible();
+ await expect(feedback).toBeVisible();
+ const readyBox = await boxOf(ready);
+ const feedbackBox = await boxOf(feedback);
+ expect(readyBox.y + readyBox.height).toBeLessThanOrEqual(feedbackBox.y + 0.5);
+
+ await ready.getByRole('button', { name: 'Dismiss notice', exact: true }).click();
+
+ await expect(ready).toHaveCount(0);
+ await expect(noticeList(page)).toHaveCount(0);
+ await expect(feedback).toBeVisible();
+ expect(await identityOf(feedbackNode, feedback)).toEqual(SAME_NODE);
+ });
+
+ test('a click in the gap between a notice and the feedback card reaches what is underneath', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-notices-gap-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openDesktopWithUpdateEvents(page, workerServer, docName);
+ const feedback = feedbackCard(page);
+ await expect(feedback).toBeVisible({ timeout: 15_000 });
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await expect(ready).toBeVisible();
+
+ const readyBox = await boxOf(ready);
+ const feedbackBox = await boxOf(feedback);
+ const gapTop = readyBox.y + readyBox.height;
+ expect(feedbackBox.y - gapTop).toBeGreaterThan(2);
+ const probe = { x: feedbackBox.x + feedbackBox.width / 2, y: (gapTop + feedbackBox.y) / 2 };
+
+ const hit = await cornerStack(page).evaluate((stack, { x, y }) => {
+ const el = document.elementFromPoint(x, y);
+ return { found: el !== null, inStack: el !== null && stack.contains(el) };
+ }, probe);
+ expect(hit).toEqual({ found: true, inStack: false });
+ });
+
+ test('a click beside a short notice, inside the stack width, reaches what is underneath', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedOneDoc(api, 'beside-short');
+ await openDesktopWithUpdateEvents(page, workerServer, docName);
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await expect(ready).toBeVisible();
+
+ const readyBox = await boxOf(ready);
+ const stackBox = await boxOf(cornerStack(page));
+ const besideEnd = readyBox.x + readyBox.width + 12;
+ expect(stackBox.x + stackBox.width - besideEnd).toBeGreaterThan(0);
+ const probe = { x: besideEnd, y: readyBox.y + readyBox.height / 2 };
+
+ const hit = await cornerStack(page).evaluate((stack, { x, y }) => {
+ const el = document.elementFromPoint(x, y);
+ return { found: el !== null, inStack: el !== null && stack.contains(el) };
+ }, probe);
+ expect(hit).toEqual({ found: true, inStack: false });
+ });
+
+ test('a long unbroken path in a notice wraps inside the card and keeps Dismiss reachable', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedOneDoc(api, 'long-path');
+ await openDesktopWithUpdateEvents(page, workerServer, docName);
+ await page.setViewportSize(SHORT);
+
+ await emitUpdateEvent(page, 'onUpdateRelaunchFailed', {
+ version: VERSION,
+ message: UNBROKEN_PATH,
+ });
+ const notice = noticeWithText(page, UNBROKEN_PATH);
+ await expect(notice).toBeVisible();
+
+ const overflow = await notice.evaluate((card, text) => {
+ const walker = document.createTreeWalker(card, NodeFilter.SHOW_TEXT);
+ const range = document.createRange();
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
+ if (node.textContent?.includes(text)) range.selectNodeContents(node);
+ }
+ const cardRect = card.getBoundingClientRect();
+ const textRect = range.getBoundingClientRect();
+ return {
+ start: Math.round(cardRect.left - textRect.left),
+ end: Math.round(textRect.right - cardRect.right),
+ };
+ }, UNBROKEN_PATH);
+ expect(overflow.start).toBeLessThanOrEqual(0);
+ expect(overflow.end).toBeLessThanOrEqual(0);
+ expect(await reachOf(notice.getByRole('button', { name: 'Dismiss notice' }))).toEqual(
+ REACHABLE,
+ );
+ });
+});
diff --git a/packages/app/tests/stress/corner-stack-surface.e2e.ts b/packages/app/tests/stress/corner-stack-surface.e2e.ts
new file mode 100644
index 000000000..e2f9ed706
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-surface.e2e.ts
@@ -0,0 +1,531 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ BORDER_SIDES,
+ type BorderSideName,
+ type CardSurface,
+ CHAT_PANE_CARD,
+ CORNER_STACK_TEST_ID,
+ contrastRatioOf,
+ countDifferingPixels,
+ EDITOR_PANE_CARD,
+ expect,
+ expectDocumentOpen,
+ expectEditorHidden,
+ feedbackCard,
+ innerClipsOf,
+ NEWSLETTER_USED_UP,
+ newsletterCard,
+ noticeWithText,
+ openDesktopLayout,
+ openWebLayout,
+ type RgbaBytes,
+ readBorderColors,
+ readCardSurface,
+ readContrastPair,
+ readRootColor,
+ type ScreenClip,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ seedNewsletterStateBeforeLoad,
+ setHeaderPane,
+ settleFrames,
+ sidebarTrigger,
+ terminalPaneCard,
+ test,
+ type WorkerServer,
+} from './_helpers';
+import { emitUpdateEvent, installUpdateEventOverlay } from './fixtures/update-event-overlay';
+
+const VERSION = '9.9.9';
+const DOWNLOAD_URL = 'https://openknowledge.ai/download';
+const RELEASE_URL = 'https://openknowledge.ai/changelog';
+const WIDE = { width: 1440, height: 900 } as const;
+const PHONE = { width: 393, height: 852 } as const;
+const THEME_KEY = 'ok-theme-v1';
+const FEEDBACK_LATCH_TIMEOUT_MS = 15_000;
+const THEMES = ['light', 'dark'] as const;
+const EDGE_CHANNEL_TOLERANCE = 3;
+const MIN_TEXT_CONTRAST = 4.5;
+const OPAQUE = 255;
+
+type Theme = (typeof THEMES)[number];
+type Host = 'web' | 'desktop';
+type EdgeTone = 'shared' | 'warning' | 'emerald';
+
+interface EdgeColor {
+ readonly token: string;
+ readonly darkToken?: string;
+ readonly alpha?: number;
+}
+
+const EDGE_COLORS: Readonly<Record<EdgeTone, EdgeColor>> = {
+ shared: { token: '--border' },
+ warning: { token: '--color-amber-200', darkToken: '--color-amber-900' },
+ emerald: { token: '--color-emerald-500', alpha: 0.4 },
+};
+
+interface SurfaceVerdict {
+ readonly opaqueBackground: boolean;
+ readonly drawnBorderSides: readonly BorderSideName[];
+ readonly radiusIsCardRadius: boolean;
+ readonly shadowMatchesPaneCard: boolean;
+}
+
+const SHARED_SURFACE: SurfaceVerdict = {
+ opaqueBackground: true,
+ drawnBorderSides: BORDER_SIDES,
+ radiusIsCardRadius: true,
+ shadowMatchesPaneCard: true,
+};
+
+interface CardKind {
+ readonly name: string;
+ readonly emit?: (page: Page) => Promise<void>;
+ readonly card: (page: Page) => Locator;
+ readonly texts: readonly string[];
+ readonly edge: EdgeTone;
+ readonly minTextContrast?: number;
+}
+
+interface ContrastRecord {
+ readonly card: string;
+ readonly text: string;
+ readonly ratio: number;
+ readonly foreground: readonly number[];
+ readonly background: readonly number[];
+}
+
+interface SurfaceReading {
+ readonly contrast: readonly ContrastRecord[];
+ readonly edge: RgbaBytes;
+}
+
+const FEEDBACK: CardKind = {
+ name: 'feedback card',
+ card: feedbackCard,
+ texts: ["Tell us how it's going"],
+ edge: 'shared',
+};
+
+const SUCCESS_NOTICE: CardKind = {
+ name: 'success notice (updated to version)',
+ emit: (page) =>
+ emitUpdateEvent(page, 'onWhatsNew', { version: VERSION, releaseUrl: RELEASE_URL }),
+ card: (page) => noticeWithText(page, `Updated to Version ${VERSION}`),
+ texts: [`Updated to Version ${VERSION}`],
+ edge: 'emerald',
+ minTextContrast: MIN_TEXT_CONTRAST,
+};
+
+const DEFAULT_NOTICE: CardKind = {
+ name: 'default notice (ready to install)',
+ emit: (page) => emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION }),
+ card: (page) => noticeWithText(page, `Version ${VERSION} ready to install`),
+ texts: [`Version ${VERSION} ready to install`],
+ edge: 'shared',
+ minTextContrast: MIN_TEXT_CONTRAST,
+};
+
+const ERROR_NOTICE: CardKind = {
+ name: 'error notice (install failed)',
+ emit: (page) =>
+ emitUpdateEvent(page, 'onUpdateRelaunchFailed', {
+ version: VERSION,
+ downloadUrl: DOWNLOAD_URL,
+ }),
+ card: (page) => noticeWithText(page, `Update to ${VERSION} didn't install.`),
+ texts: [`Update to ${VERSION} didn't install.`],
+ edge: 'warning',
+ minTextContrast: MIN_TEXT_CONTRAST,
+};
+
+const DESKTOP_NOTICES: readonly CardKind[] = [SUCCESS_NOTICE, DEFAULT_NOTICE, ERROR_NOTICE];
+
+const NEWSLETTER: CardKind = {
+ name: 'newsletter card',
+ emit: (page) =>
+ emitUpdateEvent(page, 'onWhatsNew', { version: VERSION, releaseUrl: RELEASE_URL }),
+ card: newsletterCard,
+ texts: ['Product updates in your inbox.', `Updated to Version ${VERSION}`],
+ edge: 'shared',
+};
+
+function drawnBorderSidesOf(surface: CardSurface): BorderSideName[] {
+ return BORDER_SIDES.filter((side) => {
+ const border = surface.borders[side];
+ return border.style === 'solid' && border.widthPx >= 1 && border.colorAlpha > 0;
+ });
+}
+
+function channelDistance(actual: RgbaBytes, expected: RgbaBytes): number {
+ return Math.max(
+ Math.abs(actual[0] - expected[0]),
+ Math.abs(actual[1] - expected[1]),
+ Math.abs(actual[2] - expected[2]),
+ Math.abs(actual[3] - expected[3]),
+ );
+}
+
+async function expectedEdgeOf(page: Page, tone: EdgeTone): Promise<RgbaBytes> {
+ const { token, darkToken, alpha } = EDGE_COLORS[tone];
+ const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));
+ const [red, green, blue, tokenAlpha] = await readRootColor(
+ page,
+ dark && darkToken !== undefined ? darkToken : token,
+ );
+ return [red, green, blue, alpha === undefined ? tokenAlpha : Math.round(alpha * OPAQUE)];
+}
+
+const CARD_RADIUS = '10px';
+
+function verdictOf(surface: CardSurface, paneCard: CardSurface): SurfaceVerdict {
+ return {
+ opaqueBackground: surface.backgroundAlpha === 1,
+ drawnBorderSides: drawnBorderSidesOf(surface),
+ radiusIsCardRadius: surface.borderRadius === CARD_RADIUS,
+ shadowMatchesPaneCard: surface.boxShadow === paneCard.boxShadow,
+ };
+}
+
+async function seedThemeBeforeLoad(page: Page, theme: Theme): Promise<void> {
+ await page.emulateMedia({ colorScheme: theme });
+ await page.addInitScript(({ key, value }) => window.localStorage.setItem(key, value), {
+ key: THEME_KEY,
+ value: theme,
+ });
+}
+
+async function expectThemeOnHost(page: Page, theme: Theme, host: Host): Promise<void> {
+ expect(
+ await page.evaluate(() => ({
+ dark: document.documentElement.classList.contains('dark'),
+ electronMode: document.documentElement.classList.contains('electron-mode'),
+ })),
+ ).toEqual({ dark: theme === 'dark', electronMode: host === 'desktop' });
+}
+
+async function seedFeedbackDocs(api: ApiHelpers, slug: string): Promise<string> {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-surface-${slug}-w${test.info().workerIndex}`,
+ );
+ return docName;
+}
+
+async function openOn(
+ page: Page,
+ workerServer: WorkerServer,
+ host: Host,
+ theme: Theme,
+ docName: string,
+): Promise<void> {
+ await seedThemeBeforeLoad(page, theme);
+ if (host === 'web') {
+ await openWebLayout(page, docName, WIDE);
+ } else {
+ await installUpdateEventOverlay(page);
+ await openDesktopLayout(page, workerServer, docName, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ }
+ await expectDocumentOpen(page, docName);
+ await expectThemeOnHost(page, theme, host);
+}
+
+async function expectSharedSurface(page: Page, kind: CardKind): Promise<SurfaceReading> {
+ await kind.emit?.(page);
+ const card = kind.card(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+ const paneCard = page.locator(EDITOR_PANE_CARD);
+ await expect(paneCard).toBeVisible();
+
+ const [surface, reference] = await Promise.all([
+ readCardSurface(card),
+ readCardSurface(paneCard),
+ ]);
+ expect(
+ verdictOf(surface, reference),
+ `${kind.name}: ${JSON.stringify({ surface, paneCard: reference })}`,
+ ).toEqual(SHARED_SURFACE);
+
+ const [edges, expectedEdge] = await Promise.all([
+ readBorderColors(card),
+ expectedEdgeOf(page, kind.edge),
+ ]);
+ expect(
+ BORDER_SIDES.filter(
+ (side) => channelDistance(edges[side], expectedEdge) <= EDGE_CHANNEL_TOLERANCE,
+ ),
+ `${kind.name}: border ${JSON.stringify(edges)} against ${EDGE_COLORS[kind.edge].token} ${JSON.stringify(expectedEdge)}`,
+ ).toEqual(BORDER_SIDES);
+
+ await page.emulateMedia({ forcedColors: 'active' });
+ const forced = await readCardSurface(card);
+ expect(
+ drawnBorderSidesOf(forced),
+ `${kind.name} with forced colors: ${JSON.stringify(forced)}`,
+ ).toEqual(BORDER_SIDES);
+ await page.emulateMedia({ forcedColors: 'none' });
+
+ const contrast: ContrastRecord[] = [];
+ for (const text of kind.texts) {
+ const pair = await readContrastPair(card.getByText(text, { exact: true }), card);
+ const ratio = contrastRatioOf(pair);
+ contrast.push({
+ card: kind.name,
+ text,
+ ratio: Math.round(ratio * 100) / 100,
+ foreground: pair.foreground,
+ background: pair.background.map(Math.round),
+ });
+ if (kind.minTextContrast !== undefined) {
+ expect(ratio, `${kind.name}: "${text}" against its surface`).toBeGreaterThanOrEqual(
+ kind.minTextContrast,
+ );
+ }
+ }
+ return { contrast, edge: edges.top };
+}
+
+async function attachContrast(label: string, records: readonly ContrastRecord[]): Promise<void> {
+ await test.info().attach(`contrast ratios, ${label}`, {
+ body: JSON.stringify(records, null, 2),
+ contentType: 'application/json',
+ });
+}
+
+async function attachScreenshot(page: Page, label: string): Promise<void> {
+ await test.info().attach(label, { body: await page.screenshot(), contentType: 'image/png' });
+}
+
+async function settleForCapture(
+ page: Page,
+ viewport: { readonly width: number; readonly height: number },
+): Promise<void> {
+ await page.mouse.move(viewport.width / 2, viewport.height / 2);
+ await expect
+ .poll(() =>
+ page.evaluate(() =>
+ document
+ .getAnimations()
+ .filter(
+ (animation): animation is CSSTransition =>
+ animation instanceof CSSTransition && animation.playState === 'running',
+ )
+ .map((transition) => transition.transitionProperty),
+ ),
+ )
+ .toEqual([]);
+ await settleFrames(page);
+}
+
+interface ClipCapture {
+ readonly clip: ScreenClip;
+ readonly card: Buffer;
+ readonly backdrop: Buffer;
+}
+
+async function captureCardAndBackdrop(page: Page, card: Locator): Promise<ClipCapture[]> {
+ const stack = page.getByTestId(CORNER_STACK_TEST_ID);
+ const captures: ClipCapture[] = [];
+ for (const clip of await innerClipsOf(card)) {
+ const cardShot = await page.screenshot({ clip });
+ await stack.evaluate((el) => {
+ el.style.visibility = 'hidden';
+ });
+ const backdropShot = await page.screenshot({ clip });
+ await stack.evaluate((el) => {
+ el.style.removeProperty('visibility');
+ });
+ captures.push({ clip, card: cardShot, backdrop: backdropShot });
+ }
+ return captures;
+}
+
+interface BackdropLayout {
+ readonly name: string;
+ readonly compared: boolean;
+ readonly arrange: (page: Page) => Promise<void>;
+}
+
+const BACKDROP_LAYOUTS: readonly BackdropLayout[] = [
+ {
+ name: 'editor shown with the file sidebar open, over its bottom row',
+ compared: false,
+ arrange: async (page) => {
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('nav#app-file-sidebar')).toBeVisible();
+ },
+ },
+ {
+ name: 'editor shown with the file sidebar collapsed, over a document',
+ compared: true,
+ arrange: async (page) => {
+ await sidebarTrigger(page).click();
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator(EDITOR_PANE_CARD)).toBeVisible();
+ },
+ },
+ {
+ name: 'editor hidden with the terminal at the bottom',
+ compared: true,
+ arrange: async (page) => {
+ await setHeaderPane(page, 'terminal', true);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeVisible();
+ },
+ },
+ {
+ name: 'editor hidden with chat alone',
+ compared: true,
+ arrange: async (page) => {
+ await setHeaderPane(page, 'terminal', false);
+ await setHeaderPane(page, 'agents', true);
+ await expect(page.locator(CHAT_PANE_CARD)).toBeVisible();
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeHidden();
+ },
+ },
+ {
+ name: 'Nothing open',
+ compared: false,
+ arrange: async (page) => {
+ await setHeaderPane(page, 'agents', false);
+ await expect(page.getByRole('region', { name: 'Nothing open', exact: true })).toBeVisible();
+ },
+ },
+];
+
+interface BackdropCapture {
+ readonly layout: string;
+ readonly clips: readonly ClipCapture[];
+}
+
+for (const theme of THEMES) {
+ test.describe(`floating card surface, ${theme} theme`, () => {
+ test('fake desktop: the feedback card and the success, default and error notices share the floating card surface, each notice edge in its tone', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedFeedbackDocs(api, `kinds-${theme}`);
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await seedNewsletterStateBeforeLoad(page, NEWSLETTER_USED_UP);
+ await openOn(page, workerServer, 'desktop', theme, docName);
+
+ const records: ContrastRecord[] = [];
+ const edges = new Map<CardKind, RgbaBytes>();
+ for (const kind of [FEEDBACK, ...DESKTOP_NOTICES]) {
+ await test.step(kind.name, async () => {
+ const reading = await expectSharedSurface(page, kind);
+ records.push(...reading.contrast);
+ edges.set(kind, reading.edge);
+ });
+ }
+ await attachContrast(`fake desktop, ${theme}`, records);
+
+ const edgeOf = (kind: CardKind): RgbaBytes => {
+ const edge = edges.get(kind);
+ if (edge === undefined) throw new Error(`expected a border reading for the ${kind.name}`);
+ return edge;
+ };
+ expect(edgeOf(ERROR_NOTICE), 'error notice edge against the default notice edge').not.toEqual(
+ edgeOf(DEFAULT_NOTICE),
+ );
+ expect(
+ edgeOf(SUCCESS_NOTICE),
+ 'success notice edge against the default notice edge',
+ ).not.toEqual(edgeOf(DEFAULT_NOTICE));
+ });
+
+ test('fake desktop: the newsletter card shares the floating card surface', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = `corner-surface-newsletter-${theme}-w${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: docName, markdown: `# ${docName}\n\nUnder the newsletter card.\n` },
+ ]);
+ await openOn(page, workerServer, 'desktop', theme, docName);
+
+ const reading = await expectSharedSurface(page, NEWSLETTER);
+ await attachContrast(`newsletter, fake desktop, ${theme}`, reading.contrast);
+ });
+
+ test('web: the feedback card shares the floating card surface and fits a phone-width window', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedFeedbackDocs(api, `web-${theme}`);
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openOn(page, workerServer, 'web', theme, docName);
+
+ const reading = await expectSharedSurface(page, FEEDBACK);
+ await attachContrast(`web, ${theme}`, reading.contrast);
+
+ await page.setViewportSize(PHONE);
+ await settleForCapture(page, PHONE);
+ await expect(feedbackCard(page)).toBeInViewport({ ratio: 1 });
+ await attachScreenshot(page, `${theme}: web at ${PHONE.width} wide`);
+ });
+
+ test('fake desktop: the feedback card paints the same pixels over a document, the terminal and chat', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = await seedFeedbackDocs(api, `backdrops-${theme}`);
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openOn(page, workerServer, 'desktop', theme, docName);
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+
+ const captures: BackdropCapture[] = [];
+ for (const layout of BACKDROP_LAYOUTS) {
+ await test.step(layout.name, async () => {
+ await layout.arrange(page);
+ await expect(card).toBeVisible();
+ await settleForCapture(page, WIDE);
+ await attachScreenshot(page, `${theme}: ${layout.name}`);
+ if (!layout.compared) return;
+ captures.push({ layout: layout.name, clips: await captureCardAndBackdrop(page, card) });
+ });
+ }
+
+ const [reference, ...others] = captures;
+ if (reference === undefined) throw new Error('expected compared backdrop layouts');
+ expect(others).toHaveLength(2);
+ for (const other of others) {
+ expect(
+ other.clips.map(({ clip }) => clip),
+ `${other.layout}: the card moved`,
+ ).toEqual(reference.clips.map(({ clip }) => clip));
+ for (const [index, base] of reference.clips.entries()) {
+ const shot = other.clips[index];
+ if (shot === undefined) throw new Error('expected a capture for every clip');
+ const where = `inside ${JSON.stringify(base.clip)}, ${other.layout} against ${reference.layout}`;
+ expect(
+ await countDifferingPixels(page, base.backdrop, shot.backdrop),
+ `the backdrops ${where} should differ`,
+ ).toBeGreaterThan(0);
+ const differing = await countDifferingPixels(page, base.card, shot.card);
+ if (differing > 0) {
+ await test.info().attach(`${theme}: card over ${reference.layout}`, {
+ body: base.card,
+ contentType: 'image/png',
+ });
+ await test.info().attach(`${theme}: card over ${other.layout}`, {
+ body: shot.card,
+ contentType: 'image/png',
+ });
+ }
+ expect(differing, `card pixels ${where}`).toBe(0);
+ }
+ }
+ });
+ });
+}
diff --git a/packages/app/tests/stress/corner-stack-survival.e2e.ts b/packages/app/tests/stress/corner-stack-survival.e2e.ts
new file mode 100644
index 000000000..2ec44128d
--- /dev/null
+++ b/packages/app/tests/stress/corner-stack-survival.e2e.ts
@@ -0,0 +1,260 @@
+import type { Locator, Page } from '@playwright/test';
+import {
+ arrangeTerminalAlone,
+ CHAT_PANE_CARD,
+ CORNER_STACK_TEST_ID,
+ EDITOR_PANE_CARD,
+ expect,
+ expectDocumentOpen,
+ expectEditorHidden,
+ feedbackCard,
+ headerPaneButton,
+ identityOf,
+ noticeWithText,
+ openDesktopLayout,
+ openWebLayout,
+ runPaletteCommand,
+ SAME_NODE,
+ seedFeedbackEligibleDocs,
+ seedFeedbackNudgeStateBeforeLoad,
+ setHeaderPane,
+ sidebarTrigger,
+ terminalPaneCard,
+ test,
+} from './_helpers';
+import {
+ emitUpdateEvent,
+ installUpdateEventOverlay,
+ readRelaunchCalls,
+} from './fixtures/update-event-overlay';
+
+const WIDE = { width: 1440, height: 900 } as const;
+const FEEDBACK_LATCH_TIMEOUT_MS = 15_000;
+const ONBOARDING_TIMEOUT_MS = 15_000;
+const VERSION = '9.9.9';
+const RELAUNCHING = 'Relaunching to install the update…';
+const DRAFT = 'The file list keeps hiding my notes.';
+
+interface LayoutStep {
+ readonly name: string;
+ readonly act: (page: Page) => Promise<void>;
+}
+
+function onboardingChecklist(page: Page): Locator {
+ return page.getByRole('region', { name: 'Get set up', exact: true });
+}
+
+async function homeOf(element: Locator) {
+ await expect(element.page().getByTestId(CORNER_STACK_TEST_ID)).toBeAttached();
+ return await element.evaluate(
+ (el, stackTestId) => ({
+ inSidebarFooter: el.closest('[data-slot="sidebar-footer"]') !== null,
+ inCornerStack: el.closest(`[data-testid="${stackTestId}"]`) !== null,
+ }),
+ CORNER_STACK_TEST_ID,
+ );
+}
+
+const IN_SIDEBAR_FOOTER = { inSidebarFooter: true, inCornerStack: false };
+
+const FEEDBACK_DRAFT_STEPS: readonly LayoutStep[] = [
+ {
+ name: 'hide the editor',
+ act: async (page) => {
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ },
+ },
+ {
+ name: 'show the editor',
+ act: async (page) => {
+ await setHeaderPane(page, 'editor', true);
+ await expect(page.locator(EDITOR_PANE_CARD)).toBeVisible();
+ },
+ },
+ {
+ name: 'collapse the file sidebar',
+ act: async (page) => {
+ await sidebarTrigger(page).click();
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'false');
+ },
+ },
+ {
+ name: 'reopen the file sidebar',
+ act: async (page) => {
+ await sidebarTrigger(page).click();
+ await expect(sidebarTrigger(page)).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('nav#app-file-sidebar')).toBeVisible();
+ },
+ },
+ {
+ name: 'open chat',
+ act: async (page) => {
+ await setHeaderPane(page, 'agents', true);
+ await expect(page.locator(CHAT_PANE_CARD)).toBeVisible();
+ },
+ },
+ {
+ name: 'close chat',
+ act: async (page) => {
+ await setHeaderPane(page, 'agents', false);
+ await expect(page.locator(CHAT_PANE_CARD)).toBeHidden();
+ },
+ },
+];
+
+const RELAUNCH_STEPS: readonly LayoutStep[] = [
+ {
+ name: 'show the editor',
+ act: async (page) => {
+ await setHeaderPane(page, 'editor', true);
+ await expect(page.locator(EDITOR_PANE_CARD)).toBeVisible();
+ },
+ },
+ {
+ name: 'hide the editor',
+ act: async (page) => {
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ },
+ },
+ {
+ name: 'hide the terminal',
+ act: async (page) => {
+ await setHeaderPane(page, 'terminal', false);
+ await expect(page.getByRole('region', { name: 'Nothing open', exact: true })).toBeVisible();
+ },
+ },
+ {
+ name: 'show the terminal',
+ act: async (page) => {
+ await setHeaderPane(page, 'terminal', true);
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeVisible();
+ },
+ },
+ {
+ name: 'move the terminal to the right',
+ act: async (page) => {
+ await runPaletteCommand(page, 'move terminal', 'move-terminal');
+ await expect(page.locator(terminalPaneCard('right'))).toBeVisible();
+ },
+ },
+ {
+ name: 'move the terminal back to the bottom',
+ act: async (page) => {
+ await runPaletteCommand(page, 'move terminal', 'move-terminal');
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeVisible();
+ },
+ },
+];
+
+test.describe('cards survive layout changes', () => {
+ test('a feedback draft keeps its card, rating and text across editor, sidebar and chat changes', async ({
+ page,
+ api,
+ }) => {
+ const docName = await seedFeedbackEligibleDocs(
+ api,
+ `corner-survival-draft-w${test.info().workerIndex}`,
+ );
+ await seedFeedbackNudgeStateBeforeLoad(page);
+ await openWebLayout(page, docName, WIDE);
+ await expectDocumentOpen(page, docName);
+
+ const card = feedbackCard(page);
+ await expect(card).toBeVisible({ timeout: FEEDBACK_LATCH_TIMEOUT_MS });
+ const notGreat = card.getByRole('radio', { name: 'Not great' });
+ await notGreat.click();
+ const draft = card.getByPlaceholder('Tell us more (optional)');
+ await draft.fill(DRAFT);
+ const before = await card.elementHandle();
+ if (before === null) throw new Error('expected the feedback card element');
+
+ for (const step of FEEDBACK_DRAFT_STEPS) {
+ await test.step(step.name, async () => {
+ await step.act(page);
+ await expect(card).toBeVisible();
+ expect(await identityOf(before, card)).toEqual(SAME_NODE);
+ await expect(notGreat).toHaveAttribute('aria-checked', 'true');
+ await expect(draft).toHaveValue(DRAFT);
+ });
+ }
+ });
+
+ test('a held relaunch keeps its notice across editor, terminal and terminal-placement changes', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = `corner-survival-relaunch-w${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${docName}\n\nA terminal session.\n` }]);
+ await installUpdateEventOverlay(page);
+ await openDesktopLayout(page, workerServer, docName, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ await expectDocumentOpen(page, docName);
+ await arrangeTerminalAlone(page, 'bottom');
+
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ await noticeWithText(page, `Version ${VERSION} ready to install`)
+ .getByRole('button', { name: 'Relaunch', exact: true })
+ .click();
+ const relaunching = noticeWithText(page, RELAUNCHING);
+ await expect(relaunching).toBeVisible();
+ await expect(relaunching.getByRole('button')).toHaveCount(0);
+ expect(await readRelaunchCalls(page)).toBe(1);
+ const before = await relaunching.elementHandle();
+ if (before === null) throw new Error('expected the relaunching notice element');
+
+ for (const step of RELAUNCH_STEPS) {
+ await test.step(step.name, async () => {
+ await step.act(page);
+ await expect(relaunching).toBeVisible();
+ expect(await identityOf(before, relaunching)).toEqual(SAME_NODE);
+ await expect(relaunching).toHaveText(RELAUNCHING);
+ await expect(relaunching.getByRole('button')).toHaveCount(0);
+ });
+ }
+ });
+});
+
+test.describe('the onboarding checklist stays in the file sidebar', () => {
+ test('the checklist renders in the sidebar footer, an update notice goes to the corner, and hiding the editor hides only the checklist', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const docName = `corner-survival-onboarding-w${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${docName}\n\nA new project.\n` }]);
+ await installUpdateEventOverlay(page, { freshlyCreated: true });
+ await openDesktopLayout(page, workerServer, docName, {
+ viewport: WIDE,
+ terminalPlacement: 'bottom',
+ });
+ await expectDocumentOpen(page, docName);
+
+ const checklist = onboardingChecklist(page);
+ await expect(checklist).toBeVisible({ timeout: ONBOARDING_TIMEOUT_MS });
+ await expect(checklist).toHaveCount(1);
+ expect(await homeOf(checklist)).toEqual(IN_SIDEBAR_FOOTER);
+
+ await emitUpdateEvent(page, 'onUpdateDownloaded', { version: VERSION });
+ const ready = noticeWithText(page, `Version ${VERSION} ready to install`);
+ await expect(ready).toBeVisible();
+ await expect(checklist).toBeVisible();
+ await expect(checklist).toHaveCount(1);
+ expect(await homeOf(checklist)).toEqual(IN_SIDEBAR_FOOTER);
+
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect(checklist).toBeHidden();
+ await expect(ready).toBeVisible();
+
+ await setHeaderPane(page, 'editor', true);
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(checklist).toBeVisible();
+ expect(await homeOf(checklist)).toEqual(IN_SIDEBAR_FOOTER);
+ await expect(ready).toBeVisible();
+ });
+});
diff --git a/packages/app/tests/stress/editor-card-file-list-drag.e2e.ts b/packages/app/tests/stress/editor-card-file-list-drag.e2e.ts
new file mode 100644
index 000000000..bc275d688
--- /dev/null
+++ b/packages/app/tests/stress/editor-card-file-list-drag.e2e.ts
@@ -0,0 +1,109 @@
+import type { Locator, Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced } from './_helpers';
+
+const FILE_LIST = '[data-slot="sidebar-container"]';
+const RAIL = '[data-sidebar="rail"]';
+const EDITOR_CARD = '[data-slot="pane-card"][data-pane="editor"]';
+const BOOT_TIMEOUT_MS = 30_000;
+const FIRST_MOVE_PX = 8;
+const DRAG_PX = 80;
+const WIDTH_TOLERANCE_PX = 1;
+const REM_PX = 16;
+const GRABS = [
+ { label: 'the middle of the edge', offsetPx: 0 },
+ { label: 'just inside the file list', offsetPx: -4 },
+ { label: 'just inside the document', offsetPx: 4 },
+] as const;
+
+async function widthOf(locator: Locator): Promise<number> {
+ return locator.evaluate((element) => element.getBoundingClientRect().width);
+}
+
+async function savedWidthPx(page: Page): Promise<number | null> {
+ const raw = await page.evaluate(
+ () =>
+ document.cookie
+ .split('; ')
+ .find((row) => row.startsWith('sidebar_width='))
+ ?.split('=')[1] ?? null,
+ );
+ if (raw == null) return null;
+ const value = Number.parseFloat(raw);
+ return raw.endsWith('rem') ? value * REM_PX : value;
+}
+
+async function waitForEditorWithFileList(page: Page): Promise<void> {
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible({
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await expect(page.locator('[data-slot="sidebar"]').first()).toHaveAttribute(
+ 'data-state',
+ 'expanded',
+ );
+}
+
+for (const grab of GRABS) {
+ test(`dragging the file list edge from ${grab.label} saves the width the user sees`, async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-card-file-list-drag-${test.info().workerIndex}-${grab.offsetPx + 4}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${docName}\n\nbody\n` }]);
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForEditorWithFileList(page);
+
+ const fileList = page.locator(FILE_LIST);
+ await expect(
+ page.locator(EDITOR_CARD).locator(FILE_LIST),
+ 'the file list lives in the editor card',
+ ).toHaveCount(1);
+ const widthBefore = await widthOf(fileList);
+
+ const railBox = await page.locator(RAIL).boundingBox();
+ if (railBox == null) throw new Error('the file list edge has no bounds');
+ const x = railBox.x + railBox.width / 2 + grab.offsetPx;
+ const y = railBox.y + railBox.height / 2;
+ expect(
+ await page.evaluate(
+ ([px, py]) => document.elementFromPoint(px, py)?.closest('[data-sidebar="rail"]') != null,
+ [x, y] as const,
+ ),
+ 'the grab point lands on the file list edge',
+ ).toBe(true);
+
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + FIRST_MOVE_PX, y);
+ await expect
+ .poll(async () => Math.abs((await widthOf(fileList)) - (widthBefore + FIRST_MOVE_PX)), {
+ message: 'the first move does not jump',
+ })
+ .toBeLessThanOrEqual(WIDTH_TOLERANCE_PX);
+ await page.mouse.move(x + DRAG_PX, y, { steps: 10 });
+ await expect
+ .poll(async () => Math.abs((await widthOf(fileList)) - (widthBefore + DRAG_PX)), {
+ message: 'mid-drag the edge follows the pointer',
+ })
+ .toBeLessThanOrEqual(WIDTH_TOLERANCE_PX);
+ await page.mouse.up();
+
+ const seen = await widthOf(fileList);
+ expect(Math.abs(seen - (widthBefore + DRAG_PX))).toBeLessThanOrEqual(WIDTH_TOLERANCE_PX);
+ const saved = await savedWidthPx(page);
+ expect(saved, 'the drag saved a width').not.toBeNull();
+ expect(
+ Math.abs((saved ?? 0) - seen),
+ 'the saved width is the width on screen',
+ ).toBeLessThanOrEqual(WIDTH_TOLERANCE_PX);
+
+ await page.reload();
+ await waitForEditorWithFileList(page);
+ await expect
+ .poll(async () => Math.abs((await widthOf(fileList)) - seen), {
+ message: 'the saved width comes back after a reload',
+ })
+ .toBeLessThanOrEqual(WIDTH_TOLERANCE_PX);
+ });
+}
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
new file mode 100644
index 000000000..28bf2f8f9
--- /dev/null
+++ b/packages/app/tests/stress/editor-card-side-panel-width.e2e.ts
@@ -0,0 +1,3535 @@
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { join } from 'node:path';
+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';
+
+const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';
+const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
+const BOOT_TIMEOUT_MS = 30_000;
+const DRAG_PX = 150;
+const WIDTH_TOLERANCE_PX = 1;
+const BESIDE_DIVIDER_GRAB_PX = 3;
+const GRABS = [
+ { label: 'on the divider', offsetPx: 0 },
+ { label: 'beside the divider on the editor side', offsetPx: -BESIDE_DIVIDER_GRAB_PX },
+ { label: 'beside the divider on the chat side', offsetPx: BESIDE_DIVIDER_GRAB_PX },
+] as const;
+
+const DOC_MARKDOWN = `---
+title: "Side panel width"
+description: "Fixture doc for the editor card side panel width law"
+---
+
+# Side panel width
+
+Body text so the document column renders real content while the dividers are dragged.`;
+
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
+test('narrow document panes reclaim gutters while properties keep their gutter and heading and composer stay centered', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docName = `editor-compact-gutters-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '600');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.route('**/api/installed-agents', (route) => route.fulfill({ json: { claude: true } }));
+ await page.route('**/api/acp/catalog', (route) =>
+ route.fulfill({ json: acpCatalogBody([{ id: 'gutter-agent', name: 'Gutter Agent' }]) }),
+ );
+ await page.setViewportSize({ width: 1400, height: 900 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const column = page.locator('[data-editor-workspace-column]');
+ const editor = column.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ const properties = column.locator('.property-panel').first();
+ const composer = column.getByTestId('bottom-composer');
+ const heading = column.getByTestId('editor-toolbar').locator('.editor-content-aligned');
+ await expect(editor).toBeVisible();
+ await expect(properties).toBeVisible();
+ await expect(composer).toBeVisible();
+ await page.setViewportSize({ width: 1300, height: 900 });
+ const information = page.locator('#doc-panel');
+ await expect(information).toBeVisible();
+ const divider = page.locator('[data-doc-panel-handle]');
+ await divider.hover();
+ const dividerBox = await divider.boundingBox();
+ if (!dividerBox) throw new Error('the information divider has no bounds');
+ const x = dividerBox.x + dividerBox.width / 2;
+ const y = dividerBox.y + dividerBox.height / 2;
+ await page.mouse.down();
+ await expect(divider).toHaveAttribute('data-separator', 'active');
+ await page.mouse.move(x - 600, y, { steps: 8 });
+ await page.mouse.up();
+ await expect.poll(() => widthOf(information)).toBeGreaterThanOrEqual(599);
+ for (const viewport of [1300, 1800, 1300]) {
+ await page.setViewportSize({ width: viewport, height: 900 });
+ const compact = viewport === 1300;
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect.poll(async () => (await widthOf(column)) < 640).toBe(compact);
+ await expect
+ .poll(() =>
+ editor.evaluate((element, narrow) => {
+ const grid = element.closest('.tiptap-editor');
+ if (!grid) return false;
+ const box = grid.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ const body = element.getBoundingClientRect();
+ const left = body.left + Number.parseFloat(style.paddingLeft) - box.left;
+ const right = box.right - body.right + Number.parseFloat(style.paddingRight);
+ return narrow
+ ? Math.abs(left - 60) <= 1 && Math.abs(right - 16) <= 1
+ : left >= 63 && right >= 63 && Math.abs(left - right) <= 1;
+ }, compact),
+ )
+ .toBe(true);
+ await expect
+ .poll(() =>
+ properties.evaluate((element) => {
+ const body = element
+ .closest('[data-editor-workspace-column]')
+ ?.querySelector('.ProseMirror:not(.composer-prosemirror)');
+ if (!body || !element.firstElementChild) return Number.POSITIVE_INFINITY;
+ const bodyLeft =
+ body.getBoundingClientRect().left +
+ Number.parseFloat(getComputedStyle(body).paddingLeft);
+ return Math.abs(element.firstElementChild.getBoundingClientRect().left - bodyLeft);
+ }),
+ )
+ .toBeLessThanOrEqual(1);
+ for (const aligned of [heading, composer]) {
+ await expect
+ .poll(() =>
+ aligned.evaluate((element, narrow) => {
+ if (!element.firstElementChild) return false;
+ const pane = element.getBoundingClientRect();
+ const content = element.firstElementChild.getBoundingClientRect();
+ const left = content.left - pane.left;
+ const right = pane.right - content.right;
+ return Math.abs(left - right) <= 1 && (narrow ? Math.abs(left - 16) <= 1 : left >= 63);
+ }, compact),
+ )
+ .toBe(true);
+ }
+ await expect
+ .poll(() =>
+ editor.evaluate((element) => {
+ const scroll = element.closest('.editor-doc-scroll');
+ const workspace = element.closest('[data-editor-workspace-column]');
+ if (!scroll || !workspace) return Number.POSITIVE_INFINITY;
+ return Math.max(
+ scroll.scrollWidth - scroll.clientWidth,
+ workspace.scrollWidth - workspace.clientWidth,
+ );
+ }),
+ )
+ .toBeLessThanOrEqual(1);
+ }
+ for (const direction of ['ltr', 'rtl']) {
+ await page.evaluate((value) => {
+ document.documentElement.dir = value;
+ }, direction);
+ await expect
+ .poll(() =>
+ editor.evaluate((element) => {
+ const grid = element.closest('.tiptap-editor')?.getBoundingClientRect();
+ if (!grid) return null;
+ const style = getComputedStyle(element);
+ const box = element.getBoundingClientRect();
+ return [
+ Math.round(box.left + Number.parseFloat(style.paddingLeft) - grid.left),
+ Math.round(grid.right - box.right + Number.parseFloat(style.paddingRight)),
+ ];
+ }),
+ )
+ .toEqual([60, 16]);
+ await expect
+ .poll(() =>
+ properties.evaluate((element) => {
+ if (!element.firstElementChild) return null;
+ const pane = element.getBoundingClientRect();
+ const content = element.firstElementChild.getBoundingClientRect();
+ return [Math.round(content.left - pane.left), Math.round(pane.right - content.right)];
+ }),
+ )
+ .toEqual([60, 16]);
+ const propertyGrip = properties.getByRole('button', { name: 'Drag title to reorder' });
+ await propertyGrip.hover();
+ expect(
+ await propertyGrip.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ const pane = element.closest('[data-editor-workspace-column]')?.getBoundingClientRect();
+ const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2);
+ return (
+ pane != null && box.left - pane.left >= 16 && (hit === element || element.contains(hit))
+ );
+ }),
+ ).toBe(true);
+ for (const aligned of [heading, composer]) {
+ await expect
+ .poll(() =>
+ aligned.evaluate((element) => {
+ if (!element.firstElementChild) return null;
+ const pane = element.getBoundingClientRect();
+ const card = element.firstElementChild.getBoundingClientRect();
+ return [Math.round(card.left - pane.left), Math.round(pane.right - card.right)];
+ }),
+ )
+ .toEqual([16, 16]);
+ }
+ const paragraph = editor.locator(':scope > p').first();
+ await paragraph.hover();
+ const add = column.locator('.ok-add-block-btn:visible');
+ const grip = column.locator('.ok-drag-grip:visible');
+ for (const control of [add, grip]) {
+ await expect(control).toBeVisible();
+ expect(
+ await control.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ const point = document.elementFromPoint(
+ box.left + box.width / 2,
+ box.top + box.height / 2,
+ );
+ const pane = element.closest('[data-editor-workspace-column]')?.getBoundingClientRect();
+ return (
+ pane != null && box.left >= pane.left && (point === element || element.contains(point))
+ );
+ }),
+ ).toBe(true);
+ }
+ await page.screenshot({
+ path: test.info().outputPath(`compact-editor-gutters-${direction}.png`),
+ });
+ await add.click();
+ await expect(editor.locator(':scope > p').last()).toHaveText('/');
+ await page.keyboard.press('Escape');
+ await expect(page.locator('[data-suggestion-popup="slash-command"]')).toHaveCount(0);
+ }
+});
+
+test.describe('touch document gutters', () => {
+ test.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } });
+
+ test('compact desktop spacing preserves the existing phone gutters', async ({
+ page,
+ api,
+ baseURL,
+ }) => {
+ const docName = `editor-touch-gutters-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.context().addCookies([{ name: 'sidebar_state', value: 'false', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'closed', below: 'closed', embedded: 'closed' },
+ right: { above: 'closed', below: 'closed', embedded: 'closed' },
+ }),
+ );
+ });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editor).toBeVisible();
+ for (const direction of ['ltr', 'rtl']) {
+ await page.evaluate((value) => {
+ document.documentElement.dir = value;
+ }, direction);
+ await expect
+ .poll(() =>
+ editor.evaluate((element) => {
+ const style = getComputedStyle(element);
+ const grid = element.closest('.tiptap-editor')?.getBoundingClientRect();
+ if (!grid) return null;
+ const box = element.getBoundingClientRect();
+ return [
+ Math.round(box.left + Number.parseFloat(style.paddingLeft) - grid.left),
+ Math.round(grid.right - box.right + Number.parseFloat(style.paddingRight)),
+ ];
+ }),
+ )
+ .toEqual([16, 16]);
+ }
+ });
+});
+
+async function widthOf(locator: Locator): Promise<number> {
+ return locator.evaluate((element) => element.getBoundingClientRect().width);
+}
+
+async function settleFrames(page: Page): Promise<void> {
+ await page.evaluate(
+ () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
+ );
+}
+
+async function openChat(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 });
+ await settleFrames(page);
+}
+
+async function dragChatDivider(
+ page: Page,
+ grabOffsetPx: number,
+ 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();
+ 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,
+ onCard: hit?.closest('[data-slot="pane-card"]') != null,
+ };
+ },
+ [x, y] 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 settleFrames(page);
+}
+
+for (const grab of GRABS) {
+ test(`the side panel keeps its width while the chat divider is dragged from ${grab.label}`, async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-card-side-panel-width-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible({
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await expect
+ .poll(() => page.locator('[data-doc-panel-toggle]').getAttribute('aria-expanded'), {
+ timeout: 10_000,
+ })
+ .toBe('true');
+
+ const sidePanel = page.locator('#doc-panel');
+ const documentColumn = page.locator('[data-editor-workspace-column]');
+ const editorCard = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ await expect(editorCard).toBeVisible();
+ await expect(
+ editorCard.locator('#doc-panel'),
+ 'the side panel lives in the editor card',
+ ).toHaveCount(1);
+ const sidePanelBefore = await widthOf(sidePanel);
+ expect(sidePanelBefore).toBeGreaterThanOrEqual(300);
+
+ await openChat(page);
+ await expect(sidePanel).not.toBeVisible();
+ const chatPanel = page
+ .locator(AGENTS_PANEL_MOUNT)
+ .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
+ const chatBefore = await widthOf(chatPanel);
+ const columnBefore = await widthOf(documentColumn);
+
+ await dragChatDivider(page, grab.offsetPx, -DRAG_PX, async () => {
+ await expect(sidePanel).not.toBeVisible();
+ expect(
+ await widthOf(documentColumn),
+ 'mid-drag the document column yields to Chat without the information rail',
+ ).toBeLessThan(columnBefore - DRAG_PX / 2);
+ });
+
+ await expect(sidePanel).not.toBeVisible();
+ expect(await widthOf(documentColumn)).toBeGreaterThanOrEqual(300);
+ expect(await widthOf(chatPanel)).toBeGreaterThan(chatBefore + DRAG_PX / 2);
+ expect(await widthOf(documentColumn)).toBeLessThan(columnBefore - DRAG_PX / 2);
+
+ await dragChatDivider(page, grab.offsetPx, DRAG_PX / 2, async () => {
+ await expect(sidePanel).not.toBeVisible();
+ });
+
+ expect(await widthOf(documentColumn)).toBeGreaterThan(columnBefore - DRAG_PX);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(sidePanel).toBeVisible();
+ expect(Math.abs((await widthOf(sidePanel)) - sidePanelBefore)).toBeLessThanOrEqual(
+ WIDTH_TOLERANCE_PX,
+ );
+ });
+}
+
+test('restored wide sidebars never squeeze the document or cover its information toggle', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docName = `editor-min-width-restored-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '600');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const information = page.locator('#doc-panel');
+ const column = page.locator('[data-editor-workspace-column]');
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await expect(information).toBeVisible();
+ for (const width of [1200, 1100, 1000, 900, 768, 1400]) {
+ await page.setViewportSize({ width, height: 800 });
+ await settleFrames(page);
+ await expect.poll(() => widthOf(column)).toBeGreaterThanOrEqual(300);
+ await expect(toggle).toBeVisible();
+ await expect
+ .poll(() =>
+ toggle.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ return element.contains(
+ document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2),
+ );
+ }),
+ )
+ .toBe(true);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ width,
+ );
+ }
+ await expect(information).toBeVisible();
+ await toggle.click();
+ await expect(information).toBeHidden();
+});
+
+for (const input of ['pointer', 'keyboard']) {
+ test(`resizing information with ${input} keeps the document and its toggle usable`, async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-min-width-${input}-${test.info().workerIndex}`;
+ await page.addInitScript(() => {
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1000, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const information = page.locator('#doc-panel');
+ const column = page.locator('[data-editor-workspace-column]');
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await expect(information).toBeVisible();
+ const handle = page.locator('[data-doc-panel-handle]');
+ if (input === 'pointer') {
+ const bounds = await handle.boundingBox();
+ if (!bounds) throw new Error('missing information divider bounds');
+ await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(bounds.x - 200, bounds.y + bounds.height / 2, { steps: 12 });
+ await settleFrames(page);
+ await expect.poll(() => widthOf(column)).toBeGreaterThanOrEqual(300);
+ await expect(toggle).toBeVisible();
+ await page.mouse.up();
+ } else {
+ await handle.focus();
+ await page.keyboard.press('End');
+ }
+ await expect.poll(() => widthOf(column)).toBeGreaterThanOrEqual(300);
+ await expect(toggle).toBeVisible();
+ await expect
+ .poll(() =>
+ toggle.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ return element.contains(
+ document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2),
+ );
+ }),
+ )
+ .toBe(true);
+ await expect(information).toBeVisible();
+ await toggle.click();
+ await expect(information).toBeHidden();
+ });
+}
+
+test('constrained docking swaps sidebars, restores both, and preserves explicit hiding and widths', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docName = `editor-sidebar-switch-${crypto.randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '600');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const files = page.locator('[data-sidebar="trigger"]');
+ const informationToggle = page.locator('[data-doc-panel-toggle]');
+ const information = page.locator('#doc-panel');
+ const documentColumn = page.locator('[data-editor-workspace-column]');
+ await expect(information).toBeVisible();
+ await expect(files).toHaveAttribute('aria-expanded', 'true');
+ await page.setViewportSize({ width: 1000, height: 800 });
+ await expect(files).toHaveAttribute('aria-expanded', 'true');
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ await informationToggle.click();
+ await expect(information).toBeVisible();
+ await expect(files).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('[data-doc-panel-cover]')).toHaveCount(0);
+ await expect.poll(() => widthOf(documentColumn)).toBeGreaterThanOrEqual(300);
+ await expect.poll(() => widthOf(information)).toBeGreaterThanOrEqual(599);
+ await expect
+ .poll(async () => {
+ const documentBox = await documentColumn.boundingBox();
+ const informationBox = await information.boundingBox();
+ return documentBox != null && informationBox != null
+ ? documentBox.x + documentBox.width - informationBox.x
+ : Number.POSITIVE_INFINITY;
+ })
+ .toBeLessThanOrEqual(1);
+ await informationToggle.press('ControlOrMeta+Alt+KeyS');
+ await expect(files).toHaveAttribute('aria-expanded', 'true');
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ await expect.poll(() => widthOf(documentColumn)).toBeGreaterThanOrEqual(300);
+ await informationToggle.click();
+ await expect(information).toBeVisible();
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await expect(files).toHaveAttribute('aria-expanded', 'true');
+ await expect(information).toBeVisible();
+ await page.setViewportSize({ width: 1000, height: 800 });
+ await expect(files).toHaveAttribute('aria-expanded', 'true');
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ await files.click();
+ await expect(information).toBeVisible();
+ await expect(files).toHaveAttribute('aria-expanded', 'false');
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await expect(information).toBeVisible();
+ await expect(files).toHaveAttribute('aria-expanded', 'false');
+ await informationToggle.click();
+ await page.setViewportSize({ width: 1000, height: 800 });
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe('600');
+ expect(
+ (await page.context().cookies()).find((cookie) => cookie.name === 'sidebar_width')?.value,
+ ).toBe('288px');
+});
+
+test('asymmetric remembered sidebar widths use one cover regime without replacing their widths', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docName = `editor-sidebar-shared-cover-${crypto.randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '600');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await page.setViewportSize({ width: 800, height: 800 });
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ const informationToggle = page.locator('[data-doc-panel-toggle]');
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'false');
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ await filesTrigger.click();
+ const filesCover = page.locator('[data-files-cover]');
+ const card = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ await expect(filesCover).toBeVisible();
+ await expect
+ .poll(async () => Math.abs((await widthOf(filesCover)) - (await widthOf(card))))
+ .toBeLessThanOrEqual(1);
+ await page.locator('[data-files-back]').click();
+ await expect(filesTrigger).toBeVisible();
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'false');
+ await informationToggle.click();
+ const informationCover = page.locator('[data-doc-panel-cover]');
+ await expect(informationCover).toBeVisible();
+ await expect(filesCover).toHaveCount(0);
+ await expect
+ .poll(async () => Math.abs((await widthOf(informationCover)) - (await widthOf(card))))
+ .toBeLessThanOrEqual(1);
+ await page.locator('[data-doc-panel-back]').press('ControlOrMeta+Alt+KeyS');
+ await expect(filesCover).toBeVisible();
+ await expect(informationCover).toHaveCount(0);
+ await page.locator('[data-files-back]').click();
+ await expect(informationToggle).toBeVisible();
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect.poll(() => widthOf(page.locator('#doc-panel'))).toBeGreaterThanOrEqual(599);
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe('600');
+ expect(
+ (await page.context().cookies()).find((cookie) => cookie.name === 'sidebar_width')?.value,
+ ).toBe('288px');
+});
+
+test('resized Files and information widths survive reload and shared cover boundaries', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-resized-sidebar-history-${crypto.randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1600, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const files = page.locator('[data-slot="sidebar-gap"]');
+ const information = page.locator('#doc-panel');
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ const informationToggle = page.locator('[data-doc-panel-toggle]');
+ await expect(page.locator('#app-file-sidebar')).toBeVisible();
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(information).toBeVisible();
+ const initialFilesWidth = await widthOf(files);
+ const initialInformationWidth = await widthOf(information);
+
+ const filesRail = page.locator('[data-sidebar="rail"]');
+ const filesRailBounds = await filesRail.boundingBox();
+ if (!filesRailBounds) throw new Error('Files resize rail has no bounds');
+ const filesRailX = filesRailBounds.x + filesRailBounds.width / 2;
+ const filesRailY = filesRailBounds.y + filesRailBounds.height / 2;
+ await page.mouse.move(filesRailX, filesRailY);
+ await page.mouse.down();
+ await page.mouse.move(filesRailX + 60, filesRailY, { steps: 8 });
+ await page.mouse.up();
+ await expect.poll(() => widthOf(files)).toBeGreaterThan(initialFilesWidth + 40);
+
+ const informationHandle = page.locator('[data-doc-panel-handle]');
+ const informationHandleBounds = await informationHandle.boundingBox();
+ if (!informationHandleBounds) throw new Error('information resize handle has no bounds');
+ const informationHandleX = informationHandleBounds.x + informationHandleBounds.width / 2;
+ const informationHandleY = informationHandleBounds.y + informationHandleBounds.height / 2;
+ await page.mouse.move(informationHandleX, informationHandleY);
+ await page.mouse.down();
+ await page.mouse.move(informationHandleX - 140, informationHandleY, { steps: 8 });
+ await page.mouse.up();
+ await expect.poll(() => widthOf(information)).toBeGreaterThan(initialInformationWidth + 100);
+
+ const rememberedFilesWidth = await widthOf(files);
+ const rememberedInformationWidth = await widthOf(information);
+ const persistedFilesWidth = (await page.context().cookies()).find(
+ (cookie) => cookie.name === 'sidebar_width',
+ )?.value;
+ expect(persistedFilesWidth).toBeDefined();
+ const persistedFilesWidthPx = await page.evaluate((savedWidth) => {
+ const parsed = /^(\d+(?:\.\d+)?)(rem|px)$/.exec(savedWidth);
+ if (!parsed) throw new Error(`Invalid persisted Files width: ${savedWidth}`);
+ const rootFontSize = Number.parseFloat(getComputedStyle(document.documentElement).fontSize);
+ return Number(parsed[1]) * (parsed[2] === 'rem' ? rootFontSize : 1);
+ }, persistedFilesWidth ?? '');
+ expect(Math.abs(persistedFilesWidthPx - rememberedFilesWidth)).toBeLessThanOrEqual(1);
+ await expect
+ .poll(async () => {
+ const storedWidth = await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'));
+ return storedWidth == null
+ ? Number.POSITIVE_INFINITY
+ : Math.abs(Number.parseFloat(storedWidth) - rememberedInformationWidth);
+ })
+ .toBeLessThanOrEqual(1);
+
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('#app-file-sidebar')).toBeVisible();
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(information).toBeVisible();
+ await expect.poll(() => widthOf(files)).toBeCloseTo(rememberedFilesWidth, 0);
+ await expect.poll(() => widthOf(information)).toBeCloseTo(rememberedInformationWidth, 0);
+
+ for (const width of [1200, 1000, 800, 390]) {
+ await page.setViewportSize({ width, height: 800 });
+ await settleFrames(page);
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ width,
+ );
+ }
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'false');
+ await expect(informationToggle).toHaveAttribute('aria-expanded', 'false');
+ await filesTrigger.click();
+ const filesCover = page.locator('[data-files-cover]');
+ const card = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ await expect(filesCover).toBeVisible();
+ await expect
+ .poll(async () => Math.abs((await widthOf(filesCover)) - (await widthOf(card))))
+ .toBeLessThanOrEqual(1);
+ await page.locator('[data-files-back]').click();
+ await informationToggle.click();
+ const informationCover = page.locator('[data-doc-panel-cover]');
+ await expect(informationCover).toBeVisible();
+ await expect(filesCover).toHaveCount(0);
+ await expect
+ .poll(async () => Math.abs((await widthOf(informationCover)) - (await widthOf(card))))
+ .toBeLessThanOrEqual(1);
+ await page.locator('[data-doc-panel-back]').click();
+
+ for (const width of [800, 1000, 1200, 1600]) {
+ await page.setViewportSize({ width, height: 800 });
+ await settleFrames(page);
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ width,
+ );
+ }
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(information).toBeVisible();
+ await expect.poll(() => widthOf(files)).toBeCloseTo(rememberedFilesWidth, 0);
+ await expect.poll(() => widthOf(information)).toBeCloseTo(rememberedInformationWidth, 0);
+ for (const toggle of [filesTrigger, informationToggle]) {
+ await expect
+ .poll(() =>
+ toggle.evaluate((element) => {
+ const rect = element.getBoundingClientRect();
+ return element.contains(
+ document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2),
+ );
+ }),
+ )
+ .toBe(true);
+ }
+ const settledWidths = await Promise.all([widthOf(files), widthOf(information)]);
+ await settleFrames(page);
+ const afterSettling = await Promise.all([widthOf(files), widthOf(information)]);
+ expect(Math.abs(afterSettling[0] - settledWidths[0])).toBeLessThanOrEqual(1);
+ expect(Math.abs(afterSettling[1] - settledWidths[1])).toBeLessThanOrEqual(1);
+});
+
+test('editor covers suppress body-portaled comment and selection controls', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-covered-portals-${crypto.randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: '# Covered portals\n\nA quoted body passage.' }]);
+ const created = await page.request.post('/api/comments', {
+ data: { docName, quote: 'A quoted body passage.', body: 'A visible comment marker.' },
+ });
+ expect(created.ok()).toBe(true);
+ await page.setViewportSize({ width: 390, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const marker = page.locator('button[data-comment-thread]');
+ const bubble = page.getByTestId('bubble-menu-bar');
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(marker).toBeVisible();
+ await editor.click();
+ await page.keyboard.press('ControlOrMeta+A');
+ await expect(bubble).toBeVisible();
+ await page.locator('[data-sidebar="trigger"]').click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await expect(marker).toHaveCount(0);
+ await expect(bubble).toBeHidden();
+ await page.locator('[data-files-back]').click();
+ await expect(marker).toBeVisible();
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await expect(marker).toHaveCount(0);
+ await expect(bubble).toBeHidden();
+ await page.locator('[data-doc-panel-back]').click();
+ await expect(marker).toBeVisible();
+});
+
+test('information yields before Files when only the editor card becomes narrow', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-fit-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1800, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await openChat(page);
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ const initialEditorWidth = await widthOf(
+ page.locator('[data-slot="pane-card"][data-pane="editor"]'),
+ );
+
+ await dragChatDivider(page, 0, -400, async () => {
+ expect(await widthOf(page.locator('[data-slot="pane-card"][data-pane="editor"]'))).toBeLessThan(
+ 900,
+ );
+ });
+
+ await expect(page.locator('#doc-panel')).not.toBeVisible();
+ await expect(page.locator('[data-sidebar="sidebar"]')).toBeVisible();
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(1800);
+
+ await dragChatDivider(page, 0, -320, async () => {});
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'false');
+ await filesTrigger.click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await expect(page.locator('[data-doc-panel-cover]')).not.toBeVisible();
+ await page.locator('[data-files-back]').click();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(1800);
+ await dragChatDivider(page, 0, 320, async () => {});
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('#doc-panel')).not.toBeVisible();
+ await dragChatDivider(page, 0, 400, async () => {});
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ await expect
+ .poll(() => widthOf(page.locator('[data-slot="pane-card"][data-pane="editor"]')))
+ .toBeGreaterThanOrEqual(initialEditorWidth - 2);
+});
+
+test('Escape outside either cover beside Chat leaves it open and focus in place', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-cover-escape-scope-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1800, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await openChat(page);
+ await dragChatDivider(page, 0, -400, async () => {});
+ await dragChatDivider(page, 0, -320, async () => {});
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'false');
+ await filesTrigger.click();
+ const cover = page.locator('[data-files-cover]');
+ await expect(cover).toBeVisible();
+ await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
+
+ const outside = page
+ .locator(`${AGENTS_PANEL_MOUNT} button:not([data-slot="tooltip-trigger"]):visible`)
+ .first();
+ await outside.focus();
+ await expect(outside).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(cover).toBeVisible();
+ await expect(outside).toBeFocused();
+
+ await page.locator('[data-files-back]').focus();
+ await page.keyboard.press('Escape');
+ await expect(cover).toBeHidden();
+
+ await page.locator('[data-doc-panel-toggle]').click();
+ const informationCover = page.locator('[data-doc-panel-cover]');
+ await expect(informationCover).toBeVisible();
+ const coverBox = await informationCover.boundingBox();
+ if (coverBox == null) throw new Error('information cover has no box');
+ await page.mouse.move(coverBox.x + coverBox.width / 2, coverBox.y + coverBox.height / 2);
+ await expect(page.locator('[data-slot="tooltip-content"]')).toHaveCount(0);
+ await outside.focus();
+ await expect(outside).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(informationCover).toBeVisible();
+ await expect(outside).toBeFocused();
+
+ await page.locator('[data-doc-panel-back]').focus();
+ await page.keyboard.press('Escape');
+ await expect(informationCover).toBeHidden();
+});
+
+test('Files opens as a full editor cover and Back preserves docking intent', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-files-cover-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 390, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const editorCard = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ const trigger = page.locator('[data-sidebar="trigger"]');
+ await trigger.click();
+ const cover = page.locator('[data-files-cover]');
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('button', { name: 'Back to editor', exact: true })).toBeFocused();
+ await expect(page.locator('[data-slot="sidebar-inset"]')).toHaveAttribute('inert', '');
+ const cardBounds = await editorCard.boundingBox();
+ const coverBounds = await cover.boundingBox();
+ expect(Math.abs((cardBounds?.x ?? 0) - (coverBounds?.x ?? 0))).toBeLessThanOrEqual(1);
+ expect(Math.abs((cardBounds?.width ?? 0) - (coverBounds?.width ?? 0))).toBeLessThanOrEqual(1);
+ for (const width of [320, 360, 430]) {
+ await page.setViewportSize({ width, height: 560 });
+ await expect(cover.getByRole('button', { name: 'Back to editor', exact: true })).toBeVisible();
+ await cover.getByRole('button', { name: 'Tree view options' }).click();
+ await expect(page.getByRole('menuitem', { name: 'Hide Files', exact: true })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menu')).toBeHidden();
+ await expect(cover).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ width,
+ );
+ }
+ await cover.getByRole('button', { name: 'Back to editor', exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(page.locator('[data-sidebar="sidebar"]')).toBeVisible();
+});
+
+for (const panel of ['Files', 'information'] as const) {
+ test(`${panel} cover replaces the editor header and returns through its own Back control`, async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-cover-header-${panel}-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 390, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const editorCard = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ const header = editorCard.locator('[data-editor-area-header]');
+ const trigger = page.locator(
+ panel === 'Files' ? '[data-sidebar="trigger"]' : '[data-doc-panel-toggle]',
+ );
+ const cover = page.locator(panel === 'Files' ? '[data-files-cover]' : '[data-doc-panel-cover]');
+ await expect(header).toBeVisible();
+ await trigger.click();
+ await expect(cover).toBeVisible();
+ await expect(header).toBeHidden();
+ const back = cover.getByRole('button', { name: 'Back to editor', exact: true });
+ await expect(back).toBeVisible();
+ await expect(back).toBeFocused();
+ await expect(
+ cover.getByRole('heading', { name: panel === 'Files' ? 'Files' : docName }),
+ ).toBeVisible();
+ const cardBounds = await editorCard.boundingBox();
+ const coverBounds = await cover.boundingBox();
+ expect(cardBounds).not.toBeNull();
+ expect(coverBounds).not.toBeNull();
+ for (const axis of ['x', 'y', 'width', 'height'] as const) {
+ expect(Math.abs((cardBounds?.[axis] ?? 0) - (coverBounds?.[axis] ?? 0))).toBeLessThanOrEqual(
+ 1,
+ );
+ }
+ const screenshotPath = test.info().outputPath(`${panel}-full-editor-cover.png`);
+ await editorCard.screenshot({ path: screenshotPath });
+ await test.info().attach(`${panel}-full-editor-cover`, {
+ path: screenshotPath,
+ contentType: 'image/png',
+ });
+ await back.click();
+ await expect(cover).toBeHidden();
+ await expect(header).toBeVisible();
+ await expect(trigger).toBeFocused();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Side panel width',
+ );
+ await trigger.click();
+ await expect(cover).toBeVisible();
+ await expect(back).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(cover).toBeHidden();
+ await expect(header).toBeVisible();
+ await expect(trigger).toBeFocused();
+ });
+}
+
+test('dock and cover moves keep the document panel and Files scroll positions', async ({
+ page,
+ api,
+}) => {
+ const index = test.info().workerIndex;
+ const docName = `editor-card-scroll-keep-${index}`;
+ const headings = Array.from({ length: 80 }, (_, n) => `## Heading ${n}\n\nBody ${n}.`).join(
+ '\n\n',
+ );
+ await api.seedDocs([
+ { name: docName, markdown: `# Scroll keep\n\n${headings}` },
+ ...Array.from({ length: 60 }, (_, n) => ({
+ name: `editor-card-scroll-file-${String(n).padStart(2, '0')}-${index}`,
+ markdown: `# File ${n}\n`,
+ })),
+ ]);
+ await page.setViewportSize({ width: 1600, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('#doc-panel').getByRole('tab', { name: 'Outline' }).click();
+ const markScroller = (rootSelector: string, marker: string, top: number) =>
+ page.evaluate(
+ ({ rootSelector, marker, top }) => {
+ const root = document.querySelector<HTMLElement>(rootSelector);
+ const ancestors: HTMLElement[] = [];
+ for (let element = root?.parentElement ?? null; element; element = element.parentElement) {
+ ancestors.push(element);
+ }
+ const scroller = [
+ ...Array.from(root?.querySelectorAll<HTMLElement>('*') ?? []),
+ ...ancestors,
+ ].find(
+ (element) =>
+ element.scrollHeight > element.clientHeight + 100 &&
+ /auto|scroll/.test(getComputedStyle(element).overflowY),
+ );
+ if (!scroller) return false;
+ scroller.setAttribute(marker, '');
+ scroller.scrollTo({ top, behavior: 'instant' });
+ return true;
+ },
+ { rootSelector, marker, top },
+ );
+ const scrollOf = (marker: string) =>
+ page.evaluate((marker) => document.querySelector(`[${marker}]`)?.scrollTop ?? -1, marker);
+ await expect.poll(() => markScroller('#doc-panel', 'data-test-doc-scroller', 400)).toBe(true);
+ await expect.poll(() => scrollOf('data-test-doc-scroller')).toBe(400);
+ const trigger = page.locator('[data-sidebar="trigger"]');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const filesTree = page
+ .getByRole('tree')
+ .filter({ has: page.getByRole('treeitem', { name: /editor-card-scroll-file-/ }) })
+ .first();
+ await expect(filesTree).toBeVisible();
+ const filesScroll = (top?: number) =>
+ filesTree.evaluate((tree, top) => {
+ const candidates = [
+ tree as HTMLElement,
+ ...Array.from(tree.querySelectorAll<HTMLElement>('*')),
+ ];
+ for (let parent = tree.parentElement; parent; parent = parent.parentElement) {
+ candidates.push(parent);
+ }
+ const element = candidates.find(
+ (candidate) =>
+ candidate.scrollHeight > candidate.clientHeight + 100 &&
+ /auto|scroll/.test(getComputedStyle(candidate).overflowY),
+ );
+ if (!element) return -1;
+ if (top !== undefined) element.scrollTo({ top, behavior: 'instant' });
+ return element.scrollTop;
+ }, top);
+ await expect.poll(() => filesScroll(300)).toBe(300);
+ await expect.poll(() => filesScroll()).toBe(300);
+
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await expect.poll(() => scrollOf('data-test-doc-scroller')).toBe(400);
+ await page.locator('[data-doc-panel-back]').click();
+ await page.locator('[data-sidebar="trigger"]').click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await expect.poll(() => filesScroll()).toBe(300);
+ await page.keyboard.press('Escape');
+ await expect(page.locator('[data-files-cover]')).not.toBeVisible();
+
+ await page.setViewportSize({ width: 1600, height: 700 });
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect.poll(() => scrollOf('data-test-doc-scroller')).toBe(400);
+ await expect.poll(() => filesScroll()).toBe(300);
+});
+
+test('Files cover folder and asset picks leave focus on a usable control', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `editor-card-files-focus-${test.info().workerIndex}`;
+ const folder = `editor-card-files-folder-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: docName, markdown: '# Files focus\n' },
+ { name: `${folder}/inside`, markdown: '# Inside folder\n' },
+ ]);
+ const asset = `editor-card-files-asset-${test.info().workerIndex}.png`;
+ writeFileSync(
+ join(workerServer.contentDir, asset),
+ Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
+ 'base64',
+ ),
+ );
+ await page.setViewportSize({ width: 390, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const trigger = page.locator('[data-sidebar="trigger"]');
+ const cover = page.locator('[data-files-cover]');
+ const focusIsUsable = () =>
+ page.evaluate(() => {
+ const active = document.activeElement;
+ return (
+ active !== null &&
+ active !== document.body &&
+ active.closest('[inert]') === null &&
+ active.getClientRects().length > 0
+ );
+ });
+ for (const name of [folder, asset]) {
+ await trigger.click();
+ await expect(cover).toBeVisible();
+ await cover.getByRole('treeitem', { name, exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await expect.poll(focusIsUsable).toBe(true);
+ }
+});
+
+test('Escape during text composition does not dismiss either cover', async ({ page, api }) => {
+ const docName = `editor-card-ime-escape-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Composition\n' }]);
+ await page.setViewportSize({ width: 390, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const composingEscape = () =>
+ page.evaluate(() => {
+ document.body.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'Escape', isComposing: true, bubbles: true }),
+ );
+ });
+ await page.locator('[data-sidebar="trigger"]').click();
+ const filesCover = page.locator('[data-files-cover]');
+ await expect(filesCover).toBeVisible();
+ await composingEscape();
+ await expect(filesCover).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(filesCover).not.toBeVisible();
+
+ await page.locator('[data-doc-panel-toggle]').click();
+ const docCover = page.locator('[data-doc-panel-cover]');
+ await expect(docCover).toBeVisible();
+ await composingEscape();
+ await expect(docCover).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(docCover).not.toBeVisible();
+});
+
+test('Files cover selection reveals its document while Hide keeps Files off after widening', async ({
+ page,
+ api,
+}) => {
+ const first = `editor-card-files-first-${test.info().workerIndex}`;
+ const second = `editor-card-files-second-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: first, markdown: DOC_MARKDOWN },
+ { name: second, markdown: '# Second file\n\nSelected from the Files cover.' },
+ ]);
+ const readServerDocument = async (name: string) => {
+ const response = await page.request.get(`/api/document?docName=${encodeURIComponent(name)}`);
+ expect(response.ok()).toBe(true);
+ const document = (await response.json()) as { content: string };
+ return document.content;
+ };
+ const originalBytes = await Promise.all([readServerDocument(first), readServerDocument(second)]);
+ await page.setViewportSize({ width: 1600, height: 700 });
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+
+ const trigger = page.locator('[data-sidebar="trigger"]');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect.poll(() => widthOf(page.locator('[data-slot="sidebar-gap"]'))).toBeGreaterThan(200);
+ const rememberedWidth = await widthOf(page.locator('[data-slot="sidebar-gap"]'));
+ await page.setViewportSize({ width: 390, height: 700 });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await trigger.click();
+ const cover = page.locator('[data-files-cover]');
+ await expect(cover).toBeVisible();
+ await cover.getByRole('treeitem', { name: `${second}.md`, exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editor).toContainText('Selected from the Files cover.');
+ await expect(editor).toBeFocused();
+ expect(
+ await editor.evaluate((element) => element.contains(window.getSelection()?.anchorNode ?? null)),
+ ).toBe(true);
+ await trigger.click();
+ await expect(cover).toBeVisible();
+ await cover.getByRole('treeitem', { name: `${second}.md`, exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(editor).toContainText('Selected from the Files cover.');
+ await expect(editor).toBeFocused();
+ expect(
+ await editor.evaluate((element) => element.contains(window.getSelection()?.anchorNode ?? null)),
+ ).toBe(true);
+ await page.setViewportSize({ width: 1600, height: 700 });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect
+ .poll(() => widthOf(page.locator('[data-slot="sidebar-gap"]')))
+ .toBeCloseTo(rememberedWidth, 0);
+ await page.setViewportSize({ width: 390, height: 700 });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await trigger.click();
+ await expect(cover).toBeVisible();
+ await expect(cover.locator(':scope > div').first().getByRole('button')).toHaveCount(1);
+ await cover.getByRole('button', { name: 'Tree view options' }).click();
+ await page.getByRole('menuitem', { name: 'Hide Files', exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(trigger).toBeFocused();
+ await page.setViewportSize({ width: 1600, height: 700 });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#app-file-sidebar')).toHaveAttribute('inert', '');
+ await trigger.click();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('#app-file-sidebar')).toBeVisible();
+ await expect
+ .poll(() => widthOf(page.locator('[data-slot="sidebar-gap"]')))
+ .toBeCloseTo(rememberedWidth, 0);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Selected from the Files cover.',
+ );
+ expect(await Promise.all([readServerDocument(first), readServerDocument(second)])).toEqual(
+ originalBytes,
+ );
+});
+
+test('Files menu Hide is reachable by touch and keyboard without a second cover header button', async ({
+ browser,
+ api,
+ baseURL,
+}) => {
+ const docName = `editor-files-hide-menu-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ const context = await browser.newContext({
+ baseURL,
+ hasTouch: true,
+ viewport: { width: 320, height: 560 },
+ });
+ const page = await context.newPage();
+ try {
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const trigger = page.locator('[data-sidebar="trigger"]');
+ const cover = page.locator('[data-files-cover]');
+ await trigger.tap();
+ await expect(cover).toBeVisible();
+ await expect(cover.locator(':scope > div').first().getByRole('button')).toHaveCount(1);
+ await cover.getByRole('button', { name: 'Tree view options' }).tap();
+ await page.getByRole('menuitem', { name: 'Hide Files', exact: true }).tap();
+ await expect(cover).toBeHidden();
+ await expect(trigger).toBeFocused();
+ await trigger.press('Enter');
+ await expect(cover.getByRole('button', { name: 'Back to editor', exact: true })).toBeFocused();
+ await cover.getByRole('button', { name: 'Tree view options' }).press('Enter');
+ const hide = page.getByRole('menuitem', { name: 'Hide Files', exact: true });
+ await expect(hide).toBeVisible();
+ await expect
+ .poll(() =>
+ page
+ .getByTestId('tree-options-menu')
+ .evaluate((menu) => menu.contains(document.activeElement)),
+ )
+ .toBe(true);
+ await page.keyboard.press('End');
+ await expect(hide).toBeFocused();
+ await hide.press('Enter');
+ await expect(cover).toBeHidden();
+ await expect(trigger).toBeFocused();
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#app-file-sidebar')).toHaveAttribute('inert', '');
+ } finally {
+ await context.close();
+ }
+});
+
+test('Files and information covers replace one another without stacking', async ({ page, api }) => {
+ const pageErrors: string[] = [];
+ const consoleWarnings: string[] = [];
+ const failingResponses: Array<{ status: number; path: string }> = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ page.on('console', (message) => {
+ if (message.type() === 'warning' || message.type() === 'error') {
+ consoleWarnings.push(message.text());
+ }
+ });
+ page.on('response', (response) => {
+ if (response.status() >= 400) {
+ failingResponses.push({ status: response.status(), path: new URL(response.url()).pathname });
+ }
+ });
+ const docName = `editor-card-cover-switch-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 390, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const files = page.locator('[data-files-cover]');
+ const information = page.locator('[data-doc-panel-cover]');
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ const informationToggle = page.locator('[data-doc-panel-toggle]');
+ const filesBack = files.locator('[data-files-back]');
+ const informationBack = information.locator('[data-doc-panel-back]');
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ const editorHeader = page.locator('[data-editor-area-header]');
+ const visibleCovers = page.locator('[data-files-cover]:visible, [data-doc-panel-cover]:visible');
+
+ await filesTrigger.click();
+ await expect(files).toBeVisible();
+ await expect(visibleCovers).toHaveCount(1);
+ await expect(filesBack).toBeFocused();
+ await page.keyboard.press('Alt+Meta+B');
+ await expect(files).not.toBeVisible();
+ await expect(information).toBeVisible();
+ await expect(visibleCovers).toHaveCount(1);
+ await expect(informationBack).toBeFocused();
+ await page.keyboard.press('Alt+Meta+S');
+ await expect(information).not.toBeVisible();
+ await expect(files).toBeVisible();
+ await expect(visibleCovers).toHaveCount(1);
+ await expect(filesBack).toBeFocused();
+
+ await filesBack.click();
+ await expect(visibleCovers).toHaveCount(0);
+ await expect(editorHeader).toBeVisible();
+ await expect(filesTrigger).toBeFocused();
+
+ await informationToggle.click();
+ await expect(information).toBeVisible();
+ await expect(informationBack).toBeFocused();
+ await informationBack.click();
+ await expect(visibleCovers).toHaveCount(0);
+ await expect(editorHeader).toBeVisible();
+ await expect(informationToggle).toBeFocused();
+
+ await informationToggle.click();
+ await expect(information).toBeVisible();
+ await expect(informationBack).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(visibleCovers).toHaveCount(0);
+ await expect(editorHeader).toBeVisible();
+ await expect(informationToggle).toBeFocused();
+
+ await filesTrigger.click();
+ await expect(files).toBeVisible();
+ await expect(filesBack).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(visibleCovers).toHaveCount(0);
+ await expect(editorHeader).toBeVisible();
+ await expect(filesTrigger).toBeFocused();
+
+ await editor.locator('p').last().click();
+ await expect(editor).toBeFocused();
+ await page.keyboard.type(' Cover dismissed.');
+ await expect(editor).toContainText('Cover dismissed.');
+ const editorBounds = await editor.boundingBox();
+ expect(editorBounds).not.toBeNull();
+ expect(
+ await editor.evaluate((element, bounds) => {
+ const hit = document.elementFromPoint(
+ bounds.x + bounds.width / 2,
+ bounds.y + bounds.height / 2,
+ );
+ return hit !== null && element.contains(hit);
+ }, editorBounds),
+ ).toBe(true);
+
+ const screenshotPath = test.info().outputPath('Files-information-cover-switching.png');
+ await page.screenshot({ path: screenshotPath });
+ await test.info().attach('Files-information-cover-switching', {
+ path: screenshotPath,
+ contentType: 'image/png',
+ });
+ const signalsPath = test.info().outputPath('Files-information-runtime-signals.json');
+ writeFileSync(signalsPath, JSON.stringify({ pageErrors, consoleWarnings, failingResponses }));
+ await test.info().attach('Files-information-runtime-signals', {
+ path: signalsPath,
+ contentType: 'application/json',
+ });
+ expect(pageErrors).toEqual([]);
+});
+
+for (const rememberedFilesWidth of [234, 288, 512]) {
+ test(`Files fitting retains its ${rememberedFilesWidth}px remembered dock width`, async ({
+ page,
+ api,
+ baseURL,
+ }) => {
+ const docName = `editor-card-files-width-${rememberedFilesWidth}-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page
+ .context()
+ .addCookies([{ name: 'sidebar_width', value: `${rememberedFilesWidth}px`, url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({ left: { above: 'open', below: 'open', embedded: 'open' } }),
+ );
+ });
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const trigger = page.locator('[data-sidebar="trigger"]');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const dockedWidth = await widthOf(page.locator('[data-slot="sidebar-gap"]'));
+ expect(Math.abs(dockedWidth - rememberedFilesWidth)).toBeLessThanOrEqual(1);
+
+ await page.setViewportSize({ width: 650, height: 700 });
+ if (rememberedFilesWidth === 512) {
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await trigger.click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await page.locator('[data-files-back]').click();
+ } else {
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ }
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect
+ .poll(async () =>
+ Math.abs((await widthOf(page.locator('[data-slot="sidebar-gap"]'))) - dockedWidth),
+ )
+ .toBeLessThanOrEqual(1);
+ expect(
+ (await page.context().cookies(baseURL)).find((cookie) => cookie.name === 'sidebar_width')
+ ?.value,
+ ).toBe(`${rememberedFilesWidth}px`);
+ });
+}
+
+test('information cover Back restores docking while Hide keeps it closed', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-cover-${crypto.randomUUID()}`;
+ const pageErrors: string[] = [];
+ const consoleErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ page.on('console', (message) => {
+ if (message.type() === 'error') consoleErrors.push(message.text());
+ });
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1800, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const information = page.locator('#doc-panel');
+ await expect(information).toBeVisible();
+ await information.getByRole('tab', { name: 'Links' }).click();
+ await expect(information.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ const dockedInformationWidth = await widthOf(information);
+ await openChat(page);
+ await expect(information).toBeVisible();
+ await dragChatDivider(page, 0, -400, async () => {});
+ await dragChatDivider(page, 0, -320, async () => {});
+ await expect(information).not.toBeVisible();
+
+ const editorCard = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ const constrainedEditorWidth = await widthOf(editorCard);
+ expect(constrainedEditorWidth).toBeLessThan(620);
+ const savedWidthBefore = await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'));
+ await toggle.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await expect(page.locator('[data-doc-panel-back]')).toBeFocused();
+ await expect(page.locator('[data-slot="sidebar-inset"]')).toHaveAttribute('inert', '');
+ await expect(page.locator('[data-doc-panel-handle]')).not.toBeVisible();
+ const cardBounds = await editorCard.boundingBox();
+ const coverBounds = await cover.boundingBox();
+ expect(cardBounds).not.toBeNull();
+ expect(coverBounds).not.toBeNull();
+ expect(Math.abs((cardBounds?.x ?? 0) - (coverBounds?.x ?? 0))).toBeLessThanOrEqual(1);
+ expect(Math.abs((cardBounds?.width ?? 0) - (coverBounds?.width ?? 0))).toBeLessThanOrEqual(1);
+ const coverScreenshot = test.info().outputPath('qa-020-information-cover.png');
+ await page.screenshot({ path: coverScreenshot, fullPage: true });
+ await test.info().attach('qa-020-information-cover', {
+ path: coverScreenshot,
+ contentType: 'image/png',
+ });
+
+ await page.locator('[data-doc-panel-back]').click();
+ await expect(cover).not.toBeVisible();
+ await expect(toggle).toBeFocused();
+ await dragChatDivider(page, 0, 320, async () => {});
+ await dragChatDivider(page, 0, 400, async () => {});
+ await expect(information).toBeVisible();
+ await expect(information.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await expect
+ .poll(async () => Math.abs((await widthOf(information)) - dockedInformationWidth))
+ .toBeLessThanOrEqual(1);
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe(
+ savedWidthBefore,
+ );
+
+ await dragChatDivider(page, 0, -400, async () => {});
+ await dragChatDivider(page, 0, -320, async () => {});
+ await expect(information).not.toBeVisible();
+ await toggle.click();
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await page.locator('[data-doc-panel-hide]').click();
+ await expect(cover).not.toBeVisible();
+ await dragChatDivider(page, 0, 320, async () => {});
+ await dragChatDivider(page, 0, 400, async () => {});
+ await expect(information).not.toBeVisible();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ const hiddenScreenshot = test.info().outputPath('qa-020-information-hidden.png');
+ await page.screenshot({ path: hiddenScreenshot, fullPage: true });
+ await test.info().attach('qa-020-information-hidden', {
+ path: hiddenScreenshot,
+ contentType: 'image/png',
+ });
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe(
+ savedWidthBefore,
+ );
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ console.log(
+ JSON.stringify({
+ scenario: 'QA-020',
+ constrainedEditorWidth,
+ dockedInformationWidth,
+ selectedTab: 'Links',
+ backRestoredInformation: true,
+ hideKeptInformationClosed: true,
+ savedWidthBefore,
+ savedWidthAfter: await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1')),
+ pageErrors,
+ consoleErrors,
+ }),
+ );
+});
+
+test('navigating from an information cover to a folder releases the Editor inset', async ({
+ page,
+ api,
+}) => {
+ const folder = `editor-card-cover-folder-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: `${folder}/document`, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${folder}/document`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await page.evaluate((nextFolder) => {
+ window.location.hash = `#/${nextFolder}`;
+ }, folder);
+ await expect(page.locator('[data-doc-panel-cover]')).not.toBeVisible();
+ await expect(page.locator('[data-slot="sidebar-inset"]')).not.toHaveAttribute('inert', '');
+ await expect(page.getByTestId('header-pane-button-editor')).toBeFocused();
+});
+
+test('resize docking preserves focus in the Files and information panels', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-cover-focus-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ await page.locator('[data-sidebar="trigger"]').click();
+ const filesCover = page.locator('[data-files-cover]');
+ const file = filesCover.getByRole('treeitem', { name: `${docName}.md`, exact: true });
+ await file.focus();
+ await expect(file).toBeFocused();
+ await page.setViewportSize({ width: 1100, height: 700 });
+ await expect(filesCover).not.toBeVisible();
+ await expect(page.getByRole('treeitem', { name: `${docName}.md`, exact: true })).toBeFocused();
+
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.locator('[data-doc-panel-toggle]').click();
+ const infoCover = page.locator('[data-doc-panel-cover]');
+ const outline = infoCover.getByRole('tab', { name: 'Outline' });
+ await outline.focus();
+ await expect(outline).toBeFocused();
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await expect(infoCover).not.toBeVisible();
+ await expect(page.locator('#doc-panel').getByRole('tab', { name: 'Outline' })).toBeFocused();
+});
+
+test.describe('information cover on a short touch viewport', () => {
+ test.use({ hasTouch: true, viewport: { width: 320, height: 480 } });
+
+ test('Hide remains reachable with long labels and keeps information closed after widening', async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-card-info-touch-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await page.goto(`/?lang=pseudo#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await expect(toggle).toBeVisible();
+ await toggle.tap();
+ const cover = page.locator('[data-doc-panel-cover]');
+ const back = cover.locator('[data-doc-panel-back]');
+ const hide = cover.locator('[data-doc-panel-hide]');
+ await expect(cover).toBeVisible();
+ await expect(back).toBeFocused();
+ await expect(hide).toHaveAccessibleName('Ĥĩďē ƥàńēĺ');
+ await expect(page.locator('[data-slot="sidebar-inset"]')).toHaveAttribute('inert', '');
+ const controlsFit = await page.evaluate(() => {
+ const cover = document.querySelector('[data-doc-panel-cover]');
+ const back = document.querySelector('[data-doc-panel-back]');
+ const hide = document.querySelector('[data-doc-panel-hide]');
+ if (!cover || !back || !hide) return false;
+ const bounds = [cover, back, hide].map((element) => element.getBoundingClientRect());
+ return bounds.every(
+ (rect) =>
+ rect.width > 0 &&
+ rect.height > 0 &&
+ rect.left >= 0 &&
+ rect.right <= window.innerWidth &&
+ rect.top >= 0 &&
+ rect.bottom <= window.innerHeight,
+ );
+ });
+ expect(controlsFit).toBe(true);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ 320,
+ );
+
+ await hide.tap();
+ await expect(cover).not.toBeVisible();
+ await expect(toggle).toBeFocused();
+ await page.setViewportSize({ width: 1000, height: 480 });
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#doc-panel')).not.toBeVisible();
+ });
+
+ test('Back remains reachable and returns focus in a right-to-left interface', async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-card-info-rtl-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect
+ .poll(() => page.evaluate(() => localStorage.getItem('ok-language-v1')))
+ .not.toBeNull();
+ await page.evaluate(() => {
+ document.documentElement.dir = 'rtl';
+ });
+ await expect(page.locator('html')).toHaveAttribute('dir', 'rtl');
+
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await toggle.tap();
+ const cover = page.locator('[data-doc-panel-cover]');
+ const back = cover.locator('[data-doc-panel-back]');
+ const hide = cover.locator('[data-doc-panel-hide]');
+ await expect(cover).toBeVisible();
+ await expect(back).toBeFocused();
+ for (const control of [back, hide]) {
+ const bounds = await control.boundingBox();
+ expect(bounds).not.toBeNull();
+ expect(bounds?.x).toBeGreaterThanOrEqual(0);
+ expect((bounds?.x ?? 0) + (bounds?.width ?? 0)).toBeLessThanOrEqual(320);
+ }
+ await back.tap();
+ await expect(cover).not.toBeVisible();
+ await expect(toggle).toBeFocused();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ 320,
+ );
+ });
+});
+
+test('information cover Back returns focus to the visible header when its opener detaches', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-detached-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 390, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await toggle.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ await toggle.evaluate((element) => element.remove());
+ await cover.locator('[data-doc-panel-back]').click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.getByTestId('header-pane-button-editor')).toBeFocused();
+ expect(await page.evaluate(() => document.activeElement?.closest('[inert]'))).toBeNull();
+});
+
+test('information cover keeps every document tab usable at narrow browser widths', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-tabs-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('#doc-panel')).not.toBeVisible();
+
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await toggle.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ for (const label of ['Outline', 'Links', 'Graph', 'Timeline', 'Problems', 'Comments']) {
+ const tab = cover.getByRole('tab', { name: label });
+ await tab.click();
+ await expect(tab).toHaveAttribute('data-state', 'on');
+ await expect(cover).toBeVisible();
+ }
+ await cover.getByRole('tab', { name: 'Graph' }).click();
+ await cover.getByRole('button', { name: 'Expand graph' }).click();
+ await expect(page.getByRole('button', { name: 'Collapse graph' })).toBeVisible();
+ await page.mouse.move(0, 0);
+ await page.keyboard.press('Escape');
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('button', { name: 'Expand graph' })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(cover).not.toBeVisible();
+ await expect(toggle).toBeFocused();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(430);
+
+ await page.setViewportSize({ width: 320, height: 480 });
+ await expect(toggle).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(320);
+
+ await page.setViewportSize({ width: 650, height: 700 });
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ expect(await widthOf(page.locator('[data-editor-workspace-column]'))).toBeLessThan(350);
+ await expect(toggle).toBeVisible();
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editor).toBeVisible();
+ await editor.click();
+ await page.keyboard.type(' editor fit');
+ await expect(editor).toContainText('editor fit');
+ const geometry = await page.evaluate(() => ({
+ viewport: window.innerWidth,
+ document: document.querySelector('[data-editor-workspace-column]')?.getBoundingClientRect()
+ .width,
+ information: document.querySelector('#doc-panel')?.getBoundingClientRect().width,
+ page: document.documentElement.scrollWidth,
+ }));
+ await test.info().attach('information-fit.json', {
+ body: JSON.stringify(geometry),
+ contentType: 'application/json',
+ });
+ await test.info().attach('information-fit.png', {
+ body: await page.screenshot(),
+ contentType: 'image/png',
+ });
+ for (const [width, docked] of [
+ [620, false],
+ [650, true],
+ [620, false],
+ [650, true],
+ ] as const) {
+ await page.setViewportSize({ width, height: 700 });
+ if (docked) await expect(page.locator('#doc-panel')).toBeVisible();
+ else await expect(page.locator('#doc-panel')).not.toBeVisible();
+ await settleFrames(page);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
+ width,
+ );
+ }
+});
+
+test('editor mode controls remain usable beside information at the document fit budget', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-control-fit-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await page.setViewportSize({ width: 650, height: 700 });
+ await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('#doc-panel')).not.toBeVisible();
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute('aria-expanded', 'false');
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ expect(await widthOf(page.locator('[data-editor-workspace-column]'))).toBeLessThan(350);
+
+ const sourceMode = page.getByRole('radio', { name: 'Markdown source' });
+ await expect(sourceMode).toBeInViewport();
+ await sourceMode.click();
+ const sourceEditor = page.locator('.cm-editor').first();
+ await expect(sourceEditor).toBeVisible();
+ await sourceEditor.locator('.cm-content').click();
+ await page.keyboard.type('source fit');
+ await expect(sourceEditor).toContainText('source fit');
+ await page.getByRole('radio', { name: 'Visual editor' }).click();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'source fit',
+ );
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(650);
+});
+
+test('browser zoom keeps the information cover and editor controls usable', async ({
+ api,
+ baseURL,
+}) => {
+ const docName = `editor-card-browser-zoom-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ const extensionDir = test.info().outputPath('browser-zoom-extension');
+ mkdirSync(extensionDir, { recursive: true });
+ writeFileSync(
+ join(extensionDir, 'manifest.json'),
+ JSON.stringify({
+ manifest_version: 3,
+ name: 'Open Knowledge browser zoom test',
+ version: '1.0.0',
+ permissions: ['tabs'],
+ background: { service_worker: 'background.js' },
+ }),
+ );
+ writeFileSync(
+ join(extensionDir, 'background.js'),
+ 'chrome.runtime.onInstalled.addListener(() => {});\n',
+ );
+
+ const browserContext = await chromium.launchPersistentContext('', {
+ channel: 'chromium',
+ headless: true,
+ viewport: { width: 1400, height: 720 },
+ args: [`--disable-extensions-except=${extensionDir}`, `--load-extension=${extensionDir}`],
+ });
+ try {
+ const zoomPage = await browserContext.newPage();
+ await zoomPage.goto(`${baseURL}/#/${docName}`);
+ await waitForActiveProviderSynced(zoomPage);
+ const editor = zoomPage.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editor).toBeVisible();
+ await expect(zoomPage.locator('#doc-panel')).toBeVisible();
+ await expect(zoomPage.locator('[data-sidebar="sidebar"]')).toBeVisible();
+ const before = await zoomPage.evaluate(() => ({
+ innerWidth: window.innerWidth,
+ devicePixelRatio: window.devicePixelRatio,
+ visualScale: window.visualViewport?.scale,
+ }));
+ const serviceWorker =
+ browserContext.serviceWorkers()[0] ?? (await browserContext.waitForEvent('serviceworker'));
+ const browserZoom = await serviceWorker.evaluate(
+ async ({ origin, factor }) => {
+ const tabs = (
+ globalThis as typeof globalThis & {
+ chrome: {
+ tabs: {
+ query(queryInfo: object): Promise<Array<{ id?: number; url?: string }>>;
+ getZoom(tabId: number): Promise<number>;
+ getZoomSettings(tabId: number): Promise<{ mode?: string; scope?: string }>;
+ setZoomSettings(
+ tabId: number,
+ settings: { mode: string; scope: string },
+ ): Promise<void>;
+ setZoom(tabId: number, factor: number): Promise<void>;
+ };
+ };
+ }
+ ).chrome.tabs;
+ const tab = (await tabs.query({})).find((candidate) => candidate.url?.startsWith(origin));
+ if (tab?.id === undefined) throw new Error('the app tab is unavailable for browser zoom');
+ const initialFactor = await tabs.getZoom(tab.id);
+ await tabs.setZoomSettings(tab.id, { mode: 'automatic', scope: 'per-tab' });
+ await tabs.setZoom(tab.id, factor);
+ return {
+ initialFactor,
+ factor: await tabs.getZoom(tab.id),
+ settings: await tabs.getZoomSettings(tab.id),
+ };
+ },
+ { origin: baseURL, factor: 2.25 },
+ );
+ expect(browserZoom.initialFactor).toBe(1);
+ expect(browserZoom.factor).toBe(2.25);
+ expect(browserZoom.settings).toMatchObject({ mode: 'automatic', scope: 'per-tab' });
+ const after = await zoomPage.evaluate(() => ({
+ innerWidth: window.innerWidth,
+ devicePixelRatio: window.devicePixelRatio,
+ visualScale: window.visualViewport?.scale,
+ scrollWidth: document.documentElement.scrollWidth,
+ }));
+ expect(zoomPage.viewportSize()).toEqual({ width: 1400, height: 720 });
+ expect(after.innerWidth).toBeLessThan(before.innerWidth);
+ expect(after.devicePixelRatio).toBeGreaterThan(before.devicePixelRatio);
+ expect(after.visualScale).toBe(1);
+ await expect(zoomPage.locator('#doc-panel')).not.toBeVisible();
+ const toggle = zoomPage.locator('[data-doc-panel-toggle]');
+ await expect(toggle).toBeInViewport();
+ await toggle.click();
+ const cover = zoomPage.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ await expect(cover.locator('[data-doc-panel-back]')).toBeInViewport();
+ await expect(cover.locator('[data-doc-panel-hide]')).toBeInViewport();
+ await expect(zoomPage.locator('[data-slot="sidebar-inset"]')).toHaveAttribute('inert', '');
+ await cover.locator('[data-doc-panel-back]').click();
+ await expect(cover).not.toBeVisible();
+ const sourceMode = zoomPage.getByRole('radio', { name: 'Markdown source' });
+ await expect(sourceMode).toBeInViewport();
+ await sourceMode.click();
+ const sourceEditor = zoomPage.locator('.cm-editor').first();
+ await expect(sourceEditor).toBeVisible();
+ await sourceEditor.locator('.cm-content').click();
+ await zoomPage.keyboard.type('browser zoom fit');
+ await expect(sourceEditor).toContainText('browser zoom fit');
+ await expect
+ .poll(() => widthOf(zoomPage.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ const finalGeometry = await zoomPage.evaluate(() => ({
+ innerWidth: window.innerWidth,
+ scrollWidth: document.documentElement.scrollWidth,
+ documentWidth: document
+ .querySelector('[data-editor-workspace-column]')
+ ?.getBoundingClientRect().width,
+ }));
+ expect(finalGeometry.scrollWidth).toBeLessThanOrEqual(finalGeometry.innerWidth);
+ const geometryPath = test.info().outputPath('browser-zoom-fit.json');
+ writeFileSync(geometryPath, JSON.stringify({ before, browserZoom, after, finalGeometry }));
+ await test.info().attach('browser-zoom-fit.json', {
+ path: geometryPath,
+ contentType: 'application/json',
+ });
+ await test.info().attach('browser-zoom-fit.png', {
+ body: await zoomPage.screenshot(),
+ contentType: 'image/png',
+ });
+ } finally {
+ await browserContext.close();
+ }
+});
+
+test('each selected information tab survives automatic suppression and temporary cover dismissal', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-selected-tabs-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const panel = page.locator('#doc-panel');
+ const cover = page.locator('[data-doc-panel-cover]');
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await expect(panel).toBeVisible();
+
+ for (const label of ['Outline', 'Links', 'Graph', 'Timeline', 'Problems', 'Comments']) {
+ const tab = panel.getByRole('tab', { name: label });
+ await tab.click();
+ await expect(tab).toHaveAttribute('data-state', 'on');
+ await page.setViewportSize({ width: 430, height: 700 });
+ await expect(panel).not.toBeVisible();
+ await toggle.click();
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('tab', { name: label })).toHaveAttribute('data-state', 'on');
+ await cover.locator('[data-doc-panel-back]').click();
+ await expect(cover).not.toBeVisible();
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await expect(panel).toBeVisible();
+ await expect(tab).toHaveAttribute('data-state', 'on');
+ }
+});
+
+test('selected Activity yields with the information panel and returns after widening', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-activity-fit-${test.info().workerIndex}`;
+ const agentName = 'Activity Fit Agent';
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const panel = page.locator('#doc-panel');
+ await expect(panel).toBeVisible();
+ await api.writeAsAgent(docName, `${DOC_MARKDOWN}\n\nActivity update`, {
+ agentId: `activity-fit-${crypto.randomUUID().slice(0, 8)}`,
+ agentName,
+ clientName: 'claude-code',
+ });
+ const avatar = page
+ .locator(`[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="${agentName}"]`)
+ .first();
+ await expect(avatar).toBeVisible();
+ await avatar.click();
+ await expect(panel.getByTestId('activity-panel')).toBeVisible();
+
+ await page.setViewportSize({ width: 620, height: 700 });
+ await expect(panel).not.toBeVisible();
+ await expect(page.locator('[data-sidebar="sidebar"]')).toBeVisible();
+ await expect
+ .poll(() => widthOf(page.locator('[data-editor-workspace-column]')))
+ .toBeGreaterThanOrEqual(300);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(620);
+
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover.getByTestId('activity-panel')).toBeVisible();
+ await expect(page.locator('[data-slot="sidebar-inset"]')).toHaveAttribute('inert', '');
+ await cover.locator('[data-doc-panel-back]').click();
+ await expect(cover).not.toBeVisible();
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await expect(panel.getByTestId('activity-panel')).toBeVisible();
+});
+
+test('Outline destination reveals its heading from the information cover', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-outline-destination-${test.info().workerIndex}`;
+ await api.seedDocs([
+ {
+ name: docName,
+ markdown: `# First heading\n\n${'Long paragraph. '.repeat(180)}\n\n## Destination heading\n\nTarget body.\n\n## Following heading\n\nMore body.`,
+ },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ const scroller = page.locator('[data-testid="editor-scroll-container"]').first();
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ const mountedEditor = await editor.elementHandle();
+ if (!mountedEditor) throw new Error('active editor has no mounted element');
+ await expect(cover).toBeVisible();
+ await cover.getByRole('button', { name: 'Destination heading' }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror h2', { hasText: 'Destination heading' })).toBeVisible();
+ await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(50);
+ await expect(editor).toBeFocused();
+ expect(
+ await editor.evaluate(
+ (element, mounted) => element === mounted && mounted.isConnected,
+ mountedEditor,
+ ),
+ ).toBe(true);
+ await scroller.evaluate((element) => {
+ element.scrollTop = 0;
+ });
+ await page.locator('[data-doc-panel-toggle]').click();
+ await cover.getByRole('button', { name: 'Destination heading' }).click();
+ await expect(cover).not.toBeVisible();
+ await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(50);
+ await expect(page.locator('.ProseMirror h2', { hasText: 'Destination heading' })).toBeVisible();
+ await expect(editor).toBeFocused();
+ expect(
+ await editor.evaluate(
+ (element, mounted) => element === mounted && mounted.isConnected,
+ mountedEditor,
+ ),
+ ).toBe(true);
+});
+
+test('Links backlink reveals its document from the information cover', async ({ page, api }) => {
+ const source = `editor-card-backlink-source-${test.info().workerIndex}`;
+ const target = `editor-card-backlink-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: `# Source\n\n[[${target}]]` },
+ { name: target, markdown: '# Target\n\nBacklink destination.' },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${target}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ await cover.getByRole('link', { name: 'Source' }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${source}$`));
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Source' })).toBeVisible();
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Target' })).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+});
+
+for (const order of ['destination first', 'resize first'] as const) {
+ test(`a Links destination racing a narrowing resize settles on the destination (${order})`, async ({
+ page,
+ api,
+ }) => {
+ const source = `editor-card-race-source-${order.split(' ')[0]}-${test.info().workerIndex}`;
+ const target = `editor-card-race-target-${order.split(' ')[0]}-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: `# Race source\n\n[[${target}]]` },
+ { name: target, markdown: '# Race target\n\nRace destination.' },
+ ]);
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await page.goto(`/#/${target}`);
+ await waitForActiveProviderSynced(page);
+ const agentsButton = page.getByTestId(AGENTS_HEADER_BUTTON);
+ await agentsButton.click();
+ await expect(agentsButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ const backlink = cover.getByRole('link', { name: 'Race source' });
+ await expect(backlink).toBeVisible();
+ if (order === 'destination first') {
+ await backlink.click();
+ await page.setViewportSize({ width: 700, height: 700 });
+ } else {
+ await page.setViewportSize({ width: 700, height: 700 });
+ await page
+ .locator('[data-doc-panel-cover], #doc-panel')
+ .getByRole('link', { name: 'Race source' })
+ .click();
+ }
+ await expect(page).toHaveURL(new RegExp(`#/${source}$`));
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('[data-slot="pane-card"][data-pane="editor"]')).toBeVisible();
+ await expect(page.locator('[data-slot="pane-card"][data-pane="agents"]')).toBeHidden();
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Race source' })).toBeVisible();
+ if (order === 'destination first') {
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+ }
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ });
+}
+
+test('Links forward destination reveals its document from the information cover', async ({
+ page,
+ api,
+}) => {
+ const source = `editor-card-forward-source-${test.info().workerIndex}`;
+ const target = `editor-card-forward-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: `# Source\n\n[[${target}]]` },
+ { name: target, markdown: '# Forward destination\n\nTarget body.' },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ const sourceHeading = page.locator('.ProseMirror h1', { hasText: 'Source' });
+ const targetHeading = page.locator('.ProseMirror h1', { hasText: 'Forward destination' });
+ for (let visit = 0; visit < 2; visit += 1) {
+ await cover.getByRole('link', { name: 'Forward destination' }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(targetHeading).toBeVisible();
+ await expect(sourceHeading).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+ if (visit === 1) break;
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(cover.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await cover.getByRole('link', { name: 'Source' }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${source}$`));
+ await expect(sourceHeading).toBeVisible();
+ await expect(targetHeading).toBeHidden();
+ await page.locator('[data-doc-panel-toggle]').click();
+ }
+});
+
+test('Links successful page creation reveals its document from the information cover', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const source = `editor-card-create-source-${test.info().workerIndex}`;
+ const target = `editor-card-created-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: source, markdown: `# Source\n\n[[${target}]]` }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ await cover.getByRole('button', { name: /Missing page:.*Click to create/ }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(page.locator('[data-editor-activity-mount][data-doc-name]').first()).toHaveAttribute(
+ 'data-doc-name',
+ target,
+ );
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible();
+ await expect(page.locator('[data-slot="document-error-boundary"]')).toHaveCount(0);
+ expect(readdirSync(workerServer.contentDir).filter((name) => name.startsWith(target))).toEqual([
+ `${target}.md`,
+ ]);
+});
+
+test('Links page creation cannot be activated twice while its delayed request is pending', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const source = `editor-card-double-create-source-${test.info().workerIndex}`;
+ const target = `editor-card-double-created-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: source, markdown: `# Source\n\n[[${target}]]` }]);
+ let createRequests = 0;
+ let releaseCreate: () => void = () => {};
+ const createHeld = new Promise<void>((resolve) => {
+ releaseCreate = resolve;
+ });
+ await page.route('**/api/create-page', async (route) => {
+ createRequests += 1;
+ await createHeld;
+ await route.continue();
+ });
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ const create = cover.getByRole('button', { name: /Missing page:.*Click to create/ });
+ await create.click();
+ await expect.poll(() => createRequests).toBe(1);
+ expect((await create.isVisible()) && (await create.isEnabled())).toBe(false);
+ releaseCreate();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('[data-editor-activity-mount][data-doc-name]').first()).toHaveAttribute(
+ 'data-doc-name',
+ target,
+ );
+ await expect
+ .poll(() =>
+ readdirSync(workerServer.contentDir)
+ .filter((name) => name.startsWith(target))
+ .sort(),
+ )
+ .toEqual([`${target}.md`]);
+ expect(readdirSync(workerServer.contentDir).filter((name) => /^untitled/i.test(name))).toEqual(
+ [],
+ );
+ expect(createRequests).toBe(1);
+});
+
+test('compact Graph destination reveals its document from the information cover', async ({
+ page,
+ api,
+}) => {
+ const source = `editor-card-graph-source-${test.info().workerIndex}`;
+ const target = `editor-card-graph-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: `# Source\n\n[[${target}]]` },
+ { name: target, markdown: '# Graph destination\n\nTarget body.' },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Graph' }).click();
+ await page.waitForFunction(
+ (docName) =>
+ window.__graphHarness?.getNodeVisualState(docName) !== null &&
+ window.__graphHarness?.getNodeVisualState(docName) !== undefined,
+ target,
+ );
+ expect(await page.evaluate((docName) => window.__graphHarness?.clickDoc(docName), target)).toBe(
+ true,
+ );
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Graph destination' })).toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+});
+
+test('Links local reference reveals its source location from the information cover', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-local-reference-${test.info().workerIndex}`;
+ await api.seedDocs([
+ {
+ name: docName,
+ markdown: `# Local reference\n\n${'Long paragraph. '.repeat(180)}\n\n[Attachment](missing.pdf)`,
+ },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ await cover.getByRole('button', { name: /Missing file.*Go to reference/ }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+ await expect(
+ page.locator('.ProseMirror').getByText('Attachment', { exact: true }),
+ ).toBeInViewport();
+ await expect(
+ page.locator('.ProseMirror h1', { hasText: 'Local reference' }),
+ ).not.toBeInViewport();
+});
+
+test('expanded Graph inspection stays in its cover until Open reveals a document', async ({
+ page,
+ api,
+}) => {
+ const source = `editor-card-expanded-graph-source-${test.info().workerIndex}`;
+ const target = `editor-card-expanded-graph-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: `# Source\n\n[[${target}]]` },
+ { name: target, markdown: '# Expanded destination\n\nTarget body.' },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Graph' }).click();
+ await cover.getByRole('button', { name: 'Expand graph' }).click();
+ await page.waitForFunction(
+ (docName) => window.__graphHarness?.getNodeVisualState(docName) != null,
+ target,
+ );
+ await page.getByRole('radio', { name: 'Hubs' }).click();
+ await expect(page.getByRole('radio', { name: 'Hubs' })).toBeChecked();
+ await expect(cover).toBeVisible();
+ await page.getByRole('radio', { name: 'Explore' }).click();
+ await expect(cover).toBeVisible();
+ await page.waitForFunction(
+ (docName) => window.__graphHarness?.getNodeVisualState(docName) != null,
+ target,
+ );
+ expect(await page.evaluate((docName) => window.__graphHarness?.clickDoc(docName), target)).toBe(
+ true,
+ );
+ await expect(cover).toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${source}$`));
+ const selected = page.getByRole('status', { name: 'Selected graph item' });
+ await selected.getByRole('button', { name: 'Open', exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Expanded destination' })).toBeVisible();
+});
+
+test('expanded Graph Create reveals a missing document from the information cover', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const source = `editor-card-graph-create-source-${test.info().workerIndex}`;
+ const target = `editor-card-graph-create-target-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: source, markdown: `# Source\n\n[[${target}]]` }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Graph' }).click();
+ await cover.getByRole('button', { name: 'Expand graph' }).click();
+ await page.waitForFunction(
+ (docName) => window.__graphHarness?.getNodeVisualState(docName) != null,
+ target,
+ );
+ expect(await page.evaluate((docName) => window.__graphHarness?.clickDoc(docName), target)).toBe(
+ true,
+ );
+ await expect(cover).toBeVisible();
+ const selected = page.getByRole('status', { name: 'Selected graph item' });
+ await selected.getByRole('button', { name: 'Create page' }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(page.locator('[data-slot="document-error-boundary"]')).toHaveCount(0);
+ await expect(page.locator('[data-editor-activity-mount][data-doc-name]').first()).toHaveAttribute(
+ 'data-doc-name',
+ target,
+ );
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editor).toBeVisible();
+ await editor.click();
+ await page.keyboard.type('Created from the graph');
+ await expect
+ .poll(() => readdirSync(workerServer.contentDir).filter((name) => name.startsWith(target)))
+ .toEqual([`${target}.md`]);
+ await expect
+ .poll(() => readFileSync(join(workerServer.contentDir, `${target}.md`), 'utf-8'))
+ .toContain('Created from the graph');
+});
+
+test('failed expanded Graph destination keeps its inspection in the information cover', async ({
+ page,
+ context,
+ api,
+}) => {
+ const source = `editor-card-graph-failed-source-${test.info().workerIndex}`;
+ const target = `editor-card-graph-failed-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: `# Source\n\n[[${target}]]` },
+ { name: target, markdown: '# Unavailable destination\n' },
+ ]);
+ let disconnectDestination = false;
+ await context.routeWebSocket(/collab/, (socket) => {
+ if (disconnectDestination) {
+ socket.close();
+ return;
+ }
+ socket.connectToServer();
+ });
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Graph' }).click();
+ await cover.getByRole('button', { name: 'Expand graph' }).click();
+ await page.waitForFunction(
+ (docName) => window.__graphHarness?.getNodeVisualState(docName) != null,
+ target,
+ );
+ expect(await page.evaluate((docName) => window.__graphHarness?.clickDoc(docName), target)).toBe(
+ true,
+ );
+ disconnectDestination = true;
+ const selected = page.getByRole('status', { name: 'Selected graph item' });
+ await selected.getByRole('button', { name: 'Open', exact: true }).click();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('button', { name: 'Back to editor', exact: true })).toBeVisible();
+ await expect(selected).toBeVisible();
+ await expect(selected).toContainText('Selected in graph');
+ await expect(selected).not.toContainText('Already open');
+ await expect(
+ page.locator('[data-sonner-toast]').filter({ hasText: 'Connection lost' }),
+ ).toBeVisible({ timeout: 15_000 });
+ expect(
+ await page.evaluate(() => {
+ const active = document.activeElement;
+ return active !== null && active !== document.body && active.closest('[inert]') === null;
+ }),
+ ).toBe(true);
+});
+
+test('failed Links page creation keeps the information cover usable', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `editor-card-failed-link-create-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Source\n\n[[missing-target]]' }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ await page.route('**/api/create-page', (route) =>
+ route.fulfill({
+ status: 507,
+ contentType: 'application/problem+json',
+ json: { title: 'Not enough storage to create the page' },
+ }),
+ );
+ const create = cover.getByRole('button', { name: /Missing page:.*Click to create/ });
+ await create.click();
+ await expect(
+ page
+ .locator('[data-sonner-toast]')
+ .filter({ hasText: 'Not enough storage to create the page' }),
+ ).toBeVisible();
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('button', { name: 'Back to editor', exact: true })).toBeVisible();
+ await expect(cover.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await expect(page).toHaveURL(new RegExp(`#/${docName}$`));
+ expect(existsSync(join(workerServer.contentDir, 'missing-target.md'))).toBe(false);
+ await expect(create).toBeEnabled();
+ await page.unroute('**/api/create-page');
+ await create.click();
+ await expect(cover).not.toBeVisible();
+ await expect(page).toHaveURL(/#\/missing-target$/);
+ await expect
+ .poll(() => existsSync(join(workerServer.contentDir, 'missing-target.md')))
+ .toBe(true);
+});
+
+test('Problems location reveals the editor from the information cover', async ({ page, api }) => {
+ const docName = `editor-card-problem-location-${test.info().workerIndex}`;
+ await api.seedDocs([
+ {
+ name: docName,
+ markdown: `# Problem location\n\n${'Context paragraph. '.repeat(180)}\n\n[Attachment](missing.pdf)`,
+ },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Problems' }).click();
+ const location = cover.getByRole('list', { name: 'Problems' }).getByRole('button').first();
+ await expect(location).toBeVisible();
+ await location.click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+ await expect(
+ page.locator('.ProseMirror').getByText('Attachment', { exact: true }),
+ ).toBeInViewport();
+});
+
+test('Comments quote reveals its passage while comment editing stays in the cover', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-comment-quote-${test.info().workerIndex}`;
+ const passage = 'the hidden passage near the end';
+ await api.seedDocs([
+ {
+ name: docName,
+ markdown: `# Comment destination\n\n${'Context paragraph. '.repeat(180)}\n\nFind ${passage} here.`,
+ },
+ ]);
+ const created = await page.request.post('/api/comments', {
+ data: { docName, quote: passage, body: 'Keep this comment visible while editing.' },
+ });
+ expect(created.ok()).toBe(true);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Comments' }).click();
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText(
+ 'Keep this comment visible while editing.',
+ );
+ await cover.getByTestId('thread-comment-body').hover();
+ const editComment = cover.getByRole('button', { name: 'Edit this comment' });
+ await editComment.click({ timeout: 5000 });
+ const editField = cover.getByRole('textbox', { name: 'Edit this comment' });
+ await expect(editField).toBeVisible();
+ await expect(editField).toBeFocused();
+ await editField.fill('An unsaved change stays with this comment.');
+ await expect(editField).toHaveText('An unsaved change stays with this comment.');
+ await expect(cover).toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${docName}$`));
+ await cover.getByRole('button', { name: 'Cancel' }).click();
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText(
+ 'Keep this comment visible while editing.',
+ );
+ await cover.getByRole('button', { name: 'Edit this comment' }).focus();
+ await page.keyboard.press('Enter');
+ await expect(cover.getByRole('textbox', { name: 'Edit this comment' })).toBeVisible();
+ await expect(cover).toBeVisible();
+ await cover.getByRole('textbox', { name: 'Edit this comment' }).fill('Saved from the cover.');
+ await cover.getByRole('button', { name: 'Save' }).click();
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText('Saved from the cover.');
+ await expect(cover).toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${docName}$`));
+ await cover.getByRole('button', { name: `“${passage}”` }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+ await expect(page.locator('.ProseMirror p', { hasText: passage })).toBeInViewport();
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(cover.getByRole('tab', { name: 'Comments' })).toHaveAttribute('data-state', 'on');
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText('Saved from the cover.');
+});
+
+test.describe('Comments cover on a touch pointer', () => {
+ test.use({ hasTouch: true, viewport: { width: 390, height: 700 } });
+
+ test('comment editing opens by touch and stays in the information cover', async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-card-comment-touch-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Touch comment\n\nA passage to annotate.' }]);
+ const created = await page.request.post('/api/comments', {
+ data: { docName, quote: 'A passage to annotate.', body: 'Keep this draft in the cover.' },
+ });
+ expect(created.ok()).toBe(true);
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').tap();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Comments' }).tap();
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText(
+ 'Keep this draft in the cover.',
+ );
+ expect(await page.evaluate(() => window.matchMedia('(hover: none)').matches)).toBe(true);
+ const edit = cover.getByRole('button', { name: 'Edit this comment' });
+ const reachable = async () =>
+ edit.evaluate((button) => {
+ const rect = button.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
+ return hit !== null && button.contains(hit);
+ });
+ expect(await reachable()).toBe(true);
+ await edit.tap({ timeout: 5000 });
+ const field = cover.getByRole('textbox', { name: 'Edit this comment' });
+ await expect(field).toBeVisible();
+ await expect(field).toBeFocused();
+ await expect(cover).toBeVisible();
+ await cover.getByRole('button', { name: 'Cancel' }).tap();
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText(
+ 'Keep this draft in the cover.',
+ );
+ expect(await reachable()).toBe(true);
+ await edit.tap();
+ await field.fill('Saved by touch.');
+ await cover.getByRole('button', { name: 'Save' }).tap();
+ await expect(cover.getByTestId('thread-comment-body')).toHaveText('Saved by touch.');
+ await expect(cover).toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`#/${docName}$`));
+ });
+});
+
+test('project Comments quote reveals its other document from the information cover', async ({
+ page,
+ api,
+}) => {
+ const source = `editor-card-comment-source-${test.info().workerIndex}`;
+ const target = `editor-card-comment-target-${test.info().workerIndex}`;
+ const passage = 'other document passage';
+ await api.seedDocs([
+ { name: source, markdown: '# Source\n\nOpen the project comments.' },
+ { name: target, markdown: `# Target\n\nFind the ${passage} here.` },
+ ]);
+ const created = await page.request.post('/api/comments', {
+ data: { docName: target, quote: passage, body: 'Navigate to this other document.' },
+ });
+ expect(created.ok()).toBe(true);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Comments' }).click();
+ await cover.getByTestId('panel-scope-project').click();
+ await cover.getByRole('button', { name: `“${passage}”` }).click();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Target' })).toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+});
+
+test('failed Comments passage keeps the information cover and error context', async ({
+ page,
+ context,
+ api,
+}) => {
+ const source = `editor-card-comment-failed-source-${test.info().workerIndex}`;
+ const target = `editor-card-comment-failed-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: '# Source\n\nOpen the project comments.' },
+ { name: target, markdown: '# Target\n\na passage that is no longer here' },
+ ]);
+ const created = await page.request.post('/api/comments', {
+ data: {
+ docName: target,
+ quote: 'a passage that is no longer here',
+ body: 'Find the old quote.',
+ },
+ });
+ expect(created.ok()).toBe(true);
+ let disconnectDestination = false;
+ await context.routeWebSocket(/collab/, (socket) => {
+ if (disconnectDestination) {
+ socket.close();
+ return;
+ }
+ socket.connectToServer();
+ });
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Comments' }).click();
+ await cover.getByTestId('panel-scope-project').click();
+ disconnectDestination = true;
+ await cover.getByRole('button', { name: '“a passage that is no longer here”' }).click();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await expect(cover).toBeVisible();
+ await expect(
+ page.locator('[data-sonner-toast]').filter({ hasText: "That document didn't open in time" }),
+ ).toBeVisible({ timeout: 15_000 });
+ await expect(cover.getByText('Find the old quote.')).toBeVisible();
+ expect(
+ await page.evaluate(() => {
+ const active = document.activeElement;
+ return active !== null && active !== document.body && active.closest('[inert]') === null;
+ }),
+ ).toBe(true);
+});
+
+test('Problems Fix keeps information work in the cover', async ({ page, api, workerServer }) => {
+ const docName = `editor-card-problem-fix-${test.info().workerIndex}`;
+ const configPath = join(workerServer.contentDir, '.ok', 'config.yml');
+ const originalConfig = existsSync(configPath) ? readFileSync(configPath) : null;
+ mkdirSync(join(workerServer.contentDir, '.ok'), { recursive: true });
+ writeFileSync(configPath, 'contentRules:\n markdownlint:\n enabled: true\n', 'utf-8');
+ try {
+ await api.seedDocs([
+ { name: docName, markdown: '# Problem fix\n\nParagraph with trailing spaces. \n' },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Problems' }).click();
+ await expect(cover.getByText('MD009')).toBeVisible();
+ await cover.getByTestId('problems-fix').first().click();
+ await expect(cover.getByText('MD009')).toHaveCount(0);
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('tab', { name: 'Problems' })).toHaveAttribute('data-state', 'on');
+ await expect(page).toHaveURL(new RegExp(`#/${docName}$`));
+ } finally {
+ if (originalConfig) writeFileSync(configPath, originalConfig);
+ else unlinkSync(configPath);
+ }
+});
+
+test('project Problems location reveals another document from the information cover', async ({
+ page,
+ api,
+}) => {
+ const source = `editor-card-project-problem-source-${test.info().workerIndex}`;
+ const target = `editor-card-project-problem-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: '# Source\n\nOpen project problems.' },
+ {
+ name: target,
+ markdown: `# Target\n\n${'Context paragraph. '.repeat(180)}\n\n[Attachment](missing.pdf)`,
+ },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Problems' }).click();
+ await cover.getByTestId('panel-scope-project').click();
+ const group = cover.getByTestId('problems-audit-group').filter({ hasText: target });
+ await expect(group).toBeVisible();
+ await group.getByRole('button').first().click();
+ await group.getByRole('list').getByRole('button').first().click();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await waitForActiveProviderSynced(page);
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror h1', { hasText: 'Target' })).toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeFocused();
+ await expect
+ .poll(() =>
+ page
+ .locator('[data-testid="editor-scroll-container"]')
+ .first()
+ .evaluate((el) => el.scrollTop),
+ )
+ .toBeGreaterThan(50);
+});
+
+test('Comments property anchor reveals its value from the information cover', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-comment-property-${test.info().workerIndex}`;
+ const quote = 'Initial';
+ await api.seedDocs([
+ { name: docName, markdown: '---\ntitle: Initial\n---\n\n# Body\n\nProperty comment.' },
+ ]);
+ const created = await page.request.post('/api/comments', {
+ data: { docName, propertyKey: 'title', quote, body: 'Check the title property.' },
+ });
+ expect(created.ok()).toBe(true);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Comments' }).click();
+ const property = page.locator('[data-testid="property-row"][data-key="title"] textarea');
+ await expect(property).toHaveValue(quote);
+ await cover.getByRole('button', { name: `title: “${quote}”` }).click();
+ await expect(property).toHaveAttribute('data-comment-reveal', 'true');
+ await expect(cover).not.toBeVisible();
+ await expect(property).toBeFocused();
+ await expect(property).toHaveJSProperty('selectionStart', 0);
+ await expect(property).toHaveJSProperty('selectionEnd', quote.length);
+});
+
+test('project Comments property anchor reveals its other document', async ({ page, api }) => {
+ const source = `editor-card-property-source-${test.info().workerIndex}`;
+ const target = `editor-card-property-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: '# Source\n\nOpen project comments.' },
+ { name: target, markdown: '---\ntitle: Initial\n---\n\n# Target\n\nProperty comment.' },
+ ]);
+ const created = await page.request.post('/api/comments', {
+ data: { docName: target, propertyKey: 'title', quote: 'Initial', body: 'Open this property.' },
+ });
+ expect(created.ok()).toBe(true);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Comments' }).click();
+ await cover.getByTestId('panel-scope-project').click();
+ await cover.getByRole('button', { name: 'title: “Initial”' }).click();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await waitForActiveProviderSynced(page);
+ const property = page.locator('[data-testid="property-row"][data-key="title"] textarea');
+ await expect(property).toHaveAttribute('data-comment-reveal', 'true');
+ await expect(cover).not.toBeVisible();
+ await expect(property).toBeFocused();
+});
+
+test('agent Activity opens the whole information panel as a cover', async ({ page, api }) => {
+ const docName = `editor-card-info-activity-${test.info().workerIndex}`;
+ const agentId = `responsive-activity-${crypto.randomUUID().slice(0, 8)}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, `${DOC_MARKDOWN}\n\nAgent update`, {
+ agentId,
+ agentName: 'Responsive Activity',
+ clientName: 'claude-code',
+ });
+
+ const avatar = page
+ .locator(
+ '[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="Responsive Activity"]',
+ )
+ .first();
+ await expect(avatar).toBeVisible();
+ await avatar.click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await expect(page.locator('[data-testid="activity-panel"]')).toBeVisible();
+ await expect(
+ page
+ .locator('[data-doc-panel-cover] [data-testid="activity-panel-file-row"]')
+ .filter({ hasText: docName }),
+ ).toBeVisible();
+ await expect(page.locator('[data-doc-panel-back]')).toBeFocused();
+ await page.locator('[data-doc-panel-back]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).not.toBeVisible();
+ await expect(page.locator('[data-editor-activity-mount][data-doc-name]').first()).toHaveAttribute(
+ 'data-doc-name',
+ docName,
+ );
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Agent update',
+ );
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(page.locator('[data-testid="activity-panel"]')).toBeVisible();
+ await avatar.click();
+ await expect(page.locator('[data-testid="activity-panel"]')).toBeHidden();
+ await page.setViewportSize({ width: 430, height: 700 });
+ await avatar.click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await expect(page.locator('[data-testid="activity-panel"]')).toBeVisible();
+ await page.locator('[data-doc-panel-back]').click();
+ await avatar.click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await expect(page.locator('[data-testid="activity-panel"]')).toBeVisible();
+});
+
+test('Timeline version selection reveals its diff from the information cover', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-timeline-diff-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Timeline before\n\nInitial body.' }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, '# Timeline after\n\nChanged body.', {
+ agentId: `timeline-cover-${crypto.randomUUID().slice(0, 8)}`,
+ agentName: 'Timeline Cover',
+ clientName: 'claude-code',
+ });
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Timeline' }).click();
+ const entry = cover.getByTestId('timeline-entry-open').first();
+ await expect(entry).toBeVisible();
+ const before = page.url();
+ await entry.click();
+ await expect(page.getByTestId('timeline-diff-pane')).toBeVisible();
+ await expect(page.getByTestId('timeline-diff-pane')).toContainText('Changed body.');
+ await expect(cover).not.toBeVisible();
+ await expect(page.getByTestId('timeline-diff-close')).toBeFocused();
+ expect(page.url()).toBe(before);
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(cover).toBeVisible();
+ await cover.getByTestId('timeline-entry-open').first().click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.getByTestId('timeline-diff-pane')).toContainText('Changed body.');
+ await page.getByTestId('timeline-diff-close').click();
+ await expect(page.getByTestId('timeline-diff-pane')).toHaveCount(0);
+ expect(page.url()).toBe(before);
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(cover.getByRole('tab', { name: 'Timeline' })).toHaveAttribute('data-state', 'on');
+ await expect(cover.getByTestId('timeline-entry-open').first()).toBeVisible();
+});
+
+test('failed Timeline diff loading keeps the information cover and its selected version available', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-timeline-diff-failure-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Timeline before\n\nInitial body.' }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, '# Timeline after\n\nChanged body.', {
+ agentId: `timeline-diff-failure-${crypto.randomUUID().slice(0, 8)}`,
+ agentName: 'Timeline Diff Failure',
+ clientName: 'claude-code',
+ });
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Timeline' }).click();
+ const entry = cover.getByTestId('timeline-entry-open').first();
+ await expect(entry).toBeVisible();
+ const before = page.url();
+ let failedFetchObserved = false;
+ await page.route(/\/api\/history\/[^?]+\?docName=/, (route) => {
+ failedFetchObserved = true;
+ return route.fulfill({ status: 503 });
+ });
+
+ await entry.click();
+ await expect.poll(() => failedFetchObserved).toBe(true);
+ await expect(
+ page.locator('[data-sonner-toast]').filter({ hasText: 'Diff unavailable' }),
+ ).toBeVisible();
+ await expect(cover).toBeVisible();
+ await expect(entry).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByTestId('header-pane-button-editor')).toBeVisible();
+ expect(page.url()).toBe(before);
+ await expect(page.locator('[data-editor-activity-mount][data-doc-name]').first()).toHaveAttribute(
+ 'data-doc-name',
+ docName,
+ );
+ await page.unroute(/\/api\/history\/[^?]+\?docName=/);
+ await cover.getByRole('button', { name: 'Back to editor', exact: true }).click();
+ await page.getByTestId('timeline-diff-close').click();
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(cover.getByRole('tab', { name: 'Timeline' })).toHaveAttribute('data-state', 'on');
+ await cover.getByTestId('timeline-entry-open').first().click();
+ await expect(page.getByTestId('timeline-diff-pane')).toContainText('Changed body.');
+ expect(page.url()).toBe(before);
+});
+
+test('Timeline Restore confirmation and failure keep the information cover available', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `editor-card-timeline-restore-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Before restore\n\nOriginal body.' }]);
+ await saveInMemoryCheckpoint(
+ { gitDir: resolveShadowDir(workerServer.contentDir), workTree: workerServer.contentDir },
+ '',
+ {
+ kind: 'bridge-merge-loss',
+ docName,
+ contents: '# Before restore\n\nOriginal body.',
+ branch: 'main',
+ label: 'Before later edit',
+ metadata: { lostSubstrings: ['Original body.'] },
+ },
+ );
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, '# After restore\n\nCurrent body.', {
+ agentId: `timeline-restore-${crypto.randomUUID().slice(0, 8)}`,
+ agentName: 'Timeline Restore',
+ clientName: 'claude-code',
+ });
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByRole('tab', { name: 'Timeline' }).click();
+ const older = cover.getByTestId('timeline-entry-open').last();
+ await expect(older).toBeVisible();
+ await older.getByTestId('timeline-entry-restore').click();
+ await expect(page.getByTestId('timeline-entry-restore-confirm')).toBeVisible();
+ await page.getByTestId('timeline-entry-restore-cancel').click();
+ await expect(cover).toBeVisible();
+ await expect(page.getByText('Current body.')).toBeVisible();
+ const docPath = join(workerServer.contentDir, `${docName}.md`);
+ await expect.poll(() => readFileSync(docPath, 'utf-8')).toContain('Current body.');
+ expect(readFileSync(docPath, 'utf-8')).not.toContain('Original body.');
+ await page.route('**/api/rollback', (route) => route.fulfill({ status: 503 }));
+ await older.getByTestId('timeline-entry-restore').click();
+ await page.getByTestId('timeline-entry-restore-confirm').click();
+ await expect(page.getByText('Restore failed', { exact: true })).toBeVisible();
+ await expect(cover).toBeVisible();
+ await expect(page.getByText('Current body.')).toBeVisible();
+ expect(readFileSync(docPath, 'utf-8')).not.toContain('Original body.');
+ await page.unroute('**/api/rollback');
+ await page.getByTestId('timeline-entry-restore-confirm').click();
+ await expect(page.getByText('Original body.')).toBeVisible();
+ await expect(cover).toBeVisible();
+ await expect.poll(() => readFileSync(docPath, 'utf-8')).toContain('Original body.');
+ expect(readFileSync(docPath, 'utf-8')).not.toContain('Current body.');
+ await cover.getByRole('button', { name: 'Back to editor', exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Original body.',
+ );
+});
+
+test('Activity version selection reveals its diff from the information cover', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-activity-diff-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Activity before\n\nInitial body.' }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, '# Activity after\n\nChanged body.', {
+ agentId: `activity-cover-${crypto.randomUUID().slice(0, 8)}`,
+ agentName: 'Activity Cover',
+ clientName: 'claude-code',
+ });
+ const avatar = page
+ .locator(
+ '[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="Activity Cover"]',
+ )
+ .first();
+ await expect(avatar).toBeVisible();
+ await avatar.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ const version = cover.getByTestId('activity-panel-burst-open').first();
+ await expect(version).toBeVisible();
+ const before = page.url();
+ await version.click();
+ await expect(page.getByTestId('agent-diff-pane')).toBeVisible();
+ await expect(page.getByTestId('agent-diff-pane')).toContainText('Changed body.');
+ await expect(cover).not.toBeVisible();
+ await expect(page.getByTestId('agent-diff-close')).toBeFocused();
+ expect(page.url()).toBe(before);
+ await page.getByTestId('agent-diff-close').click();
+ await expect(page.getByTestId('agent-diff-pane')).toHaveCount(0);
+ expect(page.url()).toBe(before);
+ await avatar.click();
+ await expect(cover.getByTestId('activity-panel')).toBeVisible();
+ await expect(cover.getByTestId('activity-panel-burst-open').first()).toBeVisible();
+});
+
+test('failed Activity diff loading keeps the information cover and burst available', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-activity-diff-failure-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Activity before\n\nInitial body.' }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, '# Activity after\n\nChanged body.', {
+ agentId: `activity-diff-failure-${crypto.randomUUID().slice(0, 8)}`,
+ agentName: 'Activity Diff Failure',
+ clientName: 'claude-code',
+ });
+ const avatar = page
+ .locator(
+ '[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="Activity Diff Failure"]',
+ )
+ .first();
+ await expect(avatar).toBeVisible();
+ await avatar.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ const burst = cover.getByTestId('activity-panel-burst-open').first();
+ await expect(burst).toBeVisible();
+ const before = page.url();
+ let failedFetchObserved = false;
+ await page.route(/\/api\/agent-burst-diff\?/, (route) => {
+ failedFetchObserved = true;
+ return route.fulfill({
+ status: 503,
+ contentType: 'application/problem+json',
+ body: JSON.stringify({
+ type: 'urn:ok:error:internal-server-error',
+ title: 'Activity diff unavailable',
+ status: 503,
+ }),
+ });
+ });
+
+ await burst.click();
+ await expect.poll(() => failedFetchObserved).toBe(true);
+ await expect(
+ page.locator('[data-sonner-toast]').filter({ hasText: 'Diff unavailable' }),
+ ).toBeVisible();
+ await expect(cover).toBeVisible();
+ await expect(burst).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByTestId('header-pane-button-editor')).toBeVisible();
+ expect(page.url()).toBe(before);
+ await page.unroute(/\/api\/agent-burst-diff\?/);
+ await cover.getByRole('button', { name: 'Back to editor', exact: true }).click();
+ await page.getByTestId('agent-diff-close').click();
+ await avatar.click();
+ await cover.getByTestId('activity-panel-burst-open').first().click();
+ await expect(page.getByTestId('agent-diff-pane')).toContainText('Changed body.');
+ expect(page.url()).toBe(before);
+});
+
+test('Activity Undo retains the cover during inspection and restores the selected edit', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `editor-card-activity-undo-${test.info().workerIndex}`;
+ const agentId = `activity-undo-${crypto.randomUUID().slice(0, 8)}`;
+ await api.seedDocs([{ name: docName, markdown: '# Before activity\n\nOriginal body.' }]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(docName, '# First edit\n\nFirst body.', {
+ agentId,
+ agentName: 'Activity Undo',
+ clientName: 'claude-code',
+ });
+ await wait(600);
+ await api.writeAsAgent(docName, '# Second edit\n\nSecond body.', {
+ agentId,
+ agentName: 'Activity Undo',
+ clientName: 'claude-code',
+ });
+ const avatar = page
+ .locator(
+ '[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="Activity Undo"]',
+ )
+ .first();
+ await expect(avatar).toBeVisible();
+ await avatar.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ const activity = cover.getByTestId('activity-panel');
+ const file = activity.getByTestId('activity-panel-file-row').filter({ hasText: docName });
+ const bursts = file.getByTestId('activity-panel-burst-open');
+ await expect(bursts).toHaveCount(2);
+ await expect(cover).toBeVisible();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(bursts.first()).toBeVisible();
+ await expect(bursts.last()).toBeVisible();
+
+ await file.getByTestId('activity-panel-burst-restore').last().click();
+ await expect(page.getByTestId('activity-panel-burst-restore-confirm')).toBeVisible();
+ await page.getByTestId('activity-panel-burst-restore-cancel').click();
+ await expect(cover).toBeVisible();
+ await expect(bursts).toHaveCount(2);
+
+ const undoResponse = page.waitForResponse(
+ (response) =>
+ response.url().endsWith('/api/agent-undo') && response.request().method() === 'POST',
+ );
+ await file.getByTestId('activity-panel-burst-restore').last().click();
+ await page.getByTestId('activity-panel-burst-restore-confirm').click();
+ expect((await undoResponse).ok()).toBe(true);
+ await expect(cover).toBeVisible();
+ await expect(bursts).toHaveCount(1);
+ const docPath = join(workerServer.contentDir, `${docName}.md`);
+ await expect
+ .poll(() => readFileSync(docPath, 'utf-8').trim())
+ .toBe('# First edit\n\nFirst body.');
+ await cover.getByRole('button', { name: 'Back to editor', exact: true }).click();
+ await expect(page.getByText('First body.', { exact: true })).toBeVisible();
+});
+
+test('Activity file selection reveals its other document from the information cover', async ({
+ page,
+ api,
+}) => {
+ const source = `editor-card-activity-source-${test.info().workerIndex}`;
+ const target = `editor-card-activity-target-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: '# Current document' },
+ { name: target, markdown: '# Activity destination' },
+ ]);
+ await page.setViewportSize({ width: 430, height: 700 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await api.writeAsAgent(target, '# Activity destination\n\nChanged elsewhere.', {
+ agentId: `activity-file-${crypto.randomUUID().slice(0, 8)}`,
+ agentName: 'Activity File',
+ clientName: 'claude-code',
+ });
+ const avatar = page
+ .locator(
+ '[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="Activity File"]',
+ )
+ .first();
+ await expect(avatar).toBeVisible();
+ await avatar.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await cover.getByTestId('activity-panel-file-row-filename').filter({ hasText: target }).click();
+ await expect(page).toHaveURL(new RegExp(`#/${target}$`));
+ await waitForActiveProviderSynced(page);
+ await expect(cover).not.toBeVisible();
+ await expect(
+ page.locator('.ProseMirror[contenteditable="true"]:not(.composer-prosemirror)'),
+ ).toBeFocused();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Changed elsewhere.',
+ );
+ await avatar.click();
+ await expect(cover.getByTestId('activity-panel')).toBeVisible();
+ await expect(
+ cover.getByTestId('activity-panel-file-row-filename').filter({ hasText: target }),
+ ).toBeVisible();
+});
+
+for (const rememberedWidth of [300, 600]) {
+ test(`information cover retains a ${rememberedWidth}px remembered dock width`, async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-card-info-remembered-${rememberedWidth}-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.addInitScript((width) => {
+ localStorage.setItem('ok-doc-panel-width-v1', String(width));
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({ right: { above: 'open', below: 'open', embedded: 'open' } }),
+ );
+ }, rememberedWidth);
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const panel = page.locator('#doc-panel');
+ await expect(panel).toBeVisible();
+ expect(Math.abs((await widthOf(panel)) - rememberedWidth)).toBeLessThanOrEqual(1);
+
+ await page.setViewportSize({ width: 500, height: 700 });
+ await expect(panel).not.toBeVisible();
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await page.locator('[data-doc-panel-back]').click();
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(panel).toBeVisible();
+ expect(Math.abs((await widthOf(panel)) - rememberedWidth)).toBeLessThanOrEqual(1);
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe(
+ String(rememberedWidth),
+ );
+ });
+}
+
+test('information intent survives viewport partition changes without a new toggle', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-info-partition-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width: 1400, height: 700 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const panel = page.locator('#doc-panel');
+ await expect(panel).toBeVisible();
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(panel).toBeVisible();
+ await page.setViewportSize({ width: 500, height: 700 });
+ await expect(panel).not.toBeVisible();
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await expect(panel).toBeVisible();
+});
+
+test('closed wide information reopens as a cover after editor and window resizing without clipping', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const resizeErrors: string[] = [];
+ page.on('pageerror', (error) => {
+ if (error.message.includes('ResizeObserver loop')) resizeErrors.push(error.message);
+ });
+ page.on('console', (message) => {
+ if (message.text().includes('rail-layout-retry-exhausted')) resizeErrors.push(message.text());
+ });
+ const docName = `outline-reopen-${test.info().workerIndex}`;
+ await api.seedDocs([
+ {
+ name: docName,
+ markdown: `---\ntitle: Albus Dumbledore\n---\n\n# Summary\n\n${('Grindelwald in **1945**, and in doing so became master of the **Elder Wand**. ').repeat(12)}\n\n## Headmaster and public offices\n\nBeyond Hogwarts, Dumbledore held office in wizarding government.`,
+ },
+ ]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '320');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.setViewportSize({ width: 2000, height: 900 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editor).toBeVisible();
+ const info = page.locator('#doc-panel');
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ const infoDivider = page.locator('[data-doc-panel-handle]');
+ await infoDivider.hover();
+ const ib = await infoDivider.boundingBox();
+ if (!ib) throw new Error('information divider has no bounds');
+ await page.mouse.down();
+ await page.mouse.move(ib.x - 600, ib.y + ib.height / 2, { steps: 8 });
+ await page.mouse.up();
+ await expect
+ .poll(() => info.evaluate((e) => e.getBoundingClientRect().width))
+ .toBeGreaterThanOrEqual(599);
+ await page.getByTestId('header-pane-button-agents').click();
+ await expect(page.locator('[data-agents-panel-mount]')).toBeVisible();
+ await expect(info).toBeVisible();
+ 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();
+ 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 page.screenshot({ path: test.info().outputPath(`closed-${target}.png`) });
+ await expect(toggle).toBeVisible();
+ await toggle.click();
+ await page.screenshot({ path: test.info().outputPath(`reopened-${target}.png`) });
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ const coverBox = await cover.boundingBox();
+ const cardBox = await card.boundingBox();
+ if (!coverBox || !cardBox) throw new Error('the editor cover has no bounds');
+ expect(Math.abs(coverBox.width - cardBox.width)).toBeLessThanOrEqual(1);
+ expect(Math.abs(coverBox.x - cardBox.x)).toBeLessThanOrEqual(1);
+ await page.locator('[data-doc-panel-back]').click();
+ await expect
+ .poll(() =>
+ page.locator('[data-editor-workspace]').evaluate((e) => e.scrollWidth - e.clientWidth),
+ )
+ .toBeLessThanOrEqual(1);
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe('600');
+ }
+ await dragChatDivider(page, 0, 1400 - (await widthOf(card)), async () => {});
+ await expect(info).toBeVisible();
+ await expect.poll(() => widthOf(info)).toBeGreaterThanOrEqual(599);
+ await expect(page.locator('[data-sidebar="sidebar"]')).toBeVisible();
+ await toggle.click();
+ await expect(info).toBeHidden();
+ for (const width of [1400, 1200, 900]) {
+ await page.setViewportSize({ width, height: 900 });
+ await settleFrames(page);
+ await expect(toggle).toBeVisible();
+ await toggle.click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ const bounds = await cover.boundingBox();
+ const cardBounds = await card.boundingBox();
+ if (!bounds || !cardBounds) throw new Error('the editor cover has no bounds');
+ expect(Math.abs(bounds.width - cardBounds.width)).toBeLessThanOrEqual(1);
+ expect(Math.abs(bounds.x - cardBounds.x)).toBeLessThanOrEqual(1);
+ await page.locator('[data-doc-panel-back]').click();
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe('600');
+ await expect
+ .poll(() =>
+ page.locator('[data-editor-workspace]').evaluate((e) => e.scrollWidth - e.clientWidth),
+ )
+ .toBeLessThanOrEqual(1);
+ }
+ await page.setViewportSize({ width: 2000, height: 900 });
+ await expect(info).toBeVisible();
+ await settleFrames(page);
+ await expect.poll(() => widthOf(info)).toBeGreaterThanOrEqual(599);
+ await toggle.click();
+ await expect(info).toBeHidden();
+ await page.setViewportSize({ width: 1800, height: 900 });
+ await page.setViewportSize({ width: 2000, height: 900 });
+ await expect(info).toBeHidden();
+ expect(resizeErrors).toEqual([]);
+});
+
+test('information yields after resizing the editor beside Chat below its docking budget', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const resizeErrors: string[] = [];
+ page.on('pageerror', (error) => {
+ if (error.message.includes('ResizeObserver loop')) resizeErrors.push(error.message);
+ });
+ page.on('console', (message) => {
+ if (message.text().includes('rail-layout-retry-exhausted')) resizeErrors.push(message.text());
+ });
+ const docName = `outline-drag-budget-${test.info().workerIndex}`;
+ await api.seedDocs([
+ {
+ name: docName,
+ markdown:
+ '# Summary\n\nGrindelwald in 1945 became master of the Elder Wand.\n\n## Public offices\n\nBeyond Hogwarts, Dumbledore held public office.',
+ },
+ ]);
+ await page.context().addCookies([{ name: 'sidebar_width', value: '288px', url: baseURL }]);
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-doc-panel-width-v1', '320');
+ localStorage.setItem(
+ 'ok-sidebar-pins-v2',
+ JSON.stringify({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ }),
+ );
+ });
+ await page.setViewportSize({ width: 2000, height: 900 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible();
+ const informationDivider = page.locator('[data-doc-panel-handle]');
+ await informationDivider.hover();
+ const ib = await informationDivider.boundingBox();
+ if (!ib) throw new Error('information divider has no bounds');
+ await page.mouse.down();
+ await page.mouse.move(ib.x - 600, ib.y + ib.height / 2, { steps: 8 });
+ await page.mouse.up();
+ await expect
+ .poll(() => page.locator('#doc-panel').evaluate((e) => e.getBoundingClientRect().width))
+ .toBeGreaterThanOrEqual(599);
+ await page.getByTestId('header-pane-button-agents').click();
+ 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]');
+ 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');
+ 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, {
+ steps: 8,
+ });
+ await settleFrames(page);
+ await expect
+ .poll(() =>
+ page
+ .locator('[data-editor-workspace-column]')
+ .evaluate((e) => e.getBoundingClientRect().width),
+ )
+ .toBeGreaterThanOrEqual(300);
+ await expect
+ .poll(() =>
+ page.locator('[data-editor-workspace]').evaluate((e) => e.scrollWidth - e.clientWidth),
+ )
+ .toBeLessThanOrEqual(1);
+ if (target < 1189) await expect(info).toBeHidden();
+ }
+ await page.screenshot({ path: test.info().outputPath('open-information-during-drag.png') });
+ } finally {
+ await page.mouse.up();
+ }
+ await expect(handle).not.toHaveAttribute('data-separator', 'active');
+ await settleFrames(page);
+ await page.screenshot({ path: test.info().outputPath('open-information-after-drag.png') });
+ await expect(info).toBeHidden();
+ await expect
+ .poll(() => card.evaluate((e) => e.getBoundingClientRect().width))
+ .toBeGreaterThanOrEqual(749);
+ await expect
+ .poll(() => card.evaluate((e) => e.getBoundingClientRect().width))
+ .toBeLessThanOrEqual(751);
+ await expect
+ .poll(() =>
+ page
+ .locator('[data-editor-workspace-column]')
+ .evaluate((e) => e.getBoundingClientRect().width),
+ )
+ .toBeGreaterThanOrEqual(300);
+ await expect
+ .poll(() =>
+ page.locator('[data-editor-workspace]').evaluate((e) => e.scrollWidth - e.clientWidth),
+ )
+ .toBeLessThanOrEqual(1);
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await expect(toggle).toBeVisible();
+ expect(await page.evaluate(() => localStorage.getItem('ok-doc-panel-width-v1'))).toBe('600');
+ expect(
+ await toggle.evaluate((e) => {
+ const r = e.getBoundingClientRect();
+ return e.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2));
+ }),
+ ).toBe(true);
+ expect(resizeErrors).toEqual([]);
+});
diff --git a/packages/app/tests/stress/editor-group-switch-immediate-selection.e2e.ts b/packages/app/tests/stress/editor-group-switch-immediate-selection.e2e.ts
new file mode 100644
index 000000000..3ccae8e39
--- /dev/null
+++ b/packages/app/tests/stress/editor-group-switch-immediate-selection.e2e.ts
@@ -0,0 +1,419 @@
+import { randomUUID } from 'node:crypto';
+import { copyFileSync, mkdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Locator, Page } from '@playwright/test';
+import { afterEditorFocusSync, expect, test, waitForActiveProviderSynced } from './_helpers';
+
+const fixtureSuffix = '7bc247b7';
+const lineEndKey = process.platform === 'darwin' ? 'Meta+ArrowRight' : 'End';
+const documentEndKey = process.platform === 'darwin' ? 'Meta+ArrowDown' : 'Control+End';
+
+function paneTabs(page: Page): Locator {
+ return page.locator('[data-editor-header-tabs] [data-editor-pane-tabs]');
+}
+
+async function paneIds(page: Page): Promise<string[]> {
+ return paneTabs(page).evaluateAll((strips) =>
+ strips.flatMap((strip) => {
+ const id = strip.getAttribute('data-editor-pane-tabs');
+ return id ? [id] : [];
+ }),
+ );
+}
+
+function editorForDoc(page: Page, docName: string): Locator {
+ return page.locator(
+ `[data-editor-activity-mount][data-doc-name="${docName}"] .ProseMirror:not(.composer-prosemirror)`,
+ );
+}
+
+async function openDocFromSidebar(page: Page, docName: string): Promise<void> {
+ await page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${docName}.md`, exact: true })
+ .click();
+ await waitForActiveProviderSynced(page);
+ const tab = page.locator(
+ `[data-editor-pane-focused] [data-editor-tab-sortable][data-editor-tab-id="${docName}"]`,
+ );
+ if ((await tab.getAttribute('data-preview-tab')) === 'true') {
+ await tab.click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-keep-open').click();
+ }
+}
+
+async function dragTabToRightEdge(page: Page, tab: Locator, paneId: string): Promise<void> {
+ const tabBox = await tab.boundingBox();
+ if (!tabBox) throw new Error('tab has no box');
+ await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(tabBox.x + tabBox.width / 2 + 12, tabBox.y + tabBox.height / 2, {
+ steps: 2,
+ });
+ const edge = page.locator(`section[data-editor-pane-id="${paneId}"] [data-pane-edge="right"]`);
+ await expect(edge).toBeAttached();
+ const edgeBox = await edge.boundingBox();
+ if (!edgeBox) throw new Error('edge has no box');
+ await page.mouse.move(edgeBox.x + edgeBox.width / 2, edgeBox.y + edgeBox.height / 2, {
+ steps: 8,
+ });
+ await expect(edge).toHaveAttribute('data-pane-drop-side', 'right');
+ await page.mouse.up();
+}
+
+async function readDocument(page: Page, docName: string): Promise<string> {
+ const response = await page.request.get(`/api/document?docName=${encodeURIComponent(docName)}`);
+ expect(response.ok()).toBe(true);
+ const result = (await response.json()) as { content: string };
+ return result.content;
+}
+
+async function readActiveYText(page: Page): Promise<string | null> {
+ return page.evaluate(
+ () => window.__activeProvider?.document.getText('source').toString() ?? null,
+ );
+}
+
+async function selectionSnapshot(page: Page) {
+ return page.evaluate(() => {
+ const editor = window.__activeEditor;
+ if (!editor) return null;
+ const selection = editor.state.selection;
+ const dom = window.getSelection();
+ const editorElement = editor.editorView?.dom ?? null;
+ return {
+ time: performance.now(),
+ anchor: selection.anchor,
+ head: selection.head,
+ anchorOffset: selection.$anchor.parentOffset,
+ headOffset: selection.$head.parentOffset,
+ fromOffset: selection.$from.parentOffset,
+ toOffset: selection.$to.parentOffset,
+ domAnchorOffset: dom?.anchorOffset ?? -1,
+ domFocusOffset: dom?.focusOffset ?? -1,
+ domSelectedText: dom?.toString() ?? '',
+ activeDocName: window.__activeProvider?.configuration.name ?? null,
+ editorFocused:
+ editorElement !== null &&
+ (document.activeElement === editorElement ||
+ editorElement.contains(document.activeElement)),
+ editorPaneId: editorElement
+ ?.closest('[data-editor-pane-id]')
+ ?.getAttribute('data-editor-pane-id'),
+ editorInert: editorElement?.closest('[inert]') !== null,
+ paneInert: document
+ .querySelector('[data-slot="pane-card"][data-pane="editor"]')
+ ?.hasAttribute('inert'),
+ };
+ });
+}
+
+for (const projection of ['wide', 'narrow'] as const) {
+ test(
+ projection === 'narrow'
+ ? 'five consecutive ShiftLeft selections survive a group switch'
+ : 'wide four-pane physical-key control survives a tab switch',
+ async ({ page, api, workerServer }, testInfo) => {
+ const evidenceDir = testInfo.outputDir;
+ const id = randomUUID().slice(0, 8);
+ const labels = ['alpha', 'bravo', 'charlie', 'delta'];
+ const docs = labels.map((label) => ({
+ name: `qa002-${label}-${id}`,
+ markdown: `# ${label}-${id}\n\n${label} body\n\n${Array.from({ length: 70 }, (_, index) => `${label} paragraph ${index}`).join('\n\n')}`,
+ }));
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ mkdirSync(join(evidenceDir, 'screenshots'), { recursive: true });
+ mkdirSync(join(evidenceDir, 'videos'), { recursive: true });
+ try {
+ await api.seedDocs(docs);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await page.goto(`/#/${docs[0].name}`);
+ await waitForActiveProviderSynced(page);
+
+ for (const doc of docs.slice(1)) {
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, doc.name);
+ const ids = await paneIds(page);
+ const paneId = ids.at(-1);
+ if (!paneId) throw new Error('missing focused pane');
+ const tab = page.locator(
+ `[data-editor-pane-tabs="${paneId}"] [data-editor-tab-sortable][data-editor-tab-id="${doc.name}"]`,
+ );
+ await dragTabToRightEdge(page, tab, paneId);
+ await expect(paneTabs(page)).toHaveCount(ids.length + 1);
+ }
+
+ const ids = await paneIds(page);
+ expect(ids).toHaveLength(4);
+ await editorForDoc(page, docs[1].name).locator('p').last().click();
+ await afterEditorFocusSync(page);
+ await page.keyboard.press(lineEndKey);
+ await page.keyboard.type(` isolated-${fixtureSuffix}`);
+ await expect
+ .poll(() => readDocument(page, docs[1].name))
+ .toContain(`bravo paragraph 69 isolated-${fixtureSuffix}`);
+
+ await page.setViewportSize({ width: projection === 'narrow' ? 767 : 2400, height: 800 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ if (projection === 'narrow') await expect(selector).toBeVisible();
+ const selectPane = async (index: number) => {
+ if (projection === 'narrow') {
+ await selector.click();
+ await page.getByRole('option', { name: `Pane ${index + 1}` }).click();
+ } else {
+ await page
+ .locator(
+ `[data-editor-pane-tabs="${ids[index]}"] [data-editor-tab-sortable][data-editor-tab-id="${docs[index].name}"]`,
+ )
+ .click();
+ }
+ };
+ for (const [index, doc] of docs.entries()) {
+ await selectPane(index);
+ await editorForDoc(page, doc.name).locator('p').last().click();
+ await afterEditorFocusSync(page);
+ await page.keyboard.press(documentEndKey);
+ await page.keyboard.type(` group-${index}-${fixtureSuffix}`);
+ await expect
+ .poll(() => readDocument(page, doc.name))
+ .toContain(`group-${index}-${fixtureSuffix}`);
+ }
+
+ await selectPane(1);
+ await editorForDoc(page, docs[1].name).locator('p').last().click();
+ await afterEditorFocusSync(page);
+ await page.keyboard.press(documentEndKey);
+ await expect
+ .poll(() => selectionSnapshot(page))
+ .toMatchObject({ anchorOffset: 53, headOffset: 53, domSelectedText: '' });
+ const before = await selectionSnapshot(page);
+ console.log(
+ JSON.stringify({
+ stage: 'initial-caret',
+ before,
+ bravo: await readDocument(page, docs[1].name),
+ }),
+ );
+ expect(before).toMatchObject({ anchorOffset: 53, headOffset: 53, domSelectedText: '' });
+
+ const siblingBaseline = await Promise.all(
+ docs.filter((_, index) => index !== 1).map((doc) => readDocument(page, doc.name)),
+ );
+ const originalBravo = await readDocument(page, docs[1].name);
+
+ await page.evaluate((captureProjection) => {
+ const events: unknown[] = [];
+ Object.assign(window, { __qa002Events: events });
+ const initialEditor = window.__activeEditor;
+ let shiftLeftKeyups = 0;
+ let firstSwitchPointerdown = false;
+ let firstFocusout = false;
+ const capture = (type: string, key?: string, eventTimeStamp?: number) => {
+ const editor = window.__activeEditor;
+ const selection = editor?.state.selection;
+ const dom = window.getSelection();
+ const editorElement = editor?.editorView?.dom ?? null;
+ events.push({
+ type,
+ key,
+ time: performance.now(),
+ eventTimeStamp,
+ anchor: selection?.anchor,
+ head: selection?.head,
+ anchorOffset: selection?.$anchor.parentOffset,
+ headOffset: selection?.$head.parentOffset,
+ domAnchorOffset: dom?.anchorOffset,
+ domFocusOffset: dom?.focusOffset,
+ domSelectedText: dom?.toString(),
+ editorIsInitial: editor === initialEditor,
+ editorDocName: editor?.storage.collaboration?.document?.guid ?? null,
+ editorFocused:
+ editorElement !== null &&
+ (document.activeElement === editorElement ||
+ editorElement.contains(document.activeElement)),
+ editorPaneId: editorElement
+ ?.closest('[data-editor-pane-id]')
+ ?.getAttribute('data-editor-pane-id'),
+ editorInert: editorElement?.closest('[inert]') !== null,
+ paneInert: document
+ .querySelector('[data-slot="pane-card"][data-pane="editor"]')
+ ?.hasAttribute('inert'),
+ });
+ };
+ document.addEventListener(
+ 'keydown',
+ (event) => capture('keydown', event.key, event.timeStamp),
+ true,
+ );
+ document.addEventListener(
+ 'keyup',
+ (event) => {
+ if (event.key === 'ArrowLeft' && event.shiftKey) shiftLeftKeyups += 1;
+ capture(
+ shiftLeftKeyups === 5 && event.key === 'ArrowLeft' && event.shiftKey
+ ? 'fifth-keyup'
+ : 'keyup',
+ event.key,
+ event.timeStamp,
+ );
+ },
+ true,
+ );
+ document.addEventListener('selectionchange', () => capture('selectionchange'), true);
+ document.addEventListener(
+ 'pointerdown',
+ (event) => {
+ if (shiftLeftKeyups < 5 || firstSwitchPointerdown) return;
+ if (!(event.target instanceof Element)) return;
+ const target =
+ captureProjection === 'narrow'
+ ? event.target.closest('[role="combobox"]')
+ : event.target.closest('[data-editor-tab-sortable]');
+ if (target === null) return;
+ firstSwitchPointerdown = true;
+ capture('first-switch-pointerdown', undefined, event.timeStamp);
+ },
+ true,
+ );
+ document.addEventListener(
+ 'focusout',
+ (event) => {
+ if (shiftLeftKeyups < 5 || firstFocusout) return;
+ firstFocusout = true;
+ capture('first-focusout', undefined, event.timeStamp);
+ },
+ true,
+ );
+ initialEditor?.on('selectionUpdate', () => capture('selectionUpdate'));
+ }, projection);
+
+ for (let index = 0; index < 5; index++) await page.keyboard.press('Shift+ArrowLeft');
+ const immediatelyAfterFive = await selectionSnapshot(page);
+ expect(immediatelyAfterFive).toMatchObject({ domSelectedText: '247b7' });
+ await expect
+ .poll(() => selectionSnapshot(page))
+ .toMatchObject({
+ anchorOffset: 53,
+ headOffset: 48,
+ fromOffset: 48,
+ toOffset: 53,
+ domSelectedText: '247b7',
+ });
+ await selectPane(0);
+ await selectPane(1);
+ const afterSwitch = await selectionSnapshot(page);
+ await editorForDoc(page, docs[1].name).focus();
+ const afterFocus = await selectionSnapshot(page);
+ const eventTrace = await page.evaluate(
+ () => (window as Window & { __qa002Events?: unknown[] }).__qa002Events ?? [],
+ );
+ const matchesFive = (snapshot: Awaited<ReturnType<typeof selectionSnapshot>>) =>
+ snapshot?.anchorOffset === 53 &&
+ snapshot.headOffset === 48 &&
+ snapshot.fromOffset === 48 &&
+ snapshot.toOffset === 53 &&
+ snapshot.domSelectedText === '247b7';
+ const firstDivergence = !matchesFive(immediatelyAfterFive)
+ ? 'immediately-after-fifth-key'
+ : !matchesFive(afterSwitch)
+ ? 'after-group-return-before-focus'
+ : !matchesFive(afterFocus)
+ ? 'after-group-return-and-focus'
+ : null;
+ console.log(
+ JSON.stringify({
+ stage: 'after-switch',
+ projection,
+ firstDivergence,
+ before,
+ immediatelyAfterFive,
+ afterSwitch,
+ afterFocus,
+ eventTrace,
+ pageErrors,
+ }),
+ );
+ await test.info().attach(`group-switch-selection-${projection}-selection-timing.json`, {
+ body: JSON.stringify({
+ projection,
+ firstDivergence,
+ before,
+ immediatelyAfterFive,
+ afterSwitch,
+ afterFocus,
+ eventTrace,
+ docs: docs.map((doc) => doc.name),
+ pageErrors,
+ }),
+ contentType: 'application/json',
+ });
+ expect(afterFocus).toMatchObject({
+ anchorOffset: 53,
+ headOffset: 48,
+ fromOffset: 48,
+ toOffset: 53,
+ domSelectedText: '247b7',
+ });
+ await page.keyboard.type('Z');
+ await page.screenshot({
+ path: join(
+ evidenceDir,
+ 'screenshots',
+ `group-switch-selection-${projection}-five-shift-after-switch.png`,
+ ),
+ fullPage: true,
+ });
+ await expect
+ .poll(() => readDocument(page, docs[1].name))
+ .toContain(`bravo paragraph 69 isolated-${fixtureSuffix} group-1-7bcZ`);
+ const replacedBravo = await readDocument(page, docs[1].name);
+ expect(replacedBravo).not.toContain(`group-1-${fixtureSuffix}`);
+ await expect.poll(() => readActiveYText(page)).toContain('group-1-7bcZ');
+ await expect
+ .poll(() => readFileSync(join(workerServer.contentDir, `${docs[1].name}.md`), 'utf8'))
+ .toContain('group-1-7bcZ');
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect.poll(() => readDocument(page, docs[1].name)).toBe(originalBravo);
+ await expect.poll(() => readActiveYText(page)).toBe(originalBravo);
+ for (const [index, doc] of docs.filter((_, index) => index !== 1).entries()) {
+ expect(await readDocument(page, doc.name)).toBe(siblingBaseline[index]);
+ }
+ await page.screenshot({
+ path: join(
+ evidenceDir,
+ 'screenshots',
+ `group-switch-selection-${projection}-five-shift-after-undo.png`,
+ ),
+ fullPage: true,
+ });
+ console.log(
+ JSON.stringify({
+ stage: 'complete',
+ projection,
+ before,
+ immediatelyAfterFive,
+ afterSwitch,
+ afterFocus,
+ originalBravo,
+ replacedBravo,
+ siblingBaseline,
+ pageErrors,
+ }),
+ );
+ expect(pageErrors).toEqual([]);
+ } finally {
+ const video = page.video();
+ await page.close();
+ if (video)
+ copyFileSync(
+ await video.path(),
+ join(evidenceDir, 'videos', `group-switch-selection-${projection}-five-shift.webm`),
+ );
+ }
+ },
+ );
+}
diff --git a/packages/app/tests/stress/editor-pane-button.e2e.ts b/packages/app/tests/stress/editor-pane-button.e2e.ts
new file mode 100644
index 000000000..0a5c1cb90
--- /dev/null
+++ b/packages/app/tests/stress/editor-pane-button.e2e.ts
@@ -0,0 +1,875 @@
+import type { Page } from '@playwright/test';
+import type { TerminalPlacement } from '../../src/lib/terminal-placement-store';
+import type { ApiHelpers, WorkerServer } from './_helpers';
+import {
+ CHAT_PANE_CARD,
+ EDITOR_PANE_CARD,
+ expect,
+ expectEditorHidden,
+ headerPaneButton,
+ openDesktopHeader,
+ presetTerminalPlacement,
+ setHeaderPane,
+ stubAgentCatalog,
+ terminalPaneCard,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
+
+type Box = {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+};
+
+const RIGHT_TERMINAL_PANE_CARD = terminalPaneCard('right');
+const BOOT_TIMEOUT_MS = 30_000;
+const THREAD_FIRST_RENDER_TIMEOUT_MS = 60_000;
+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 MIN_CARD_PX = 100;
+
+async function boxOf(page: Page, selector: string): Promise<Box> {
+ const box = await page.locator(selector).first().boundingBox();
+ if (box === null) throw new Error(`${selector} has no layout box`);
+ return box;
+}
+
+async function widthOf(page: Page, selector: string): Promise<number> {
+ return await page.evaluate((s) => {
+ const element = document.querySelector(s);
+ if (element === null) throw new Error(`${s} is not rendered`);
+ return element.getBoundingClientRect().width;
+ }, selector);
+}
+
+function otherDocName(slug: string): string {
+ return `editor-pane-${slug}-other-${test.info().workerIndex}`;
+}
+
+async function seedDoc(api: ApiHelpers, slug: string, extraParagraphs = 0): Promise<string> {
+ const name = `editor-pane-${slug}-${test.info().workerIndex}`;
+ const filler = Array.from(
+ { length: extraParagraphs },
+ (_, i) => `Paragraph ${i + 1}. ${DOC_TEXT}`,
+ );
+ const other = otherDocName(slug);
+ await api.seedDocs([
+ { name, markdown: [`# ${name}`, DOC_TEXT, ...filler].join('\n\n') },
+ { name: other, markdown: `# ${other}\n\nThe other document.\n` },
+ ]);
+ return name;
+}
+
+async function waitForDocument(page: Page): Promise<void> {
+ await expect(page.locator('.tiptap-editor .ProseMirror').first()).toContainText(DOC_TEXT, {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+}
+
+async function openWeb(page: Page, api: ApiHelpers, slug: string, extraParagraphs = 0) {
+ const name = await seedDoc(api, slug, extraParagraphs);
+ 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 waitForDocument(page);
+ return name;
+}
+
+async function openDesktop(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ placement: TerminalPlacement,
+) {
+ const name = await seedDoc(api, slug);
+ await stubAgentCatalog(page);
+ await presetTerminalPlacement(page, placement);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await openDesktopHeader(page, workerServer, name, {});
+ await expect(headerPaneButton(page, 'terminal')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await waitForDocument(page);
+ 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 () => {
+ const boxes = await Promise.all(selectors.map((s) => boxOf(page, s)));
+ return Math.min(...boxes.flatMap((b) => [b.width, b.height]));
+ })
+ .toBeGreaterThanOrEqual(MIN_CARD_PX);
+ await expect
+ .poll(async () => {
+ const panels = await boxOf(page, PANELS);
+ const boxes = await Promise.all(selectors.map((s) => boxOf(page, s)));
+ const left = Math.min(...boxes.map((b) => b.x));
+ const right = Math.max(...boxes.map((b) => b.x + b.width));
+ return Math.round(Math.abs(left - panels.x) + Math.abs(panels.x + panels.width - right));
+ })
+ .toBeLessThanOrEqual(2);
+}
+
+test.describe('the Editor header button', () => {
+ test('sits first in the Panels group, names itself Editor and shows no shortcut', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'order');
+ const names = await page
+ .getByRole('group', { name: 'Panels' })
+ .getByRole('button')
+ .evaluateAll((buttons) => buttons.map((b) => b.getAttribute('aria-label')));
+ expect(names).toEqual(['Editor', 'Agents']);
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+
+ await headerPaneButton(page, 'editor').hover();
+ const tooltip = page.getByRole('tooltip');
+ await expect(tooltip).toHaveText('Editor');
+ await expect(tooltip.locator('[data-slot="kbd"]')).toHaveCount(0);
+ });
+
+ test('keyboard activation hides the editor keeping focus on the button, and shows it moving focus into the editor', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'keyboard');
+ await headerPaneButton(page, 'editor').focus();
+ await page.keyboard.press('Enter');
+ await expectEditorHidden(page);
+ await expect(headerPaneButton(page, 'editor')).toBeFocused();
+
+ await page.keyboard.press('Space');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.locator(EDITOR_PANE_CARD)).not.toHaveAttribute('inert', '');
+ await expect(page.locator(EDITOR_REGION)).toBeFocused();
+ });
+
+ test('hiding and showing brings back the same editor, tabs and scroll position without reloading', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'same-instance', 80);
+ await setHeaderPane(page, 'agents', true);
+ const scroller = page.getByTestId('editor-scroll-container').first();
+ await expect(scroller).toBeVisible();
+ await scroller.evaluate((el) => {
+ el.scrollTop = 900;
+ });
+ const before = await page.evaluate(() => {
+ const editor = document.querySelector('.tiptap-editor .ProseMirror') as
+ | (HTMLElement & { __editorPaneMark?: string })
+ | null;
+ if (editor === null) throw new Error('no editor');
+ editor.__editorPaneMark = 'kept';
+ return {
+ tabs: [...document.querySelectorAll('[data-editor-tab-id]')].map((t) =>
+ t.getAttribute('data-editor-tab-id'),
+ ),
+ };
+ });
+ const scrollBefore = await scroller.evaluate((el) => el.scrollTop);
+ expect(scrollBefore).toBeGreaterThan(0);
+
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await setHeaderPane(page, 'editor', true);
+
+ await expect(page.locator(EDITOR_PANE_CARD)).not.toHaveAttribute('inert', '');
+ const after = await page.evaluate(() => {
+ const editor = document.querySelector('.tiptap-editor .ProseMirror') as
+ | (HTMLElement & { __editorPaneMark?: string })
+ | null;
+ return {
+ mark: editor?.__editorPaneMark ?? null,
+ tabs: [...document.querySelectorAll('[data-editor-tab-id]')].map((t) =>
+ t.getAttribute('data-editor-tab-id'),
+ ),
+ };
+ });
+ expect(after.mark).toBe('kept');
+ expect(after.tabs).toEqual(before.tabs);
+ await expect.poll(() => scroller.evaluate((el) => el.scrollTop)).toBe(scrollBefore);
+ });
+
+ test('chat alone fills the row, and the file list, checkout line and Ask AI box go with the editor', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'chat-alone');
+ await setHeaderPane(page, 'agents', true);
+ const chatWidthBefore = await widthOf(page, CHAT_PANE_CARD);
+
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expectEditorColumnEmpty(page);
+ await expectFillsRow(page, [CHAT_PANE_CARD]);
+ await expect(page.locator('[data-editor-file-list-slot]')).not.toBeInViewport();
+ await expect(
+ page.getByRole('region', { name: /Document statistics|Editor status bar/ }),
+ ).not.toBeVisible();
+
+ await setHeaderPane(page, 'editor', true);
+ await expect.poll(() => widthOf(page, CHAT_PANE_CARD)).toBeCloseTo(chatWidthBefore, 0);
+ });
+});
+
+test.describe('filling the space on the mocked desktop', () => {
+ async function expectBottomTerminalBesideChat(page: Page): Promise<void> {
+ await expectFillsRow(page, [BOTTOM_TERMINAL_CARD, CHAT_PANE_CARD]);
+ await expect
+ .poll(
+ async () =>
+ (await boxOf(page, PANELS)).height - (await boxOf(page, BOTTOM_TERMINAL_CARD)).height,
+ )
+ .toBeLessThanOrEqual(2);
+ await expect(headerPaneButton(page, 'terminal')).toHaveAttribute('aria-pressed', 'true');
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'true');
+ }
+
+ test('a bottom terminal takes the full height alone, then keeps its column beside chat', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'bottom', 'bottom');
+ await setHeaderPane(page, 'terminal', true);
+ const heightBefore = (await boxOf(page, BOTTOM_TERMINAL_CARD)).height;
+
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expect
+ .poll(async () => {
+ const panels = await boxOf(page, PANELS);
+ const terminal = await boxOf(page, BOTTOM_TERMINAL_CARD);
+ return Math.round(Math.abs(panels.height - terminal.height));
+ })
+ .toBeLessThanOrEqual(2);
+ await expectFillsRow(page, [BOTTOM_TERMINAL_CARD]);
+
+ await setHeaderPane(page, 'agents', true);
+ await expectBottomTerminalBesideChat(page);
+
+ await setHeaderPane(page, 'editor', true);
+ await expect
+ .poll(async () => (await boxOf(page, BOTTOM_TERMINAL_CARD)).height)
+ .toBeCloseTo(heightBefore, 0);
+ });
+
+ test('hiding the editor beside chat, or opening a bottom terminal beside chat alone, keeps the terminal on screen', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'bottom-chat-first', 'bottom');
+ await setHeaderPane(page, 'terminal', true);
+ await setHeaderPane(page, 'agents', true);
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expectBottomTerminalBesideChat(page);
+
+ await setHeaderPane(page, 'terminal', false);
+ await expectFillsRow(page, [CHAT_PANE_CARD]);
+ await setHeaderPane(page, 'terminal', true);
+ await expectBottomTerminalBesideChat(page);
+ });
+
+ test('a right terminal alone fills the row', async ({ page, api, workerServer }) => {
+ await openDesktop(page, api, workerServer, 'right-alone', 'right');
+ await setHeaderPane(page, 'terminal', true);
+
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+ await expectEditorColumnEmpty(page);
+ 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 ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'right-and-chat', 'right');
+ await setHeaderPane(page, 'terminal', true);
+ await setHeaderPane(page, 'agents', true);
+ 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 expectFillsRow(page, [RIGHT_TERMINAL_PANE_CARD, CHAT_PANE_CARD]);
+ await expect
+ .poll(
+ async () =>
+ (await widthOf(page, RIGHT_TERMINAL_PANE_CARD)) / (await widthOf(page, CHAT_PANE_CARD)),
+ )
+ .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);
+ 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, '#doc-panel')).toBeCloseTo(sidePanelBefore, 0);
+ });
+});
+
+async function openThread(page: Page, title: string): Promise<string> {
+ await page.waitForFunction(() => Boolean(window.__acpThreadHarness), null, {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ const threadId = await page.evaluate((threadTitle) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ return harness.openThread({
+ agent: { id: 'editor-pane-agent', name: 'Editor Pane Agent', source: 'registry' },
+ title: threadTitle,
+ });
+ }, title);
+ await expect(page.locator('[data-agent-thread-root]')).toBeVisible({
+ timeout: THREAD_FIRST_RENDER_TIMEOUT_MS,
+ });
+ return threadId;
+}
+
+async function pushAgentMessage(page: Page, threadId: string, text: string): Promise<void> {
+ await page.evaluate(
+ ({ id, message }) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ harness.pushUpdates(id, [
+ { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: message } },
+ ] as Parameters<typeof harness.pushUpdates>[1]);
+ },
+ { id: threadId, message: text },
+ );
+}
+
+type ThreadColumnPart = 'header' | 'transcript' | 'composer';
+
+async function threadColumn(
+ page: Page,
+ part: ThreadColumnPart = 'header',
+): Promise<{ width: number; centerOffset: number }> {
+ return await page.evaluate((which) => {
+ const root = document.querySelector('[data-agent-thread-root]');
+ if (!(root instanceof HTMLElement)) throw new Error('no thread root');
+ const rootBox = root.getBoundingClientRect();
+ const contentBox = (element: Element | null | undefined) => {
+ if (!(element instanceof HTMLElement)) throw new Error(`no thread ${which}`);
+ const box = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ const left = box.left + Number.parseFloat(style.paddingLeft);
+ const right = box.right - Number.parseFloat(style.paddingRight);
+ return { left, width: right - left };
+ };
+ const composer = root.querySelector('[data-testid="agent-thread-composer"]');
+ const box =
+ which === 'header'
+ ? contentBox(root.firstElementChild)
+ : which === 'transcript'
+ ? contentBox(root.querySelector('[data-testid="agent-thread-transcript"]'))
+ : contentBox(
+ [...root.children].find((child) => composer !== null && child.contains(composer)),
+ );
+ return {
+ width: box.width,
+ centerOffset: Math.abs(box.left + box.width / 2 - (rootBox.left + rootBox.width / 2)),
+ };
+ }, part);
+}
+
+test.describe('chat on its own', () => {
+ test('keeps its conversation at a reading width, centered, and goes back to full width beside another pane', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'reading-width');
+ await openThread(page, 'Reading width');
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'true');
+ const besideEditor = await threadColumn(page);
+
+ await setHeaderPane(page, 'editor', false);
+ await expectFillsRow(page, [CHAT_PANE_CARD]);
+ for (const part of ['header', 'transcript', 'composer'] as const) {
+ await expect
+ .poll(async () => (await threadColumn(page, part)).width)
+ .toBeLessThanOrEqual(768);
+ expect((await threadColumn(page, part)).centerOffset).toBeLessThanOrEqual(1);
+ }
+ expect(await widthOf(page, CHAT_PANE_CARD)).toBeGreaterThan(1200);
+
+ const dataTransfer = await page.evaluateHandle(() => {
+ const transfer = new DataTransfer();
+ transfer.items.add(new File(['hello'], 'hello.txt', { type: 'text/plain' }));
+ return transfer;
+ });
+ await page.locator('[data-agent-thread-root]').dispatchEvent('dragenter', { dataTransfer });
+ const overlay = page.getByTestId('agent-thread-drop-overlay');
+ await expect(overlay).toBeVisible();
+ const rootBox = await boxOf(page, '[data-agent-thread-root]');
+ const overlayBox = await boxOf(page, '[data-testid="agent-thread-drop-overlay"]');
+ expect(Math.abs(overlayBox.x - rootBox.x)).toBeLessThanOrEqual(1);
+ expect(Math.abs(overlayBox.width - rootBox.width)).toBeLessThanOrEqual(1);
+ await overlay.click();
+
+ await setHeaderPane(page, 'editor', true);
+ await expect
+ .poll(async () => (await threadColumn(page)).width)
+ .toBeCloseTo(besideEditor.width, 0);
+ });
+});
+
+test.describe('Nothing open', () => {
+ test('appears when every pane is hidden, with no Ask AI box, and each button opens its pane', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'nothing-open');
+ await setHeaderPane(page, 'editor', false);
+ const screenRegion = page.getByRole('region', { name: 'Nothing open' });
+ await expect(screenRegion).toBeVisible();
+ await expect(screenRegion).toContainText('Nothing open');
+ await expect(screenRegion.getByRole('button')).toHaveText(['Open editor', 'Open agents']);
+ await expect(page.getByRole('textbox', { name: /Ask AI/i })).toHaveCount(0);
+
+ await screenRegion.getByRole('button', { name: 'Open agents' }).click();
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'true');
+ await expect(screenRegion).toHaveCount(0);
+ await expectFillsRow(page, [CHAT_PANE_CARD]);
+
+ await setHeaderPane(page, 'agents', false);
+ await expect(screenRegion).toBeVisible();
+ await screenRegion.getByRole('button', { name: 'Open editor' }).focus();
+ await page.keyboard.press('Enter');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(screenRegion).toHaveCount(0);
+ await expect(page.locator(EDITOR_REGION)).toBeFocused();
+ await waitForDocument(page);
+ });
+
+ test('offers Open terminal on the desktop, and it opens the terminal', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'nothing-open-desktop', 'bottom');
+ await setHeaderPane(page, 'editor', false);
+ const screenRegion = page.getByRole('region', { name: 'Nothing open' });
+ await expect(screenRegion.getByRole('button')).toHaveText([
+ 'Open editor',
+ 'Open agents',
+ 'Open terminal',
+ ]);
+
+ await screenRegion.getByRole('button', { name: 'Open terminal' }).click();
+ await expect(headerPaneButton(page, 'terminal')).toHaveAttribute('aria-pressed', 'true');
+ await expect(screenRegion).toHaveCount(0);
+ await expectFillsRow(page, [BOTTOM_TERMINAL_CARD]);
+ });
+});
+
+async function expectEditorShownOn(page: Page, docName: string): Promise<void> {
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.locator(EDITOR_PANE_CARD)).not.toHaveAttribute('inert', '');
+ await expect
+ .poll(() => page.evaluate(() => decodeURIComponent(window.location.hash)))
+ .toContain(docName);
+}
+
+async function quickOpen(page: Page, docName: string): Promise<void> {
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await expect(input).toBeFocused();
+ await input.fill(docName);
+ const row = page.locator(`[data-slot="command-list"] [data-testid^="command-palette-nav-"]`, {
+ hasText: docName,
+ });
+ await expect(row.first()).toBeVisible();
+ await row.first().click();
+ await expect(page.locator('[data-slot="command-list"]')).toBeHidden();
+}
+
+async function hideEditor(page: Page): Promise<void> {
+ await setHeaderPane(page, 'editor', false);
+ await expectEditorHidden(page);
+}
+
+test.describe('deliberate opens show a hidden editor', () => {
+ test('quick open of another document and of the active one both show the editor on it', async ({
+ page,
+ api,
+ }) => {
+ const active = await openWeb(page, api, 'quick-open');
+ const other = otherDocName('quick-open');
+
+ await hideEditor(page);
+ await quickOpen(page, other);
+ await expectEditorShownOn(page, other);
+
+ await hideEditor(page);
+ await quickOpen(page, other);
+ await expectEditorShownOn(page, other);
+ expect(active).not.toBe(other);
+ });
+
+ test('going back shows the editor on the earlier document', async ({ page, api }) => {
+ const first = await openWeb(page, api, 'back');
+ const second = otherDocName('back');
+ for (const docName of [second, first]) {
+ await page.evaluate((hash) => {
+ window.location.hash = hash;
+ }, `#/${docName}`);
+ await expectEditorShownOn(page, docName);
+ }
+
+ await hideEditor(page);
+ await page.goBack();
+ await expectEditorShownOn(page, second);
+ });
+
+ test('a link in an agent message to the document already open shows the editor', async ({
+ page,
+ api,
+ }) => {
+ const name = await openWeb(page, api, 'agent-link');
+ await setHeaderPane(page, 'agents', true);
+ const threadId = await openThread(page, 'Agent link');
+ await pushAgentMessage(page, threadId, `See [the notes](#/${name}).`);
+ const link = page.getByTestId('agent-thread-doc-link');
+ await expect(link).toBeVisible();
+
+ await hideEditor(page);
+ await link.click();
+ await expectEditorShownOn(page, name);
+ });
+
+ test('follow-the-agent navigation to another document shows the editor', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'follow');
+ const second = otherDocName('follow');
+ await setHeaderPane(page, 'agents', true);
+ const threadId = await openThread(page, 'Follow');
+ await page.evaluate((id) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ harness.frame({
+ op: 'event',
+ threadId: id,
+ seq: 0,
+ event: { kind: 'turn_started', ts: Date.now() },
+ });
+ }, threadId);
+
+ await hideEditor(page);
+ await page.evaluate(
+ ({ id, docName }) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ harness.pushUpdates(id, [
+ {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'follow-edit',
+ title: 'Edit the other document',
+ kind: 'edit',
+ status: 'completed',
+ rawInput: { tool: 'edit', arguments: { docName } },
+ },
+ ] as Parameters<typeof harness.pushUpdates>[1]);
+ },
+ { id: threadId, docName: second },
+ );
+ await expectEditorShownOn(page, second);
+ });
+
+ test('a comment marker on the document leaves with the editor and returns with it', async ({
+ page,
+ api,
+ }) => {
+ const name = await openWeb(page, api, 'comment-marker');
+ const created = await page.request.post('/api/comments', {
+ data: { docName: name, quote: 'brown fox', body: 'Is the fox brown?' },
+ });
+ expect(created.ok()).toBe(true);
+ const marker = page.getByRole('button', { name: 'Open comment', exact: true });
+ await expect(marker).toBeVisible();
+
+ await hideEditor(page);
+ await expect(marker).toHaveCount(0);
+
+ await setHeaderPane(page, 'editor', true);
+ await expect(marker).toBeVisible();
+ });
+
+ test('the bubble menu over a selection leaves with the editor', async ({ page, api }) => {
+ await openWeb(page, api, 'bubble-menu');
+ await page.locator('.tiptap-editor .ProseMirror p').first().selectText();
+ const bubbleMenu = page.getByTestId('bubble-menu-bar');
+ await expect(bubbleMenu).toBeVisible();
+
+ await hideEditor(page);
+ await expect(bubbleMenu).toHaveCount(0);
+ });
+
+ test('renaming the open document keeps a hidden editor hidden, while an address change from outside shows it', async ({
+ page,
+ api,
+ }) => {
+ const first = await openWeb(page, api, 'rename');
+ const second = otherDocName('rename');
+ await quickOpen(page, second);
+ await expectEditorShownOn(page, second);
+ await expect(page.locator('[data-editor-tab-id]')).toHaveCount(2);
+ await hideEditor(page);
+ await page.evaluate(() => {
+ const counted = window as unknown as { __hashChanges: number };
+ counted.__hashChanges = 0;
+ window.addEventListener('hashchange', () => {
+ counted.__hashChanges += 1;
+ });
+ });
+
+ const renamed = `${second}-renamed`;
+ const response = await page.request.post('/api/rename-path', {
+ data: { kind: 'file', fromPath: second, toPath: renamed },
+ });
+ expect(response.ok()).toBe(true);
+ await expect
+ .poll(() => page.evaluate(() => decodeURIComponent(window.location.hash)))
+ .toContain(renamed);
+ await expect
+ .poll(() =>
+ page.evaluate(() => (window as unknown as { __hashChanges: number }).__hashChanges),
+ )
+ .toBeGreaterThan(0);
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ ),
+ );
+ await expectEditorHidden(page);
+
+ await page.evaluate((hash) => {
+ window.location.hash = hash;
+ }, `#/${first}`);
+ await expectEditorShownOn(page, first);
+ });
+
+ async function runPaletteCommand(page: Page, query: string, commandId: string): Promise<void> {
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await expect(input).toBeFocused();
+ await input.fill(query);
+ const row = page.getByTestId(`command-palette-${commandId}`);
+ await expect(row).toBeVisible();
+ await row.click();
+ }
+
+ test('Blob Run from the palette shows the editor with the game open', async ({ page, api }) => {
+ await openWeb(page, api, 'blob-run');
+ await hideEditor(page);
+ await runPaletteCommand(page, 'blob', 'open-blob-run');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.locator('[data-slot="ok-blob-runner"]')).toBeVisible();
+ });
+
+ test('Skills from the palette shows the editor with the skills dock open', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'skills-dock');
+ await hideEditor(page);
+ await runPaletteCommand(page, 'skills', 'open-skills');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByTestId('skills-dock')).toBeVisible();
+ });
+
+ test('the sidebar view and tree commands from the palette show the editor', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'tree-commands');
+ await hideEditor(page);
+ await runPaletteCommand(page, 'expand', 'expand-all-tree');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+
+ await hideEditor(page);
+ await runPaletteCommand(page, 'hidden', 'toggle-show-hidden-files');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ });
+
+ test('a file created from the palette opens with the editor shown', async ({ page, api }) => {
+ await openWeb(page, api, 'palette-new-file');
+ await hideEditor(page);
+ await runPaletteCommand(page, 'new file', 'new-file');
+ const name = `palette-made-${test.info().workerIndex}`;
+ const nameInput = page.getByPlaceholder('my-note');
+ await expect(nameInput).toBeVisible();
+ await nameInput.fill(name);
+ await nameInput.press('Enter');
+ await expectEditorShownOn(page, name);
+ });
+
+ test('asking for a side panel tab from the palette shows the editor', async ({ page, api }) => {
+ await openWeb(page, api, 'graph');
+ await hideEditor(page);
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await input.fill('graph');
+ await page.getByTestId('command-palette-open-graph').click();
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ });
+});
+
+test.describe('editor shortcuts show a hidden editor before acting', () => {
+ test('the next-tab shortcut shows the editor and switches tabs', async ({ page, api }) => {
+ const first = await openWeb(page, api, 'next-tab');
+ const second = otherDocName('next-tab');
+ const editor = page.locator('.tiptap-editor .ProseMirror').first();
+ await editor.click();
+ await page.keyboard.press('End');
+ await page.keyboard.type(' kept');
+ await expect(editor).toContainText('kept');
+ await quickOpen(page, second);
+ await expectEditorShownOn(page, second);
+ await expect(page.locator('[data-editor-tab-id]')).toHaveCount(2);
+
+ await hideEditor(page);
+ await page.keyboard.press('Control+Tab');
+ await expectEditorShownOn(page, first);
+ });
+
+ test('Rename from the palette shows the editor first, so the inline name field is visible and focused', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = await openDesktop(page, api, workerServer, 'rename-inline', 'bottom');
+ await hideEditor(page);
+ await page.keyboard.press('ControlOrMeta+k');
+ await page.locator('[data-slot="command-input"]').fill('Rename');
+ await page.getByTestId('command-palette-rename').click();
+
+ const nameField = page.getByRole('textbox', { name: new RegExp(`rename ${name}\\.md`, 'i') });
+ await expect(nameField).toBeVisible();
+ await expect(nameField).toBeFocused();
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ });
+
+ test('the side panel and file list shortcuts show the editor', async ({ page, api }) => {
+ await openWeb(page, api, 'panel-shortcuts');
+ await hideEditor(page);
+ await page.keyboard.press('ControlOrMeta+Alt+KeyB');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+
+ await hideEditor(page);
+ await page.keyboard.press('ControlOrMeta+Alt+KeyS');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ });
+});
+
+test.describe('the editor level is remembered', () => {
+ test('a reload keeps a hidden editor hidden, with the document in the address, and reopens to Nothing open', async ({
+ page,
+ api,
+ }) => {
+ const name = await openWeb(page, api, 'reload');
+ await hideEditor(page);
+ await expect(page.getByRole('region', { name: 'Nothing open' })).toBeVisible();
+
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'false');
+ await expect(page.getByRole('region', { name: 'Nothing open' })).toBeVisible();
+ expect(await page.evaluate(() => decodeURIComponent(window.location.hash))).toContain(name);
+
+ await page
+ .getByRole('region', { name: 'Nothing open' })
+ .getByRole('button', {
+ name: 'Open editor',
+ })
+ .click();
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await waitForDocument(page);
+ });
+
+ test('the palette offers Hide Editor, then Show Editor once hidden', async ({ page, api }) => {
+ await openWeb(page, api, 'palette-label');
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await input.fill('editor');
+ await expect(page.getByTestId('command-palette-toggle-editor')).toContainText('Hide Editor');
+ await page.getByTestId('command-palette-toggle-editor').click();
+ await expectEditorHidden(page);
+
+ await page.keyboard.press('ControlOrMeta+k');
+ await input.fill('editor');
+ await expect(page.getByTestId('command-palette-toggle-editor')).toContainText('Show Editor');
+ await page.getByTestId('command-palette-toggle-editor').click();
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ });
+});
+
+test.describe('dialogs that ride the address bar', () => {
+ test('opening and closing Settings leaves a hidden editor hidden', async ({ page, api }) => {
+ const name = await openWeb(page, api, 'settings-dialog');
+ await hideEditor(page);
+
+ await page.evaluate(() => {
+ window.location.hash = '#settings';
+ });
+ await expect(page.getByTestId('settings-dialog')).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(page.getByTestId('settings-dialog')).toHaveCount(0);
+ await expect
+ .poll(() => page.evaluate(() => decodeURIComponent(window.location.hash)))
+ .toContain(name);
+
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'false');
+ await expect(page.getByRole('region', { name: 'Nothing open' })).toBeVisible();
+ });
+
+ test('a template created from Settings opens with the editor shown', async ({ page, api }) => {
+ await openWeb(page, api, 'settings-open');
+ await hideEditor(page);
+
+ await page.evaluate(() => {
+ window.location.hash = '#settings/project-templates';
+ });
+ await expect(page.getByTestId('settings-dialog')).toBeVisible();
+ await page.getByTestId('settings-project-templates-new-button').click();
+ const templateName = `pane-template-${test.info().workerIndex}`;
+ await page.getByTestId('template-name-input').fill(templateName);
+ await page.getByRole('button', { name: 'Create template' }).click();
+
+ await expect(page.getByTestId('settings-dialog')).toHaveCount(0);
+ await expectEditorShownOn(page, `.ok/templates/${templateName}`);
+ });
+});
diff --git a/packages/app/tests/stress/editor-pane-cards.e2e.ts b/packages/app/tests/stress/editor-pane-cards.e2e.ts
new file mode 100644
index 000000000..cacaf48ab
--- /dev/null
+++ b/packages/app/tests/stress/editor-pane-cards.e2e.ts
@@ -0,0 +1,1490 @@
+import AxeBuilder from '@axe-core/playwright';
+import type {
+ ThreadClientFrame,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type { Locator, Page, WebSocketRoute } from '@playwright/test';
+import { PANE_CARD_GAP_PX } from '../../src/components/ui/pane-card';
+import {
+ acpCatalogBody,
+ expect,
+ switchColorThemeAndSettleFade,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
+import { startHiddenChatAgent } from './hidden-chat-transport.test-helper';
+
+const EDITOR_CARD = '[data-slot="pane-card"][data-pane="editor"]';
+const CHAT_CARD = '[data-slot="pane-card"][data-pane="agents"]';
+const TERMINAL_CARD = '[data-slot="pane-card"][data-pane="terminal"]';
+const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';
+const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
+const TOP_BAR_PX = 44;
+const BOOT_TIMEOUT_MS = 30_000;
+const PX_TOLERANCE = 1;
+
+const DOC_MARKDOWN = `---
+title: "Pane cards"
+description: "Fixture doc for the editor, chat and terminal card geometry"
+---
+
+# Pane cards
+
+Body text so the document column renders real content while the cards are measured.`;
+
+interface Rect {
+ readonly top: number;
+ readonly left: number;
+ readonly right: number;
+ readonly bottom: number;
+ readonly height: number;
+ readonly width: number;
+}
+
+async function rectOf(locator: Locator): Promise<Rect> {
+ return locator.evaluate((element) => {
+ const r = element.getBoundingClientRect();
+ return {
+ top: r.top,
+ left: r.left,
+ right: r.right,
+ bottom: r.bottom,
+ height: r.height,
+ width: r.width,
+ };
+ });
+}
+
+async function openDoc(
+ page: Page,
+ api: { seedDocs: (docs: Array<{ name: string; markdown: string }>) => Promise<void> },
+ width: number,
+) {
+ const docName = `editor-pane-cards-${width}-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.setViewportSize({ width, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible({
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ return docName;
+}
+
+async function openChat(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 });
+ await expect(page.locator('[data-dragging="true"]')).toHaveCount(0);
+}
+
+async function noSidewaysScroll(page: Page): Promise<void> {
+ const overflow = await page.evaluate(() => ({
+ scrollWidth: document.documentElement.scrollWidth,
+ clientWidth: document.documentElement.clientWidth,
+ }));
+ expect(overflow.scrollWidth).toBeLessThanOrEqual(overflow.clientWidth + PX_TOLERANCE);
+}
+
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
+
+test('the editor and chat cards stand side by side, full height, one gap apart, under matching 44px top bars', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ await expect
+ .poll(() => page.locator('[data-doc-panel-toggle]').getAttribute('aria-expanded'), {
+ timeout: 10_000,
+ })
+ .toBe('true');
+ await openChat(page);
+
+ const editorCard = page.locator(EDITOR_CARD);
+ const chatCard = page.locator(CHAT_CARD);
+ await expect(editorCard).toBeVisible();
+ await expect(chatCard).toBeVisible();
+ const [editor, chat] = await Promise.all([rectOf(editorCard), rectOf(chatCard)]);
+
+ expect(
+ Math.abs(chat.top - editor.top),
+ 'the chat card top lines up with the editor card',
+ ).toBeLessThanOrEqual(PX_TOLERANCE);
+ expect(
+ Math.abs(chat.bottom - editor.bottom),
+ 'the chat card runs the full height of the editor card',
+ ).toBeLessThanOrEqual(PX_TOLERANCE);
+ expect(
+ Math.abs(chat.left - editor.right - PANE_CARD_GAP_PX),
+ 'one gap separates the two cards',
+ ).toBeLessThanOrEqual(PX_TOLERANCE);
+
+ const tabRow = editorCard.locator('header[data-editor-header]');
+ const sidePanelHeader = editorCard.locator('[data-doc-panel-header]');
+ const chatBar = chatCard.locator('[data-terminal-tab-row]');
+ const [tabRowRect, sidePanelHeaderRect, chatBarRect] = await Promise.all([
+ rectOf(tabRow),
+ rectOf(sidePanelHeader),
+ rectOf(chatBar),
+ ]);
+ for (const [label, bar, cardTop] of [
+ ['tab row', tabRowRect, editor.top],
+ ['side panel header', sidePanelHeaderRect, editor.top],
+ ['chat top bar', chatBarRect, chat.top],
+ ] as const) {
+ expect(
+ Math.abs(bar.height - TOP_BAR_PX),
+ `${label} is ${TOP_BAR_PX}px tall`,
+ ).toBeLessThanOrEqual(PX_TOLERANCE);
+ expect(Math.abs(bar.top - cardTop), `${label} sits at the top of its card`).toBeLessThanOrEqual(
+ PX_TOLERANCE,
+ );
+ }
+ await expect(tabRow.locator('[data-doc-panel-toggle]')).toHaveCount(1);
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveCount(1);
+ const [tabCanvasRect, tabGroupRect, newTabRect, toggleRect] = await Promise.all([
+ rectOf(tabRow.locator('[data-editor-header-tab-canvas]')),
+ rectOf(tabRow.locator('[data-editor-pane-tab-group]').last()),
+ rectOf(tabRow.getByTestId('editor-new-tab-button')),
+ rectOf(tabRow.locator('[data-doc-panel-toggle]')),
+ ]);
+ expect(
+ Math.abs(tabGroupRect.right - tabCanvasRect.right),
+ 'the tab group still spans to the end of the tab canvas under the toggle',
+ ).toBeLessThanOrEqual(PX_TOLERANCE);
+ expect(newTabRect.right, 'the new tab button ends before the toggle').toBeLessThanOrEqual(
+ toggleRect.left + PX_TOLERANCE,
+ );
+
+ for (const card of [editorCard, chatCard]) {
+ const clipping = await card.evaluate((element) => {
+ const clippers: string[] = [];
+ let cur: Element | null = element.parentElement;
+ while (cur != null && cur !== document.body) {
+ if (getComputedStyle(cur).overflow !== 'visible') clippers.push(cur.className.toString());
+ cur = cur.parentElement;
+ }
+ return clippers;
+ });
+ expect(clipping, 'nothing between the cards and the window clips their shadows').toEqual([]);
+ }
+
+ await expect(page.locator(TERMINAL_CARD), 'the web draws no terminal card').toHaveCount(0);
+ await expect(page.locator('#terminal-dock-panel')).toHaveCount(0);
+ await noSidewaysScroll(page);
+});
+
+test('at 320px nothing scrolls sideways and the web still draws no terminal card', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 320);
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(TERMINAL_CARD)).toHaveCount(0);
+ await noSidewaysScroll(page);
+});
+
+test('the last selected component stands alone below 48rem and widening restores both cards', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 769);
+ await openChat(page);
+ const editorHandle = await page.locator(EDITOR_CARD).elementHandle();
+ const chatHandle = await page.locator(CHAT_CARD).elementHandle();
+ if (editorHandle == null || chatHandle == null) throw new Error('component cards did not mount');
+ const savedWideVisibility = await page.evaluate(() => ({
+ editor: localStorage.getItem('ok-editor-visible-v1'),
+ chat: JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}').agentPanelVisible as
+ | boolean
+ | undefined,
+ }));
+ const measurements: Array<{ width: number; editor: Rect; chat: Rect }> = [];
+
+ for (const width of [768, 767, 320, 768, 769, 768, 767, 768, 769]) {
+ await page.setViewportSize({ width, height: 800 });
+ const editor = page.locator(EDITOR_CARD);
+ const chat = page.locator(CHAT_CARD);
+ if (width < 768) {
+ await expect(editor).toBeHidden();
+ await expect(chat).toBeVisible();
+ await expect(editor).toHaveAttribute('inert', '');
+ await expect(page.getByTestId('header-pane-button-agents')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ expect((await rectOf(chat)).width).toBeGreaterThan(width - 32);
+ if (width === 767) {
+ await test.info().attach('selected-chat-767', {
+ body: await page.screenshot(),
+ contentType: 'image/png',
+ });
+ await page.getByTestId('header-pane-button-agents').click();
+ await expect(chat).toBeVisible();
+ expect(await chat.evaluate((element, original) => element === original, chatHandle)).toBe(
+ true,
+ );
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(editor).toBeVisible();
+ await expect(chat).toBeHidden();
+ expect(
+ await editor.evaluate((element, original) => element === original, editorHandle),
+ ).toBe(true);
+ await page.getByTestId('header-pane-button-agents').click();
+ await expect(chat).toBeVisible();
+ }
+ } else {
+ await expect(editor).toBeVisible();
+ await expect(chat).toBeVisible();
+ }
+ measurements.push({ width, editor: await rectOf(editor), chat: await rectOf(chat) });
+ await noSidewaysScroll(page);
+ }
+ expect(
+ await page.evaluate(() => ({
+ editor: localStorage.getItem('ok-editor-visible-v1'),
+ chat: JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}')
+ .agentPanelVisible as boolean | undefined,
+ })),
+ ).toEqual(savedWideVisibility);
+ await test.info().attach('component-bounds', {
+ body: JSON.stringify({ measurements, savedWideVisibility }, null, 2),
+ contentType: 'application/json',
+ });
+});
+
+test('working in an already visible Editor wins the next narrow selection', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ await openChat(page);
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await editor.click();
+ await page.keyboard.type(' working in Editor');
+ await expect(editor).toContainText('working in Editor');
+
+ await page.setViewportSize({ width: 767, height: 800 });
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+});
+
+test('hiding and showing chat never remounts the open editor', async ({ page, api }) => {
+ await openDoc(page, api, 1400);
+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ const editorHandle = await editor.elementHandle();
+ if (editorHandle == null) throw new Error('no editor to follow across the chat toggles');
+
+ await openChat(page);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.getByTestId(AGENTS_HEADER_BUTTON)).toHaveAttribute('aria-pressed', 'false');
+ await openChat(page);
+
+ expect(await editorHandle.evaluate((element) => element.isConnected)).toBe(true);
+ expect(
+ await editor.evaluate((current, followed) => current === followed, editorHandle),
+ 'the same editor element is still the open editor',
+ ).toBe(true);
+});
+
+test('hiding selected chat in a narrow workspace returns to Editor and keeps the wide layout', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ await openChat(page);
+ const editor = page.locator(EDITOR_CARD);
+ const chat = page.locator(CHAT_CARD);
+ const chatHandle = await chat.elementHandle();
+ if (chatHandle === null) throw new Error('Chat card is missing');
+
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(chat).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+l');
+
+ await expect(editor).toBeVisible();
+ await expect(chat).toBeHidden();
+ await expect(page.getByTestId(AGENTS_HEADER_BUTTON)).toHaveAttribute('aria-pressed', 'false');
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await expect(chat).toBeVisible();
+ expect(await chat.evaluate((element, original) => element === original, chatHandle)).toBe(true);
+});
+
+test('Hide Editor leaves a narrow project intentionally empty until Editor is reopened', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 767);
+ const editor = page.locator(EDITOR_CARD);
+ const chat = page.locator(CHAT_CARD);
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await input.fill('hide editor');
+ const hideEditor = page.getByTestId('command-palette-toggle-editor');
+ await expect(hideEditor).toContainText('Hide Editor');
+ await hideEditor.click();
+
+ await expect(page.locator('[data-nothing-open]')).toBeVisible();
+ await expect(editor).toBeHidden();
+ await expect(chat).toBeHidden();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ await page.reload();
+ await expect(page.locator('[data-nothing-open]')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await page.getByTestId('nothing-open-editor').click();
+ await expect(editor).toBeVisible();
+});
+
+test('the narrow palette labels and hides the visible Chat without changing wide intent', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 767);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await input.fill('agents');
+ const toggle = page.getByTestId('command-palette-toggle-agent-panel');
+ await expect(toggle).toContainText('Hide Agents');
+ await toggle.click();
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+});
+
+test('Hide Editor chooses an already open Chat and respects a later explicit Chat Hide', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ await openChat(page);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+
+ const hideEditor = async () => {
+ await page.keyboard.press('ControlOrMeta+k');
+ await page.locator('[data-slot="command-input"]').fill('hide editor');
+ const command = page.getByTestId('command-palette-toggle-editor');
+ await expect(command).toContainText('Hide Editor');
+ await command.click();
+ };
+
+ await hideEditor();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect(page.locator(EDITOR_CARD)).toBeHidden();
+ await page.keyboard.press('ControlOrMeta+l');
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await hideEditor();
+ await expect(page.locator('[data-nothing-open]')).toBeVisible();
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+});
+
+test('a narrow Chat visit remains eligible after reload when Editor is hidden', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 767);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await page.getByTestId('header-pane-button-editor').click();
+ await page.reload();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(page.getByTestId('web-project-name')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+
+ await page.keyboard.press('ControlOrMeta+k');
+ await page.locator('[data-slot="command-input"]').fill('hide editor');
+ await page.getByTestId('command-palette-toggle-editor').click();
+
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect(page.locator('[data-nothing-open]')).toHaveCount(0);
+});
+
+test('a narrow Chat Hide remains excluded from Editor fallback after reload', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ await openChat(page);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await page.keyboard.press('ControlOrMeta+l');
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await page.reload();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(page.getByTestId('web-project-name')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+
+ await page.keyboard.press('ControlOrMeta+k');
+ await page.locator('[data-slot="command-input"]').fill('hide editor');
+ await page.getByTestId('command-palette-toggle-editor').click();
+
+ await expect(page.locator('[data-nothing-open]')).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+});
+
+test('refresh restores the selected narrow component without changing wide visibility', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 767);
+ const editor = page.locator(EDITOR_CARD);
+ const chat = page.locator(CHAT_CARD);
+ const wideVisibilityBefore = await page.evaluate(() => ({
+ editor: localStorage.getItem('ok-editor-visible-v1'),
+ chat: JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}').agentPanelVisible as
+ | boolean
+ | undefined,
+ }));
+
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(chat).toBeVisible();
+ await expect(editor).toBeHidden();
+ await page.reload();
+
+ await expect(page.getByTestId(AGENTS_HEADER_BUTTON)).toHaveAttribute('aria-pressed', 'true', {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await expect(chat).toBeVisible();
+ await expect(editor).toBeHidden();
+ expect(
+ await page.evaluate(() => ({
+ editor: localStorage.getItem('ok-editor-visible-v1'),
+ chat: JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}')
+ .agentPanelVisible as boolean | undefined,
+ })),
+ ).toEqual(wideVisibilityBefore);
+});
+
+test('refresh preserves an intentional empty narrow workspace', async ({ page, api }) => {
+ await openDoc(page, api, 767);
+ const sessionKey = await page.evaluate(() =>
+ Object.keys(sessionStorage).find((key) => key.startsWith('ok-narrow-workspace-v1:')),
+ );
+ if (sessionKey === undefined) throw new Error('narrow session record was not written');
+ await page.evaluate((key) => {
+ sessionStorage.setItem(key, JSON.stringify({ version: 1, selected: null }));
+ }, sessionKey);
+
+ await page.reload();
+
+ await expect(page.locator('[data-nothing-open]')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(page.locator(EDITOR_CARD)).toBeHidden();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.getByTestId('nothing-open-editor')).toBeVisible();
+});
+
+test('a malformed narrow record falls back to Editor and becomes usable', async ({ page, api }) => {
+ await openDoc(page, api, 767);
+ const sessionKey = await page.evaluate(() =>
+ Object.keys(sessionStorage).find((key) => key.startsWith('ok-narrow-workspace-v1:')),
+ );
+ if (sessionKey === undefined) throw new Error('narrow session record was not written');
+ await page.evaluate((key) => sessionStorage.setItem(key, '{broken'), sessionKey);
+
+ await page.reload();
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect
+ .poll(() =>
+ page.evaluate((key) => {
+ try {
+ return JSON.parse(sessionStorage.getItem(key) ?? '{}');
+ } catch {
+ return {};
+ }
+ }, sessionKey),
+ )
+ .toMatchObject({ version: 1, selected: 'editor' });
+});
+
+test('an unavailable Terminal in the narrow record falls back to Editor', async ({ page, api }) => {
+ await openDoc(page, api, 767);
+ const sessionKey = await page.evaluate(() =>
+ Object.keys(sessionStorage).find((key) => key.startsWith('ok-narrow-workspace-v1:')),
+ );
+ if (sessionKey === undefined) throw new Error('narrow session record was not written');
+ await page.evaluate((key) => {
+ sessionStorage.setItem(key, JSON.stringify({ version: 1, selected: 'terminal' }));
+ }, sessionKey);
+
+ await page.reload();
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(page.locator(TERMINAL_CARD)).toHaveCount(0);
+ await expect
+ .poll(() => page.evaluate((key) => JSON.parse(sessionStorage.getItem(key) ?? '{}'), sessionKey))
+ .toMatchObject({ version: 1, selected: 'editor' });
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+});
+
+test('a narrow workspace remains usable when session storage is unavailable', async ({
+ page,
+ api,
+}) => {
+ await page.addInitScript(() => {
+ Object.defineProperty(window, 'sessionStorage', {
+ configurable: true,
+ get() {
+ throw new DOMException('Storage denied', 'SecurityError');
+ },
+ });
+ });
+ await openDoc(page, api, 767);
+ expect(
+ await page.evaluate(() => {
+ try {
+ sessionStorage.getItem('unavailable-storage-probe');
+ return false;
+ } catch {
+ return true;
+ }
+ }),
+ ).toBe(true);
+ await page.reload();
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+});
+
+test('a second browser tab starts with Editor instead of another tab’s narrow selection', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 767);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ for (const storage of [sessionStorage, localStorage]) {
+ const key = Object.keys(storage).find((item) =>
+ item.startsWith('ok-narrow-workspace-v1:'),
+ );
+ if (key !== undefined) return JSON.parse(storage.getItem(key) ?? '{}');
+ }
+ return null;
+ }),
+ )
+ .toMatchObject({ version: 1, selected: 'agents' });
+
+ const otherTab = await page.context().newPage();
+ try {
+ await otherTab.setViewportSize({ width: 767, height: 800 });
+ await otherTab.goto(new URL(page.url()).origin);
+ await expect(otherTab.locator(EDITOR_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(otherTab.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(otherTab.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ } finally {
+ await otherTab.close();
+ }
+});
+
+test('a new document deep link selects Editor after a narrow Chat visit', async ({ page, api }) => {
+ const source = `narrow-deep-link-source-${test.info().workerIndex}`;
+ const destination = `narrow-deep-link-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: '# Deep link source\n' },
+ { name: destination, markdown: '# Deep link destination\n' },
+ ]);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const key = Object.keys(sessionStorage).find((item) =>
+ item.startsWith('ok-narrow-workspace-v1:'),
+ );
+ return key === undefined ? null : JSON.parse(sessionStorage.getItem(key) ?? '{}');
+ }),
+ )
+ .toMatchObject({ version: 1, selected: 'agents' });
+
+ await page.goto(`${new URL(page.url()).origin}/?deep-link=1#/${destination}`);
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Deep link destination',
+ );
+ await page.reload();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Deep link destination',
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+ await page.goBack();
+ await expect(page).toHaveURL(new RegExp(`#/${source}$`));
+ await expect(page.locator('[data-editor-activity-mount][data-doc-name]').first()).toHaveAttribute(
+ 'data-doc-name',
+ source,
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+ await page.goForward();
+ await expect(page).toHaveURL(new RegExp(`#/${destination}$`));
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Deep link destination',
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+});
+
+test('search and history reveal their documents from narrow Chat', async ({ page, api }) => {
+ const first = `narrow-history-${test.info().workerIndex}`;
+ const second = `narrow-search-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: first, markdown: '# History destination\n' },
+ { name: second, markdown: '# Search destination\n' },
+ ]);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'History destination',
+ );
+ await openChat(page);
+
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await page.locator('[data-slot="command-input"]').fill(second);
+ await page.getByTestId(`command-palette-nav-file-${second}`).click();
+ await expect(page).toHaveURL(new RegExp(`#/${second}$`));
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Search destination',
+ );
+
+ await openChat(page);
+ await page.goBack();
+ await expect(page).toHaveURL(new RegExp(`#/${first}$`));
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'History destination',
+ );
+});
+
+test('a late seeded Chat thread does not replace an explicit document destination', async ({
+ page,
+ context,
+ api,
+ workerServer,
+}) => {
+ const first = `roster-seed-source-${test.info().workerIndex}`;
+ const second = `roster-seed-destination-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: first, markdown: '# Roster source\n' },
+ { name: second, markdown: '# Roster destination\n' },
+ ]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ const heldRoster: string[] = [];
+ const heldCreated: string[] = [];
+ const createRequests: ThreadClientFrame[] = [];
+ let threadSocket: WebSocketRoute | null = null;
+ const getThreadSocket = () => threadSocket;
+ let holdRoster = true;
+ let createdThreadId: string | null = null;
+
+ await page.addInitScript((agentId) => {
+ localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({
+ agents: [{ source: 'custom', id: agentId, name: 'Hidden activity fixture' }],
+ defaultKey: `custom:${agentId}`,
+ }),
+ );
+ }, fixture.agentId);
+ await context.routeWebSocket(/\/collab\/thread$/, (socket) => {
+ threadSocket = socket;
+ const server = socket.connectToServer();
+ socket.onMessage((message) => {
+ if (typeof message === 'string') {
+ const frame = JSON.parse(message) as ThreadClientFrame;
+ if (frame.op === 'create') createRequests.push(frame);
+ }
+ server.send(message);
+ });
+ server.onMessage((message) => {
+ if (typeof message !== 'string') {
+ socket.send(message);
+ return;
+ }
+ const frame = JSON.parse(message) as ThreadServerFrame;
+ if (frame.op === 'threads' && holdRoster) heldRoster.push(message);
+ else if (
+ frame.op === 'created' &&
+ frame.reqId === (createRequests[0]?.op === 'create' ? createRequests[0].reqId : null)
+ ) {
+ heldCreated.push(message);
+ createdThreadId = frame.info.threadId;
+ } else socket.send(message);
+ });
+ });
+
+ try {
+ await fixture.closeThread(fixture.threadId);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await expect.poll(() => heldRoster.length).toBeGreaterThan(0);
+ const roster = JSON.parse(heldRoster[0]) as ThreadServerFrame;
+ expect(roster.op).toBe('threads');
+ if (roster.op === 'threads') expect(roster.threads).toEqual([]);
+ expect(createRequests).toHaveLength(0);
+
+ await openChat(page);
+ expect(createRequests).toHaveLength(0);
+ const deliver = getThreadSocket();
+ if (deliver === null) throw new Error('thread route was not established');
+ holdRoster = false;
+ for (const frame of heldRoster) deliver.send(frame);
+ await expect.poll(() => createRequests.length).toBe(1);
+ await expect.poll(() => heldCreated.length).toBe(1);
+ expect(createRequests[0]).toMatchObject({ agent: { source: 'custom', id: fixture.agentId } });
+
+ await page.evaluate((hash) => {
+ window.location.hash = hash;
+ }, `#/${second}`);
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Roster destination',
+ );
+
+ const editorSurface = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await editorSurface.click();
+ await page.keyboard.press('ControlOrMeta+End');
+ await page.keyboard.type(' typed before restore');
+ for (const frame of heldCreated) deliver.send(frame);
+ if (createdThreadId === null) throw new Error('seeded thread was not created');
+ await expect(page.locator(CHAT_CARD).locator(`[data-tab-id="${createdThreadId}"]`)).toHaveCount(
+ 1,
+ );
+ expect(createRequests).toHaveLength(1);
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(editorSurface).toBeFocused();
+ await page.keyboard.type(' and after');
+ await expect(editorSurface).toContainText('typed before restore and after');
+ } finally {
+ try {
+ if (createdThreadId !== null) await fixture.closeThread(createdThreadId);
+ } finally {
+ await fixture.close();
+ }
+ }
+});
+
+test('an independent same-agent thread reveals Chat after a pending seed loses its socket', async ({
+ page,
+ context,
+ api,
+ workerServer,
+}) => {
+ const source = `same-agent-source-${test.info().workerIndex}`;
+ const destination = `same-agent-destination-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: source, markdown: '# Same-agent source\n' },
+ { name: destination, markdown: '# Same-agent destination\n' },
+ ]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ let socketGeneration = 0;
+ let seedRequestId: string | null = null;
+ const createRequestIds: string[] = [];
+ const browserCreatedThreadIds: string[] = [];
+ let initialRoster: ThreadServerFrame | null = null;
+ let firstSocket: WebSocketRoute | null = null;
+ let reconnectList: { server: WebSocketRoute; message: string } | null = null;
+ let independentThreadId: string | null = null;
+ let observedReconnectRoster: ThreadServerFrame | null = null;
+ const getInitialRoster = () => initialRoster;
+ const getFirstSocket = () => firstSocket;
+ const getReconnectList = () => reconnectList;
+ const getObservedReconnectRoster = () => observedReconnectRoster;
+
+ await page.addInitScript((agentId) => {
+ localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({
+ agents: [{ source: 'custom', id: agentId, name: 'Hidden activity fixture' }],
+ defaultKey: `custom:${agentId}`,
+ }),
+ );
+ }, fixture.agentId);
+ await context.routeWebSocket(/\/collab\/thread$/, (socket) => {
+ const generation = ++socketGeneration;
+ const server = socket.connectToServer();
+ if (generation === 1) firstSocket = socket;
+ socket.onMessage((message) => {
+ if (typeof message !== 'string') {
+ server.send(message);
+ return;
+ }
+ const frame = JSON.parse(message) as ThreadClientFrame;
+ if (frame.op === 'create') {
+ createRequestIds.push(frame.reqId);
+ if (generation === 1 && seedRequestId === null) {
+ seedRequestId = frame.reqId;
+ return;
+ }
+ }
+ if (generation > 1 && frame.op === 'list') {
+ reconnectList = { server, message };
+ return;
+ }
+ server.send(message);
+ });
+ server.onMessage((message) => {
+ if (typeof message === 'string') {
+ const frame = JSON.parse(message) as ThreadServerFrame;
+ if (generation === 1 && frame.op === 'threads' && initialRoster === null)
+ initialRoster = frame;
+ if (generation > 1 && frame.op === 'threads') observedReconnectRoster = frame;
+ if (frame.op === 'created' && createRequestIds.includes(frame.reqId))
+ browserCreatedThreadIds.push(frame.info.threadId);
+ }
+ socket.send(message);
+ });
+ });
+
+ try {
+ await fixture.closeThread(fixture.threadId);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${source}`);
+ await waitForActiveProviderSynced(page);
+ await expect
+ .poll(getInitialRoster, { timeout: BOOT_TIMEOUT_MS })
+ .toMatchObject({ op: 'threads', threads: [] });
+ expect(createRequestIds).toHaveLength(0);
+
+ await openChat(page);
+ await expect.poll(() => seedRequestId).not.toBeNull();
+ expect(createRequestIds).toHaveLength(1);
+ const openedSocket = getFirstSocket();
+ if (openedSocket === null) throw new Error('initial socket was not established');
+ await openedSocket.close();
+ await page.evaluate((hash) => {
+ window.location.hash = hash;
+ }, `#/${destination}`);
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect.poll(() => reconnectList, { timeout: BOOT_TIMEOUT_MS }).not.toBeNull();
+
+ independentThreadId = await fixture.createThread();
+ expect(independentThreadId).not.toBe(fixture.threadId);
+ const roster = getInitialRoster();
+ if (roster?.op !== 'threads') throw new Error('initial roster missing');
+ expect(roster.threads.map((thread) => thread.threadId)).not.toContain(independentThreadId);
+ const heldList = getReconnectList();
+ if (heldList === null) throw new Error('reconnect list was not held');
+ heldList.server.send(heldList.message);
+ await expect
+ .poll(() => observedReconnectRoster, { timeout: BOOT_TIMEOUT_MS })
+ .toMatchObject({ op: 'threads' });
+ const reconnectRoster = getObservedReconnectRoster();
+ if (reconnectRoster?.op !== 'threads') throw new Error('reconnect roster missing');
+ expect(reconnectRoster.threads.map((thread) => thread.threadId)).toContain(independentThreadId);
+ await expect(
+ page.locator(CHAT_CARD).locator(`[data-tab-id="${independentThreadId}"]`),
+ ).toHaveCount(1);
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect(page.getByTestId(AGENTS_HEADER_BUTTON)).toHaveAttribute('aria-pressed', 'true');
+ expect(createRequestIds).toHaveLength(1);
+ } finally {
+ try {
+ for (const threadId of browserCreatedThreadIds) await fixture.closeThread(threadId);
+ if (independentThreadId !== null) await fixture.closeThread(independentThreadId);
+ } finally {
+ await fixture.close();
+ }
+ }
+});
+
+test('a disconnected document destination leaves error recovery and header navigation visible', async ({
+ page,
+ context,
+ api,
+ workerServer,
+}) => {
+ const first = `connected-destination-${test.info().workerIndex}`;
+ const second = `disconnected-destination-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: first, markdown: '# Connected document\n' },
+ { name: second, markdown: '# Disconnected document\n' },
+ ]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ try {
+ await page.addInitScript((agentId) => {
+ localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({
+ agents: [{ source: 'custom', id: agentId, name: 'Hidden activity fixture' }],
+ defaultKey: `custom:${agentId}`,
+ }),
+ );
+ }, fixture.agentId);
+ let disconnectDestination = false;
+ await context.routeWebSocket(/collab/, (socket) => {
+ if (disconnectDestination) {
+ socket.close();
+ return;
+ }
+ socket.connectToServer();
+ });
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await openChat(page);
+ await expect(
+ page.locator(CHAT_CARD).locator(`[data-tab-id="${fixture.threadId}"]`),
+ ).toHaveCount(1);
+ disconnectDestination = true;
+
+ await page.evaluate((hash) => {
+ window.location.hash = hash;
+ }, `#/${second}`);
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ const error = page.locator('[data-slot="document-error-boundary"]');
+ await expect(error).toContainText('Connection dropped', { timeout: BOOT_TIMEOUT_MS });
+ const tryAgain = error.getByRole('button', { name: 'Try again' });
+ await expect(tryAgain).toBeVisible();
+ expect(
+ await tryAgain.evaluate((button) => {
+ const rect = button.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
+ return hit !== null && button.contains(hit);
+ }),
+ ).toBe(true);
+ await expect(page.getByRole('button', { name: 'Search', exact: true })).toBeVisible();
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ const errorHandle = await error.elementHandle();
+ if (errorHandle === null) throw new Error('document recovery did not mount');
+ const editorButton = page.getByTestId('header-pane-button-editor');
+ await editorButton.click();
+ await expect(editorButton).toBeFocused();
+ await expect(editorButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(error.getByRole('button', { name: 'Try again' })).toBeVisible();
+ expect(await error.evaluate((element, original) => element === original, errorHandle)).toBe(
+ true,
+ );
+ } finally {
+ await fixture.close();
+ }
+});
+
+test('a deleted document destination returns to a surviving editor without claiming success', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const first = `deleted-source-${test.info().workerIndex}`;
+ const second = `deleted-destination-${test.info().workerIndex}`;
+ await api.seedDocs([
+ { name: first, markdown: '# Existing source\n' },
+ { name: second, markdown: '# Existing destination\n' },
+ ]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ try {
+ await page.addInitScript((agentId) => {
+ localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({
+ agents: [{ source: 'custom', id: agentId, name: 'Hidden activity fixture' }],
+ defaultKey: `custom:${agentId}`,
+ }),
+ );
+ }, fixture.agentId);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await openChat(page);
+ await expect(
+ page.locator(CHAT_CARD).locator(`[data-tab-id="${fixture.threadId}"]`),
+ ).toHaveCount(1);
+
+ const deletion = await fetch(`${workerServer.baseURL}/api/delete-path`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ kind: 'file', path: second }),
+ });
+ expect(deletion.ok).toBe(true);
+ await page.evaluate((hash) => {
+ window.location.hash = hash;
+ }, `#/${second}`);
+
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'Existing source',
+ );
+ await expect(page).toHaveURL(new RegExp(`#/${first}$`));
+ await expect(page.getByRole('button', { name: `${second}.md`, exact: true })).toHaveCount(0);
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(page.getByRole('button', { name: 'Search', exact: true })).toBeVisible();
+ } finally {
+ await fixture.close();
+ }
+});
+
+test('the side panel names its dividers and keeps the current outline heading readable in every theme', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ if ((await toggle.getAttribute('aria-expanded')) === 'false') await toggle.click();
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect(page.getByRole('separator', { name: 'Resize document panel' })).toHaveAttribute(
+ 'aria-controls',
+ 'doc-panel',
+ );
+
+ const current = page.locator('#doc-panel [aria-current="location"]').first();
+ await expect(current).toBeVisible();
+ for (const theme of [
+ 'dracula',
+ 'catppuccin-frappe',
+ 'catppuccin-latte',
+ 'monokai',
+ 'gruvbox',
+ 'solarized',
+ ]) {
+ await switchColorThemeAndSettleFade(page, theme);
+ const audit = await new AxeBuilder({ page })
+ .include('#doc-panel [aria-current="location"]')
+ .withRules(['color-contrast'])
+ .analyze();
+ expect(audit.violations, `${theme}: current outline heading contrast`).toEqual([]);
+ }
+});
+
+for (const mode of ['source', 'visual'] as const) {
+ test(`a narrow Chat visit keeps the ${mode} editor mode, caret, scroll, bytes and undo`, async ({
+ page,
+ api,
+ }) => {
+ const docName = `editor-pane-cards-mode-${mode}-${test.info().workerIndex}`;
+ const paragraphs = Array.from({ length: 60 }, (_, index) => `Mode paragraph ${index}`).join(
+ '\n\n',
+ );
+ await api.seedDocs([{ name: docName, markdown: `# Mode ${mode}\n\n${paragraphs}\n` }]);
+ const readDocument = async () => {
+ const response = await page.request.get(
+ `/api/document?docName=${encodeURIComponent(docName)}`,
+ );
+ expect(response.ok()).toBe(true);
+ return ((await response.json()) as { content: string }).content;
+ };
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const seededBytes = await readDocument();
+ const modeToggle = page.getByRole('radio', {
+ name: mode === 'source' ? 'Markdown source' : 'Visual editor',
+ });
+ if (mode === 'source') await modeToggle.click();
+ await expect(modeToggle).toHaveAttribute('aria-checked', 'true');
+ const surface =
+ mode === 'source'
+ ? page.locator(`${EDITOR_CARD} .cm-content`)
+ : page.locator(`${EDITOR_CARD} .ProseMirror:not(.composer-prosemirror)`).first();
+ await expect(surface).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ const lineEndKey = process.platform === 'darwin' ? 'Meta+ArrowRight' : 'End';
+ if (mode === 'source') {
+ await surface.evaluate((element) => {
+ for (let node = element.parentElement; node; node = node.parentElement) {
+ const overflowY = getComputedStyle(node).overflowY;
+ if (overflowY === 'auto' || overflowY === 'scroll') node.scrollTop = node.scrollHeight;
+ }
+ });
+ await surface.getByText('Mode paragraph 59', { exact: true }).click();
+ await page.keyboard.press('End');
+ } else {
+ await surface.locator('p').last().click();
+ await page.keyboard.press(lineEndKey);
+ }
+ await page.keyboard.type(' edited');
+ await expect.poll(readDocument).toContain('Mode paragraph 59 edited');
+ const scrollTopOf = () =>
+ surface.evaluate((element) => {
+ for (let node = element.parentElement; node; node = node.parentElement) {
+ const overflowY = getComputedStyle(node).overflowY;
+ if (
+ (overflowY === 'auto' || overflowY === 'scroll') &&
+ node.scrollHeight > node.clientHeight + 1
+ ) {
+ return node.scrollTop;
+ }
+ }
+ return 0;
+ });
+ const bytesBefore = await readDocument();
+ const scrollBefore = await scrollTopOf();
+ expect(scrollBefore).toBeGreaterThan(0);
+
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect(page.locator(EDITOR_CARD)).toBeHidden();
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+
+ await expect(modeToggle).toHaveAttribute('aria-checked', 'true');
+ await expect(surface).toBeVisible();
+ expect(await readDocument()).toBe(bytesBefore);
+ await expect.poll(scrollTopOf).toBeGreaterThanOrEqual(scrollBefore - 2);
+ expect(await scrollTopOf()).toBeLessThanOrEqual(scrollBefore + 2);
+
+ await surface.focus();
+ const caret = await page.evaluate(() => {
+ const selection = window.getSelection();
+ return {
+ text: selection?.focusNode?.textContent ?? '',
+ offset: selection?.focusOffset ?? -1,
+ collapsed: selection?.isCollapsed ?? false,
+ };
+ });
+ expect(caret.collapsed).toBe(true);
+ expect(caret.text.endsWith('Mode paragraph 59 edited')).toBe(true);
+ expect(caret.offset).toBe(caret.text.length);
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect.poll(readDocument).not.toContain('Mode paragraph 59 edited');
+ expect(await readDocument()).toBe(seededBytes);
+ await page.keyboard.press('ControlOrMeta+Shift+Z');
+ await expect.poll(readDocument).toBe(bytesBefore);
+ });
+}
+
+test('repeated Chat selection, Chat Hide and Hide Editor keep the same thread, draft and session', async ({
+ page,
+ context,
+ api,
+ workerServer,
+}) => {
+ const docName = `narrow-same-session-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Same session\n' }]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ const createRequests: string[] = [];
+ await context.routeWebSocket(/\/collab\/thread$/, (socket) => {
+ const server = socket.connectToServer();
+ socket.onMessage((message) => {
+ if (typeof message === 'string' && (JSON.parse(message) as { op?: string }).op === 'create') {
+ createRequests.push(message);
+ }
+ server.send(message);
+ });
+ server.onMessage((message) => socket.send(message));
+ });
+ try {
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const wideVisibility = () =>
+ page.evaluate(() => ({
+ editor: localStorage.getItem('ok-editor-visible-v1'),
+ chat:
+ (JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}')
+ .agentPanelVisible as boolean | undefined) ?? false,
+ }));
+ const wideBefore = await wideVisibility();
+ const chatButton = page.getByTestId(AGENTS_HEADER_BUTTON);
+ const editorButton = page.getByTestId('header-pane-button-editor');
+ const chat = page.locator(CHAT_CARD);
+ const editor = page.locator(EDITOR_CARD);
+ await chatButton.click();
+ await expect(chat).toBeVisible();
+ await chat.locator(`[role="tab"][data-tab-id="${fixture.threadId}"]`).click();
+ const composer = chat.getByRole('textbox', { name: 'Message Hidden activity fixture' });
+ const threadSurface = composer.locator('xpath=ancestor::*[@data-session-id][1]');
+ await composer.click();
+ await page.keyboard.insertText('Narrow draft');
+ const sessionId = await threadSurface.getAttribute('data-session-id');
+ expect(sessionId).not.toBeNull();
+ const expectSameThread = async () => {
+ await expect(chat).toBeVisible();
+ await expect(editor).toBeHidden();
+ await expect(chatButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(composer).toContainText('Narrow draft');
+ await expect(threadSurface).toHaveAttribute('data-session-id', sessionId ?? '');
+ };
+
+ for (let press = 0; press < 3; press += 1) await chatButton.click();
+ await expectSameThread();
+ await chatButton.focus();
+ await page.keyboard.press('Enter');
+ await page.keyboard.press('Enter');
+ await expectSameThread();
+
+ await page.keyboard.press('ControlOrMeta+k');
+ await page.locator('[data-slot="command-input"]').fill('agents');
+ await page.getByTestId('command-palette-toggle-agent-panel').click();
+ await expect(editor).toBeVisible();
+ await expect(chat).toBeHidden();
+ await chatButton.click();
+ await expectSameThread();
+
+ await composer.click();
+ await page.keyboard.press('ControlOrMeta+l');
+ await expect(editor).toBeVisible();
+ await expect(chat).toBeHidden();
+ await chatButton.click();
+ await expectSameThread();
+
+ await editorButton.click();
+ await expect(editor).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+k');
+ await page.locator('[data-slot="command-input"]').fill('hide editor');
+ await page.getByTestId('command-palette-toggle-editor').click();
+ await expectSameThread();
+
+ expect(createRequests).toEqual([]);
+ expect(await wideVisibility()).toEqual(wideBefore);
+ } finally {
+ await fixture.close();
+ }
+});
+
+test('a narrow Chat visit does not reopen Chat that was explicitly closed on the wide layout', async ({
+ page,
+ api,
+}) => {
+ await openDoc(page, api, 1400);
+ await openChat(page);
+ const chatButton = page.getByTestId(AGENTS_HEADER_BUTTON);
+ await chatButton.click();
+ await expect(chatButton).toHaveAttribute('aria-pressed', 'false');
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+
+ await page.setViewportSize({ width: 767, height: 800 });
+ await chatButton.click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await chatButton.click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(CHAT_CARD)).toBeHidden();
+ await expect(chatButton).toHaveAttribute('aria-pressed', 'false');
+});
+
+test('two tabs keep their own narrow selections across refresh while edits converge', async ({
+ page,
+ api,
+}) => {
+ const docName = await openDoc(page, api, 767);
+ const readSelection = (target: Page) =>
+ target.evaluate(() => {
+ const key = Object.keys(sessionStorage).find((item) =>
+ item.startsWith('ok-narrow-workspace-v1:'),
+ );
+ return key === undefined ? null : JSON.parse(sessionStorage.getItem(key) ?? '{}');
+ });
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect.poll(() => readSelection(page)).toMatchObject({ selected: 'agents' });
+
+ const otherTab = await page.context().newPage();
+ try {
+ await otherTab.route('**/api/acp/catalog', (route) =>
+ route.fulfill({ json: acpCatalogBody([]) }),
+ );
+ await otherTab.setViewportSize({ width: 767, height: 800 });
+ await otherTab.goto(page.url());
+ await waitForActiveProviderSynced(otherTab);
+ await otherTab.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(otherTab.locator(CHAT_CARD)).toBeVisible();
+ await otherTab.getByTestId('header-pane-button-editor').click();
+ await expect(otherTab.locator(EDITOR_CARD)).toBeVisible();
+ await expect.poll(() => readSelection(otherTab)).toMatchObject({ selected: 'editor' });
+ const otherEditor = otherTab.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await otherEditor.click();
+ await otherTab.keyboard.press('ControlOrMeta+End');
+ await otherTab.keyboard.type(' converged from the other tab');
+
+ await page.reload();
+ await expect(page.getByTestId(AGENTS_HEADER_BUTTON)).toHaveAttribute('aria-pressed', 'true', {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await otherTab.reload();
+ await expect(otherTab.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+ await expect(otherTab.locator(CHAT_CARD)).toBeHidden();
+ await expect(otherTab.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'converged from the other tab',
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toContainText(
+ 'converged from the other tab',
+ );
+ await expect(
+ page.locator('[data-editor-activity-mount][data-doc-name]').first(),
+ ).toHaveAttribute('data-doc-name', docName);
+ await expect(otherTab.locator(CHAT_CARD)).toBeHidden();
+ } finally {
+ await otherTab.close();
+ }
+});
+
+test('opening and refreshing below 48rem raises no page error and leaves wide preferences alone', async ({
+ page,
+ api,
+}) => {
+ const errors: string[] = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ const docName = `narrow-fresh-open-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Fresh narrow open\n' }]);
+ for (const width of [767, 360]) {
+ await page.setViewportSize({ width, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const readWideIntent = () => ({
+ editor: localStorage.getItem('ok-editor-visible-v1'),
+ chat:
+ (
+ JSON.parse(localStorage.getItem('ok-agent-session-order-v1') ?? '{}') as {
+ agentPanelVisible?: boolean;
+ }
+ ).agentPanelVisible ?? false,
+ });
+ const wideBefore = await page.evaluate(readWideIntent);
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(TERMINAL_CARD)).toHaveCount(0);
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await page.reload();
+ await expect(page.locator(CHAT_CARD)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await page.getByTestId('header-pane-button-editor').focus();
+ await page.keyboard.press('Enter');
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(page.locator(TERMINAL_CARD)).toHaveCount(0);
+ await noSidewaysScroll(page);
+ expect(await page.evaluate(readWideIntent)).toEqual(wideBefore);
+ }
+ expect(errors).toEqual([]);
+});
+
+test('a second client edit made while narrow Chat is selected appears once and keeps local undo coherent', async ({
+ page,
+ browser,
+ api,
+}) => {
+ const docName = `narrow-remote-edit-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: '# Remote edit\n\nShared line.' }]);
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const editorA = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await editorA.click();
+ await page.keyboard.press('ControlOrMeta+End');
+ await page.keyboard.type(' local edit');
+ await expect(editorA).toContainText('Shared line. local edit');
+ await page.getByTestId(AGENTS_HEADER_BUTTON).click();
+ await expect(page.locator(CHAT_CARD)).toBeVisible();
+ await expect(page.locator(EDITOR_CARD)).toBeHidden();
+
+ const clientB = await browser.newContext();
+ try {
+ const pageB = await clientB.newPage();
+ await pageB.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+ await pageB.setViewportSize({ width: 1400, height: 800 });
+ await pageB.goto(`${new URL(page.url()).origin}/#/${docName}`);
+ await waitForActiveProviderSynced(pageB);
+ const editorB = pageB.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(editorB).toContainText('local edit');
+ await editorB.locator('h1').click();
+ await pageB.keyboard.press('End');
+ await pageB.keyboard.type(' from B');
+ await expect(editorB).toContainText('Remote edit from B');
+
+ const occurrences = (text: string | null, needle: string) =>
+ (text ?? '').split(needle).length - 1;
+ await page.getByTestId('header-pane-button-editor').click();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(editorA).toContainText('Remote edit from B');
+ expect(occurrences(await editorA.textContent(), 'from B')).toBe(1);
+ expect(occurrences(await editorA.textContent(), 'local edit')).toBe(1);
+
+ await editorA.locator('p').last().click();
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect(editorA).not.toContainText('local edit');
+ await expect(editorA).toContainText('Remote edit from B');
+ await expect(editorB).not.toContainText('local edit');
+
+ await page.setViewportSize({ width: 1400, height: 800 });
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(editorA).toContainText('Remote edit from B');
+ expect(occurrences(await editorA.textContent(), 'from B')).toBe(1);
+ await expect(editorA).not.toContainText('local edit');
+ await page.keyboard.press('ControlOrMeta+Shift+z');
+ await expect(editorA).toContainText('Shared line. local edit');
+ await expect(editorB).toContainText('local edit');
+ } finally {
+ await clientB.close();
+ }
+});
diff --git a/packages/app/tests/stress/editor-split-view.e2e.ts b/packages/app/tests/stress/editor-split-view.e2e.ts
index 84f9559a3..11f486467 100644
--- a/packages/app/tests/stress/editor-split-view.e2e.ts
+++ b/packages/app/tests/stress/editor-split-view.e2e.ts
@@ -2,10 +2,11 @@ import { randomUUID } from 'node:crypto';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Locator, Page } from '@playwright/test';
-import { expect, test, waitForActiveProviderSynced } from './_helpers';
+import { afterEditorFocusSync, expect, test, waitForActiveProviderSynced } from './_helpers';
const WIDE_VIEWPORT = { width: 2400, height: 900 } as const;
const MIN_EDITOR_PANE_WIDTH = 300;
+const LINE_END_KEY = process.platform === 'darwin' ? 'Meta+ArrowRight' : 'End';
function testId(): string {
return randomUUID().slice(0, 8);
@@ -178,6 +179,37 @@ function editorForDoc(page: Page, docName: string): Locator {
.locator('.ProseMirror:not(.composer-prosemirror)');
}
+async function activeCaret(page: Page): Promise<{
+ from: number;
+ to: number;
+ fromOffset: number;
+ toOffset: number;
+ paragraph: string;
+ domText: string;
+ domOffset: number;
+ domSelectedText: string;
+ domWithinEditor: boolean;
+} | null> {
+ return page.evaluate(() => {
+ const editor = window.__activeEditor;
+ if (!editor) return null;
+ const selection = editor.state.selection;
+ const domSelection = window.getSelection();
+ const domNode = domSelection?.anchorNode;
+ return {
+ from: selection.from,
+ to: selection.to,
+ fromOffset: selection.$from.parentOffset,
+ toOffset: selection.$to.parentOffset,
+ paragraph: selection.$from.parent.textContent,
+ domText: domNode?.textContent ?? '',
+ domOffset: domSelection?.anchorOffset ?? -1,
+ domSelectedText: domSelection?.toString() ?? '',
+ domWithinEditor: Boolean(domNode && editor.view.dom.contains(domNode)),
+ };
+ });
+}
+
function sourceEditorForDoc(page: Page, docName: string): Locator {
return page
.locator(`[data-editor-activity-mount][data-doc-name="${docName}"]`)
@@ -289,6 +321,117 @@ test.describe('vertical editor splits', () => {
writeFileSync(join(workerServer.contentDir, '.ok', 'config.yml'), '', 'utf-8');
});
+ test('narrow editor selects one live group and restores the split', async ({ page, api }) => {
+ const suffix = testId();
+ const first = `group-first-${suffix}`;
+ const second = `group-second-${suffix}`;
+ await api.seedDocs([
+ { name: first, markdown: '# First group' },
+ { name: second, markdown: '# Second group' },
+ ]);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await paneTabs(page).first().getByTestId('editor-new-tab-button').click();
+ await openDocFromSidebar(page, second);
+ const [firstPaneId] = await paneIds(page);
+ expect(firstPaneId).toBeTruthy();
+ if (!firstPaneId) return;
+ await dragTabToPaneEdge(page, tabInPane(page, firstPaneId, second), firstPaneId, 'right');
+ await expect(paneTabs(page)).toHaveCount(2);
+ const ids = await paneIds(page);
+
+ await page.setViewportSize({ width: 767, height: 800 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ await expect(selector).toBeVisible();
+ await expect(paneRoot(page, ids[1])).toBeVisible();
+ await expect(paneRoot(page, ids[0])).toBeHidden();
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 1' }).click();
+ await expect(paneRoot(page, ids[0])).toBeVisible();
+ await expect(paneRoot(page, ids[1])).toBeHidden();
+ await expect(tabInPane(page, ids[0], first)).toBeFocused();
+ await expect(
+ page.locator(`[data-editor-pane-panel]:not([data-editor-pane-selected])`),
+ ).toHaveAttribute('inert', '');
+ await expect(editorForDoc(page, first)).toBeVisible();
+
+ await selector.focus();
+ await page.keyboard.press('Enter');
+ await expect(page.getByRole('option', { name: 'Pane 2' })).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await expect(page.getByRole('option', { name: 'Pane 2' })).toHaveAttribute(
+ 'data-highlighted',
+ '',
+ );
+ await page.keyboard.press('Enter');
+ await expect(paneRoot(page, ids[1])).toBeVisible();
+ await expect(tabInPane(page, ids[1], second)).toBeFocused();
+
+ await page.setViewportSize({ width: 320, height: 700 });
+ await expect(selector).toBeVisible();
+ await expect(paneRoot(page, ids[1])).toBeVisible();
+ const narrowGeometry = await page.evaluate(() => ({
+ viewport: document.documentElement.clientWidth,
+ page: document.documentElement.scrollWidth,
+ editor: document.querySelector('[data-editor-workspace]')?.getBoundingClientRect().width,
+ }));
+ expect(narrowGeometry.viewport).toBe(320);
+ expect(narrowGeometry.page).toBeLessThanOrEqual(narrowGeometry.viewport + 1);
+ expect(narrowGeometry.editor).toBeGreaterThan(0);
+
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await expect(paneRoot(page, ids[0])).toBeVisible();
+ await expect(paneRoot(page, ids[1])).toBeVisible();
+ expect(await paneIds(page)).toEqual(ids);
+ });
+
+ test('splitting a tab while projected selects the new group without removing others', async ({
+ page,
+ api,
+ }) => {
+ const suffix = testId();
+ const docs = ['first', 'second', 'third'].map((label) => ({
+ name: `projected-split-${label}-${suffix}`,
+ markdown: `# ${label}`,
+ }));
+ await api.seedDocs(docs);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${docs[0].name}`);
+ await waitForActiveProviderSynced(page);
+ for (const doc of docs.slice(1)) {
+ await paneTabs(page).first().getByTestId('editor-new-tab-button').click();
+ await openDocFromSidebar(page, doc.name);
+ }
+ const [firstPaneId] = await paneIds(page);
+ expect(firstPaneId).toBeTruthy();
+ if (!firstPaneId) return;
+ await dragTabToPaneEdge(page, tabInPane(page, firstPaneId, docs[1].name), firstPaneId, 'right');
+ await expect(paneTabs(page)).toHaveCount(2);
+
+ await page.setViewportSize({ width: 767, height: 800 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ await expect(selector).toBeVisible();
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 1' }).click();
+ await tabInPane(page, firstPaneId, docs[2].name).click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-split-right').click();
+ await expect(selector).toBeVisible();
+ await selector.click();
+ await expect(page.getByRole('option')).toHaveCount(3);
+ await expect(page.getByRole('option', { name: 'Pane 2' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await page.keyboard.press('Escape');
+ await expect(page.locator('section[data-editor-pane-id]:visible')).toHaveCount(1);
+ await expect(editorForDoc(page, docs[2].name)).toBeVisible();
+
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await expect(paneTabs(page)).toHaveCount(3);
+ for (const doc of docs) await expect(editorForDoc(page, doc.name)).toBeVisible();
+ });
+
test('pointer edge splits create four live, isolated editors and restore their layout', async ({
page,
api,
@@ -296,7 +439,7 @@ test.describe('vertical editor splits', () => {
const suffix = testId();
const docs = ['alpha', 'bravo', 'charlie', 'delta'].map((label) => ({
name: `split-${label}-${suffix}`,
- markdown: `# ${label}-${suffix}\n\n${label} body`,
+ markdown: `# ${label}-${suffix}\n\n${label} body\n\n${Array.from({ length: 70 }, (_, index) => `${label} paragraph ${index}`).join('\n\n')}`,
}));
await api.seedDocs(docs);
await page.setViewportSize(WIDE_VIEWPORT);
@@ -341,9 +484,11 @@ test.describe('vertical editor splits', () => {
const uniqueToken = `isolated-${suffix}`;
const editedDoc = docs[1];
await editorForDoc(page, editedDoc.name).locator('p').last().click();
- await page.keyboard.press('End');
+ await page.keyboard.press(LINE_END_KEY);
await page.keyboard.type(` ${uniqueToken}`);
- await expect.poll(() => readDocument(page, editedDoc.name)).toContain(uniqueToken);
+ await expect
+ .poll(() => readDocument(page, editedDoc.name))
+ .toContain(`bravo paragraph 69 ${uniqueToken}`);
for (const other of docs.filter((doc) => doc.name !== editedDoc.name)) {
await expect.poll(() => readDocument(page, other.name)).not.toContain(uniqueToken);
}
@@ -398,23 +543,325 @@ test.describe('vertical editor splits', () => {
)
.toBe(4);
+ const readSavedSizes = () =>
+ page.evaluate(() => {
+ const raw = localStorage.getItem(`ok-editor-tabs-v1:${window.location.origin}`);
+ if (!raw) throw new Error('no persisted editor session');
+ return (JSON.parse(raw) as { panes: Array<{ id: string; size: number }> }).panes.map(
+ ({ id, size }) => ({ id, size }),
+ );
+ });
+ const savedSizesBeforeReload = await readSavedSizes();
+ expect(savedSizesBeforeReload).toEqual(
+ splitPaneIds.map((id) => ({ id, size: expect.any(Number) })),
+ );
+
await page.reload();
await waitForActiveProviderSynced(page);
await expect(paneTabs(page)).toHaveCount(4);
+ expect(await paneIds(page)).toEqual(splitPaneIds);
await expectHeaderGroupsAlignedWithPanes(page);
const widthsAfterReload = await paneWidths(page);
- expect(Math.abs(widthsAfterReload[0] - widthsAfterResize[0])).toBeLessThan(40);
+ for (const [index, width] of widthsAfterReload.entries()) {
+ expect(Math.abs(width - widthsAfterResize[index])).toBeLessThan(40);
+ }
await expect.poll(() => windowHash(page)).toContain(editedDoc.name);
for (const doc of docs) {
await expect.poll(() => portalGeneration(page, doc.name)).not.toBe('absent');
}
- await page.setViewportSize({ width: 1200, height: 800 });
- await page.locator('[data-editor-workspace]').evaluate((workspace) => {
- workspace.scrollLeft = 96;
- workspace.dispatchEvent(new Event('scroll'));
+ const generationsAfterReload = Object.fromEntries(
+ await Promise.all(
+ docs.map(async (doc) => [doc.name, await portalGeneration(page, doc.name)] as const),
+ ),
+ );
+ const savedSizes = await readSavedSizes();
+ expect(savedSizes).toEqual(savedSizesBeforeReload);
+ const requestedScrollTops = docs.map((_, index) => 140 * (index + 1));
+ const scrollContainerForDoc = (docName: string) =>
+ page
+ .locator(`[data-editor-activity-mount][data-doc-name="${docName}"]`)
+ .getByTestId('editor-scroll-container');
+ const scrollState = (docName: string) =>
+ scrollContainerForDoc(docName).evaluate((element) => {
+ const readingLine = element.getBoundingClientRect().top + 100;
+ const paragraphs = Array.from(element.querySelectorAll('.ProseMirror p'));
+ return {
+ top: element.scrollTop,
+ max: element.scrollHeight - element.clientHeight,
+ firstVisibleParagraph: paragraphs.findIndex(
+ (paragraph) => paragraph.getBoundingClientRect().bottom > readingLine,
+ ),
+ };
+ });
+ const expectScrollTop = async (docName: string, requestedTop: number, tolerance: number) => {
+ await expect
+ .poll(async () => {
+ const state = await scrollState(docName);
+ expect(state.max).toBeGreaterThan(requestedTop + 50);
+ return Math.abs(state.top - requestedTop);
+ })
+ .toBeLessThanOrEqual(tolerance);
+ };
+ const firstVisibleParagraphs: number[] = [];
+ for (const [index, doc] of docs.entries()) {
+ await scrollContainerForDoc(doc.name).evaluate(
+ (element, top) => element.scrollTo({ top, behavior: 'instant' }),
+ requestedScrollTops[index],
+ );
+ await expectScrollTop(doc.name, requestedScrollTops[index], 2);
+ const state = await scrollState(doc.name);
+ expect(state.firstVisibleParagraph).toBeGreaterThan(0);
+ firstVisibleParagraphs.push(state.firstVisibleParagraph);
+ }
+ expect(new Set(firstVisibleParagraphs).size).toBe(docs.length);
+ const charlieAnchor = () =>
+ scrollContainerForDoc(docs[2].name).evaluate((element, index) => {
+ const paragraph = element.querySelectorAll('.ProseMirror p')[index];
+ const node = paragraph?.firstChild;
+ if (!paragraph || !node || node.nodeType !== Node.TEXT_NODE) {
+ throw new Error('the reading anchor is missing');
+ }
+ const range = document.createRange();
+ range.setStart(node, 8);
+ range.setEnd(node, 9);
+ const port = element.getBoundingClientRect();
+ const block = paragraph.getBoundingClientRect();
+ return {
+ text: node.textContent,
+ glyphTop: range.getBoundingClientRect().top - port.top,
+ blockTop: block.top - port.top,
+ blockHeight: block.height,
+ scrollTop: element.scrollTop,
+ scrollMax: element.scrollHeight - element.clientHeight,
+ portWidth: port.width,
+ };
+ }, firstVisibleParagraphs[2]);
+ const initialCharlieAnchor = await charlieAnchor();
+ const expectCharlieAnchor = async () => {
+ const current = await charlieAnchor();
+ expect(current.text).toBe(initialCharlieAnchor.text);
+ expect(
+ Math.abs(current.glyphTop - initialCharlieAnchor.glyphTop),
+ JSON.stringify({ initial: initialCharlieAnchor, current }),
+ ).toBeLessThanOrEqual(4);
+ };
+
+ await page.setViewportSize({ width: 767, height: 800 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ await expect(selector).toBeVisible();
+ await expect(page.locator('section[data-editor-pane-id]:visible')).toHaveCount(1);
+ for (const [index, doc] of docs.entries()) {
+ await expectScrollTop(doc.name, requestedScrollTops[index], 50);
+ }
+ await expectCharlieAnchor();
+ for (const [index, paneId] of splitPaneIds.entries()) {
+ await selector.click();
+ await expect(page.getByRole('option')).toHaveCount(4);
+ if (index === 0) {
+ await expectScrollTop(docs[0].name, requestedScrollTops[0], 50);
+ }
+ await page.getByRole('option', { name: `Pane ${index + 1}` }).click();
+ await expect(paneRoot(page, paneId)).toBeVisible();
+ await expect(editorForDoc(page, docs[index].name)).toBeVisible();
+ await expect(page.locator('section[data-editor-pane-id]:visible')).toHaveCount(1);
+ await expectScrollTop(docs[index].name, requestedScrollTops[index], 50);
+ await expect
+ .poll(async () => (await scrollState(docs[index].name)).firstVisibleParagraph)
+ .toBe(firstVisibleParagraphs[index]);
+ if (index === 2) await expectCharlieAnchor();
+ }
+
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 1' }).click();
+ await expect(paneRoot(page, splitPaneIds[0])).toBeVisible();
+ await selector.focus();
+ await page.keyboard.press('Enter');
+ await expect(page.getByRole('option', { name: 'Pane 2' })).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await expect(page.getByRole('option', { name: 'Pane 2' })).toHaveAttribute(
+ 'data-highlighted',
+ '',
+ );
+ await page.keyboard.press('Enter');
+ await expect(paneRoot(page, splitPaneIds[1])).toBeVisible();
+ await expect(tabInPane(page, splitPaneIds[1], docs[1].name)).toBeFocused();
+ await expect(editorForDoc(page, docs[1].name)).toBeVisible();
+
+ const hiddenDoc = docs[0];
+ const hiddenUpdate = `remote-${suffix}`;
+ await api.writeAsAgent(hiddenDoc.name, `${hiddenDoc.markdown}\n\n${hiddenUpdate}`, {
+ agentId: `split-${suffix}`,
+ agentName: 'Split test',
});
+ await expect.poll(() => readDocument(page, hiddenDoc.name)).toContain(hiddenUpdate);
+ await expect.poll(() => readDocument(page, hiddenDoc.name)).toContain('alpha paragraph 69');
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 1' }).click();
+ await expect(editorForDoc(page, hiddenDoc.name)).toContainText(hiddenUpdate);
+ await expectScrollTop(hiddenDoc.name, requestedScrollTops[0], 50);
+ await expect
+ .poll(async () => (await scrollState(hiddenDoc.name)).firstVisibleParagraph)
+ .toBe(firstVisibleParagraphs[0]);
+ for (const doc of docs) {
+ expect(await portalGeneration(page, doc.name)).toBe(generationsAfterReload[doc.name]);
+ }
+
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await expect(selector).toBeHidden();
+ await expect(page.locator('section[data-editor-pane-id]:visible')).toHaveCount(4);
await expectHeaderGroupsAlignedWithPanes(page);
+ expect(await paneIds(page)).toEqual(splitPaneIds);
+ const restoredSizes = await readSavedSizes();
+ expect(restoredSizes).toEqual(savedSizes);
+ for (const [index, doc] of docs.entries()) {
+ await expectScrollTop(doc.name, requestedScrollTops[index], 50);
+ await expect
+ .poll(async () => (await scrollState(doc.name)).firstVisibleParagraph)
+ .toBe(firstVisibleParagraphs[index]);
+ }
+ await expectCharlieAnchor();
+
+ await page.setViewportSize({ width: 1200, height: 800 });
+ await expect(selector).toBeVisible();
+ await expect(page.locator('section[data-editor-pane-id]:visible')).toHaveCount(1);
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 2' }).click();
+ await expect(editorForDoc(page, editedDoc.name)).toBeVisible();
+ const bareEndParagraph = `bravo paragraph 69 ${uniqueToken}`;
+ const bareEndToken = `bare-end-${suffix}`;
+ const bareEndBaseline = await readDocument(page, editedDoc.name);
+ const bravoParagraph = editorForDoc(page, editedDoc.name)
+ .locator('p')
+ .filter({ hasText: 'bravo paragraph 69' });
+ await bravoParagraph.click();
+ await expect(editorForDoc(page, editedDoc.name)).toBeFocused();
+ await page.keyboard.press('End');
+ await page.keyboard.type(bareEndToken);
+ const readBareEndLine = async () =>
+ (await readDocument(page, editedDoc.name)).split('\n').filter(Boolean).at(-1);
+ await expect.poll(readBareEndLine).toContain(bareEndToken);
+ const persistedLine = await readBareEndLine();
+ const localLine = (await bravoParagraph.textContent())?.replace(/\u00a0/g, ' ');
+ expect(persistedLine?.split(bareEndToken)).toHaveLength(2);
+ expect(localLine?.split(bareEndToken)).toHaveLength(2);
+ expect(persistedLine?.replace(bareEndToken, '')).toBe(bareEndParagraph);
+ expect(localLine?.replace(bareEndToken, '')).toBe(bareEndParagraph);
+ for (const other of docs.filter((doc) => doc.name !== editedDoc.name)) {
+ await expect.poll(() => readDocument(page, other.name)).not.toContain(bareEndToken);
+ }
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect
+ .poll(async () => (await readDocument(page, editedDoc.name)).replace(/\n$/, ''))
+ .toBe(bareEndBaseline.replace(/\n$/, ''));
+ await bravoParagraph.click();
+ const projectedEdit = `projected-${suffix}`;
+ expect(await readDocument(page, editedDoc.name)).not.toContain(projectedEdit);
+ await page.keyboard.press(LINE_END_KEY);
+ await page.keyboard.type(projectedEdit);
+ await expect
+ .poll(() => readDocument(page, editedDoc.name))
+ .toContain(`bravo paragraph 69 ${uniqueToken}${projectedEdit}`);
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect.poll(() => readDocument(page, editedDoc.name)).not.toContain(projectedEdit);
+
+ const groupLabels = ['alpha', 'bravo', 'charlie', 'delta'];
+ const groupTokens = docs.map((_, index) => ` group-${index}-${suffix}`);
+ const baselines = await Promise.all(docs.map((doc) => readDocument(page, doc.name)));
+ const carets = [];
+ for (const [index, doc] of docs.entries()) {
+ await selector.click();
+ await page.getByRole('option', { name: `Pane ${index + 1}` }).click();
+ const paragraph = editorForDoc(page, doc.name)
+ .locator('p')
+ .filter({ hasText: `${groupLabels[index]} paragraph 69` });
+ const seededParagraph = `${groupLabels[index]} paragraph 69${index === 1 ? ` ${uniqueToken}` : ''}`;
+ await expect(paragraph).toHaveText(seededParagraph);
+ await paragraph.click();
+ await afterEditorFocusSync(page);
+ await page.keyboard.press(LINE_END_KEY);
+ const initialCaret = await activeCaret(page);
+ expect(initialCaret).toMatchObject({
+ paragraph: seededParagraph,
+ domText: seededParagraph,
+ domOffset: seededParagraph.length,
+ domSelectedText: '',
+ domWithinEditor: true,
+ });
+ expect(initialCaret?.from).toBe(initialCaret?.to);
+ await page.keyboard.type(groupTokens[index]);
+ const expectedParagraph = `${seededParagraph}${groupTokens[index]}`;
+ await expect.poll(() => readDocument(page, doc.name)).toContain(expectedParagraph);
+ await expect.poll(async () => (await activeCaret(page))?.paragraph).toBe(expectedParagraph);
+ const caret = await activeCaret(page);
+ expect(caret).not.toBeNull();
+ expect(caret?.from).toBe(caret?.to);
+ expect(caret).toMatchObject({
+ fromOffset: expectedParagraph.length,
+ toOffset: expectedParagraph.length,
+ paragraph: expectedParagraph,
+ domText: expectedParagraph,
+ domOffset: expectedParagraph.length,
+ domSelectedText: '',
+ });
+ expect(caret?.domWithinEditor).toBe(true);
+ carets.push(caret);
+ }
+
+ for (const [index, doc] of docs.entries()) {
+ await selector.click();
+ await page.getByRole('option', { name: `Pane ${index + 1}` }).click();
+ await editorForDoc(page, doc.name).focus();
+ await expect.poll(() => activeCaret(page)).toEqual(carets[index]);
+ }
+
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 2' }).click();
+ await editorForDoc(page, editedDoc.name).focus();
+ await afterEditorFocusSync(page);
+ await expect.poll(() => activeCaret(page)).toEqual(carets[1]);
+ const bravoCaret = carets[1];
+ if (!bravoCaret) throw new Error('the Bravo caret was not captured');
+ const selectedSuffix = groupTokens[1].slice(-1);
+ await page.keyboard.press('Shift+ArrowLeft');
+ await expect
+ .poll(() => activeCaret(page))
+ .toMatchObject({
+ fromOffset: bravoCaret.toOffset - selectedSuffix.length,
+ toOffset: bravoCaret.toOffset,
+ paragraph: bravoCaret.paragraph,
+ domSelectedText: selectedSuffix,
+ domWithinEditor: true,
+ });
+ const selectedRange = await activeCaret(page);
+ expect(selectedRange?.from).toBeLessThan(selectedRange?.to ?? 0);
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 1' }).click();
+ await selector.click();
+ await page.getByRole('option', { name: 'Pane 2' }).click();
+ await editorForDoc(page, editedDoc.name).focus();
+ await expect.poll(() => activeCaret(page)).toEqual(selectedRange);
+
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await expect(page.locator('section[data-editor-pane-id]:visible')).toHaveCount(4);
+ for (const [index, doc] of docs.entries()) {
+ await tabInPane(page, splitPaneIds[index], doc.name).click();
+ await editorForDoc(page, doc.name).focus();
+ await expect
+ .poll(() => activeCaret(page))
+ .toEqual(index === 1 ? selectedRange : carets[index]);
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect
+ .poll(async () => (await readDocument(page, doc.name)).replace(/\n$/, ''))
+ .toBe(baselines[index].replace(/\n$/, ''));
+ for (const [otherIndex, other] of docs.entries()) {
+ if (otherIndex > index) {
+ await expect
+ .poll(() => readDocument(page, other.name))
+ .toContain(groupTokens[otherIndex]);
+ }
+ }
+ }
});
test('diagonal pointer movement keeps the dragged tab visible before an edge split', async ({
@@ -472,7 +919,7 @@ test.describe('vertical editor splits', () => {
api,
}) => {
const suffix = testId();
- const docs = Array.from({ length: 6 }, (_, index) => ({
+ const docs = Array.from({ length: 8 }, (_, index) => ({
name: `shrink-tab-${index}-${suffix}`,
markdown: `# Shrink tab ${index}`,
}));
@@ -767,6 +1214,68 @@ test.describe('vertical editor splits', () => {
const totalWidth = widths.reduce((sum, width) => sum + width, 0);
expect(smallest).toBeGreaterThan((Math.min(...skewed) / 100) * totalWidth + 1);
});
+
+ test.describe('touch group selection', () => {
+ test.use({ hasTouch: true, viewport: { width: 390, height: 700 } });
+
+ test('touch can select and close a projected group without restoring its document', async ({
+ page,
+ api,
+ }) => {
+ const suffix = testId();
+ const first = `touch-group-first-${suffix}`;
+ const second = `touch-group-second-${suffix}`;
+ await api.seedDocs([
+ { name: first, markdown: '# First group\n\nFirst body' },
+ { name: second, markdown: '# Second group\n\nSecond body' },
+ ]);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await paneTabs(page).first().getByTestId('editor-new-tab-button').click();
+ await openDocFromSidebar(page, second);
+ const [firstPaneId] = await paneIds(page);
+ expect(firstPaneId).toBeTruthy();
+ if (!firstPaneId) return;
+ await dragTabToPaneEdge(page, tabInPane(page, firstPaneId, second), firstPaneId, 'right');
+ await expect(paneTabs(page)).toHaveCount(2);
+ const [firstId, secondId] = await paneIds(page);
+
+ await page.setViewportSize({ width: 390, height: 700 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ await expect(selector).toBeVisible();
+ await selector.tap();
+ await page.getByRole('option', { name: 'Pane 1' }).tap();
+ await expect(paneRoot(page, firstId)).toBeVisible();
+ await expect(
+ paneRoot(page, secondId).locator('xpath=ancestor::*[@data-editor-pane-panel][1]'),
+ ).toHaveAttribute('inert', '');
+ await expect(editorForDoc(page, first)).toBeVisible();
+
+ await selector.tap();
+ await page.getByRole('option', { name: 'Pane 2' }).tap();
+ await expect(paneRoot(page, secondId)).toBeVisible();
+ await expect(
+ paneRoot(page, firstId).locator('xpath=ancestor::*[@data-editor-pane-panel][1]'),
+ ).toHaveAttribute('inert', '');
+ await expect(editorForDoc(page, second)).toBeVisible();
+ await page
+ .locator(`[data-editor-pane-tabs="${secondId}"]`)
+ .getByTestId('editor-tab-close-button')
+ .tap();
+ await expect(paneTabs(page)).toHaveCount(1);
+ expect(await paneIds(page)).toEqual([firstId]);
+ await expect(editorForDoc(page, first)).toBeVisible();
+ await expect(editorForDoc(page, second)).toHaveCount(0);
+
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ expect(await paneIds(page)).toEqual([firstId]);
+ await expect(editorForDoc(page, first)).toBeVisible();
+ await expect(editorForDoc(page, second)).toHaveCount(0);
+ });
+ });
});
async function windowHash(page: Page): Promise<string> {
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index b898d119f..7f712a4b3 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -8,11 +8,17 @@ export interface InstallMap {
readonly cursor: boolean;
}
+export interface HeldDockState {
+ readonly terminalVisible: boolean;
+ readonly agentPanelVisible: boolean;
+}
+
export interface HandoffMockConfig {
readonly host: 'electron' | 'web';
readonly install: InstallMap;
readonly workerBaseURL: string;
readonly workerContentDir: string;
+ readonly heldDockState?: HeldDockState;
readonly initialConnectionSnapshot?: HostSnapshot;
}
@@ -31,6 +37,7 @@ export interface CapturedHandoff {
readonly workspacePath?: string;
}>;
readonly recordHandoffCalls: ReadonlyArray<Record<string, unknown>>;
+ readonly terminalCreateCalls: ReadonlyArray<Record<string, unknown>>;
}
function connectedAgentSnapshot(): HostSnapshot {
@@ -116,7 +123,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
await page.addInitScript((args) => {
const init = args as HandoffMockInitConfig;
- const { host, install, workerBaseURL, workerContentDir } = init;
+ const { host, install, workerBaseURL, workerContentDir, heldDockState } = init;
interface HandoffApiCall {
target: string;
@@ -129,19 +136,29 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
detectProtocolCalls: string[];
handoffApiCalls: HandoffApiCall[];
recordHandoffCalls: Record<string, unknown>[];
+ terminalCreateCalls: Record<string, unknown>[];
install: { claude: boolean; codex: boolean; cursor: boolean };
fakeTimeOffset: number;
installedAgentsFetchResolved: boolean;
+ dockStateRequests: number;
+ releaseDockState: () => void;
}
+ let releaseDockState = (): void => {};
+ const dockStateReleased = new Promise<void>((resolve) => {
+ releaseDockState = resolve;
+ });
const mocks: HandoffMocksState = {
anchorClicks: [],
openExternalCalls: [],
detectProtocolCalls: [],
handoffApiCalls: [],
recordHandoffCalls: [],
+ terminalCreateCalls: [],
install: { ...install },
fakeTimeOffset: 0,
installedAgentsFetchResolved: false,
+ dockStateRequests: 0,
+ releaseDockState,
};
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
(window as any).__handoffMocks__ = mocks;
@@ -529,7 +546,10 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
collapseAll: (_cb: () => void) => () => {},
},
terminal: {
- create: async () => ({ ok: true as const, ptyId: 'mock-pty' }),
+ create: async (options: Record<string, unknown>) => {
+ mocks.terminalCreateCalls.push({ ...options });
+ return { ok: true as const, ptyId: 'mock-pty' };
+ },
input: () => {},
resize: () => {},
kill: async () => {},
@@ -539,7 +559,14 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
start: async () => ({ ok: true as const, replay: '' }),
setMeta: () => {},
setOrder: () => {},
- getDockState: async () => ({ terminalVisible: false, agentPanelVisible: false }),
+ getDockState: async () => {
+ mocks.dockStateRequests += 1;
+ if (heldDockState === undefined) {
+ return { terminalVisible: false, agentPanelVisible: false };
+ }
+ await dockStateReleased;
+ return { ...heldDockState };
+ },
setDockState: async () => ({ ok: true as const }),
onData: () => () => {},
onExit: () => () => {},
@@ -591,6 +618,7 @@ export async function readCapturedHandoff(page: Page): Promise<CapturedHandoff>
detectProtocolCalls: string[];
handoffApiCalls: { target: string; url: string; workspacePath?: string }[];
recordHandoffCalls: Record<string, unknown>[];
+ terminalCreateCalls: Record<string, unknown>[];
};
return {
anchorClicks: [...mocks.anchorClicks],
@@ -598,6 +626,7 @@ export async function readCapturedHandoff(page: Page): Promise<CapturedHandoff>
detectProtocolCalls: [...mocks.detectProtocolCalls],
handoffApiCalls: mocks.handoffApiCalls.map((c) => ({ ...c })),
recordHandoffCalls: mocks.recordHandoffCalls.map((l) => ({ ...l })),
+ terminalCreateCalls: mocks.terminalCreateCalls.map((call) => ({ ...call })),
};
});
}
@@ -621,6 +650,20 @@ export async function updateWebInstallMap(page: Page, install: InstallMap): Prom
});
}
+export async function releaseHeldDockState(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ // biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
+ (window as any).__handoffMocks__.releaseDockState();
+ });
+}
+
+export async function readDockStateRequests(page: Page): Promise<number> {
+ return await page.evaluate(
+ // biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
+ () => (window as any).__handoffMocks__.dockStateRequests as number,
+ );
+}
+
export async function advanceHandoffFakeTime(page: Page, ms: number): Promise<void> {
await page.evaluate((delta) => {
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
diff --git a/packages/app/tests/stress/fixtures/update-event-overlay.ts b/packages/app/tests/stress/fixtures/update-event-overlay.ts
new file mode 100644
index 000000000..4b09ad088
--- /dev/null
+++ b/packages/app/tests/stress/fixtures/update-event-overlay.ts
@@ -0,0 +1,192 @@
+import type { Page } from '@playwright/test';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+const UPDATE_EVENT_CHANNELS = [
+ 'onUpdateDownloaded',
+ 'onUpdateRelaunching',
+ 'onUpdateFetchingLatest',
+ 'onUpdateRelaunchFailed',
+ 'onWhatsNew',
+ 'onWhatsNewDismissed',
+ 'onUpdateStuckHint',
+ 'onUpdateManualCheck',
+] as const satisfies ReadonlyArray<keyof OkDesktopBridge>;
+
+export type UpdateEventChannel = (typeof UPDATE_EVENT_CHANNELS)[number];
+
+export type UpdateEventPayload<C extends UpdateEventChannel> = Parameters<
+ Parameters<OkDesktopBridge[C]>[0]
+>[0];
+
+export type OnboardingToastPayload = Parameters<
+ Parameters<OkDesktopBridge['onboarding']['onToast']>[0]
+>[0];
+
+export type SchemaIncompatibility = NonNullable<
+ Awaited<ReturnType<OkDesktopBridge['state']['query']>>['schemaIncompatibility']
+>;
+
+export interface UpdateEventOverlayConfig {
+ readonly schemaIncompatibility?: SchemaIncompatibility;
+ readonly freshlyCreated?: boolean;
+}
+
+export type HeldRelaunchOutcome =
+ | { readonly kind: 'resolve' }
+ | { readonly kind: 'reject'; readonly message: string };
+
+type UpdateListener = (info: never) => void;
+type OnboardingToastListener = (payload: OnboardingToastPayload) => void;
+
+interface UpdateEventOverlayState {
+ readonly listeners: Partial<Record<UpdateEventChannel, Set<UpdateListener>>>;
+ readonly onboardingToastListeners: Set<OnboardingToastListener>;
+ relaunchCalls: number;
+ readonly heldRelaunches: Array<{
+ readonly resolve: () => void;
+ readonly reject: (error: Error) => void;
+ }>;
+}
+
+type OverlayWindow = Window & { __okUpdateEventOverlay__?: UpdateEventOverlayState };
+
+interface OverlayInitArgs {
+ readonly channels: readonly UpdateEventChannel[];
+ readonly schemaIncompatibility: SchemaIncompatibility | null;
+ readonly freshlyCreated: boolean;
+}
+
+export async function installUpdateEventOverlay(
+ page: Page,
+ config: UpdateEventOverlayConfig = {},
+): Promise<void> {
+ await page.addInitScript(
+ ({ channels, schemaIncompatibility, freshlyCreated }: OverlayInitArgs) => {
+ const state: UpdateEventOverlayState = {
+ listeners: {},
+ onboardingToastListeners: new Set(),
+ relaunchCalls: 0,
+ heldRelaunches: [],
+ };
+ const overlayWindow = window as OverlayWindow;
+ overlayWindow.__okUpdateEventOverlay__ = state;
+
+ const overlay = (bridge: OkDesktopBridge): void => {
+ for (const channel of channels) {
+ const listeners = new Set<UpdateListener>();
+ state.listeners[channel] = listeners;
+ bridge[channel] = (listener: UpdateListener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ };
+ }
+ bridge.onboarding.onToast = (listener) => {
+ state.onboardingToastListeners.add(listener);
+ return () => {
+ state.onboardingToastListeners.delete(listener);
+ };
+ };
+ bridge.update.relaunchNow = () => {
+ state.relaunchCalls += 1;
+ return new Promise<void>((resolve, reject) => {
+ state.heldRelaunches.push({ resolve, reject });
+ });
+ };
+ if (schemaIncompatibility !== null) {
+ const query = bridge.state.query;
+ bridge.state.query = async () => ({ ...(await query()), schemaIncompatibility });
+ }
+ if (freshlyCreated) {
+ Object.assign(bridge.config, {
+ freshlyCreated: true,
+ } satisfies Partial<OkDesktopBridge['config']>);
+ }
+ };
+
+ let installed: OkDesktopBridge | undefined;
+ Object.defineProperty(overlayWindow, 'okDesktop', {
+ configurable: true,
+ enumerable: true,
+ get: () => installed,
+ set: (bridge: OkDesktopBridge | undefined) => {
+ if (bridge !== undefined) overlay(bridge);
+ installed = bridge;
+ },
+ });
+ },
+ {
+ channels: UPDATE_EVENT_CHANNELS,
+ schemaIncompatibility: config.schemaIncompatibility ?? null,
+ freshlyCreated: config.freshlyCreated ?? false,
+ } satisfies OverlayInitArgs,
+ );
+}
+
+export async function emitUpdateEvent<C extends UpdateEventChannel>(
+ page: Page,
+ channel: C,
+ payload: UpdateEventPayload<C>,
+): Promise<void> {
+ const delivered = await page.evaluate(
+ ({ channel, payload }) => {
+ const state = (window as OverlayWindow).__okUpdateEventOverlay__;
+ if (state === undefined) return -1;
+ const listeners = [...(state.listeners[channel] ?? [])];
+ for (const listener of listeners) listener(payload as never);
+ return listeners.length;
+ },
+ { channel, payload },
+ );
+ if (delivered === -1) {
+ throw new Error('update event overlay: installUpdateEventOverlay did not run in this page');
+ }
+ if (delivered === 0) {
+ throw new Error(
+ `update event overlay: nothing subscribed to ${channel}; install the overlay before the desktop bridge`,
+ );
+ }
+}
+
+export async function emitOnboardingToast(
+ page: Page,
+ payload: OnboardingToastPayload,
+): Promise<void> {
+ const delivered = await page.evaluate((next: OnboardingToastPayload) => {
+ const state = (window as OverlayWindow).__okUpdateEventOverlay__;
+ if (state === undefined) return -1;
+ const listeners = [...state.onboardingToastListeners];
+ for (const listener of listeners) listener(next);
+ return listeners.length;
+ }, payload);
+ if (delivered === -1) {
+ throw new Error('update event overlay: installUpdateEventOverlay did not run in this page');
+ }
+ if (delivered === 0) {
+ throw new Error(
+ 'update event overlay: nothing subscribed to onboarding.onToast; install the overlay before the desktop bridge',
+ );
+ }
+}
+
+export async function readRelaunchCalls(page: Page): Promise<number> {
+ return await page.evaluate(() => {
+ const state = (window as OverlayWindow).__okUpdateEventOverlay__;
+ if (state === undefined) {
+ throw new Error('update event overlay: installUpdateEventOverlay did not run in this page');
+ }
+ return state.relaunchCalls;
+ });
+}
+
+export async function settleHeldRelaunch(page: Page, outcome: HeldRelaunchOutcome): Promise<void> {
+ const settled = await page.evaluate((next: HeldRelaunchOutcome) => {
+ const held = (window as OverlayWindow).__okUpdateEventOverlay__?.heldRelaunches.shift();
+ if (held === undefined) return false;
+ if (next.kind === 'resolve') held.resolve();
+ else held.reject(new Error(next.message));
+ return true;
+ }, outcome);
+ if (!settled) throw new Error('update event overlay: no relaunchNow call is being held');
+}
diff --git a/packages/app/tests/stress/header-pane-buttons.e2e.ts b/packages/app/tests/stress/header-pane-buttons.e2e.ts
new file mode 100644
index 000000000..ddcc77557
--- /dev/null
+++ b/packages/app/tests/stress/header-pane-buttons.e2e.ts
@@ -0,0 +1,1411 @@
+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 {
+ expect,
+ headerPaneButton,
+ openDesktopHeader,
+ presetTerminalPlacement,
+ stubAgentCatalog,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
+import {
+ installHandoffMocks,
+ readCapturedHandoff,
+ readDockStateRequests,
+ releaseHeldDockState,
+} from './fixtures/handoff-mocks';
+
+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 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,
+ },
+ );
+}
+
+async function expectPane(page: Page, pane: Pane, state: PaneState): Promise<void> {
+ if (state === 'shown') {
+ await expect.poll(() => paneExtentPx(page, pane)).toBeGreaterThan(0);
+ } else {
+ await expect.poll(() => paneExtentPx(page, pane)).toBe(0);
+ }
+ await expect(headerPaneButton(page, pane)).toHaveAttribute(
+ 'aria-pressed',
+ String(state === 'shown'),
+ );
+}
+
+async function expectFocusKept(page: Page): Promise<void> {
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const active = document.activeElement;
+ return active === null || active === document.body ? 'lost' : 'kept';
+ }),
+ )
+ .toBe('kept');
+}
+
+async function expectPaneKeepingFocus(page: Page, pane: Pane, state: PaneState): Promise<void> {
+ await expectPane(page, pane, state);
+ await expectFocusKept(page);
+}
+
+async function waitForFocusInPane(page: Page, pane: Pane): Promise<void> {
+ const container =
+ pane === 'agents' ? AGENTS_MOUNT : `${RIGHT_TERMINAL_MOUNT}, ${BOTTOM_TERMINAL_PANEL}`;
+ await expect
+ .poll(
+ () =>
+ page.evaluate((selector) => document.activeElement?.closest(selector) != null, container),
+ { timeout: BOOT_TIMEOUT_MS },
+ )
+ .toBe(true);
+}
+
+async function clickPaneButton(page: Page, pane: Pane, expected: PaneState): Promise<void> {
+ await headerPaneButton(page, pane).click();
+ await expectPaneKeepingFocus(page, pane, expected);
+}
+
+async function bringBackWithOneClick(
+ page: Page,
+ pane: Pane,
+ preferredExtent: number,
+): Promise<void> {
+ await headerPaneButton(page, pane).click();
+ await expectPane(page, pane, 'shown');
+ await expect.poll(() => paneExtentPx(page, pane)).toBeCloseTo(preferredExtent, -1);
+ await waitForFocusInPane(page, pane);
+}
+
+async function focusDocument(page: Page): Promise<void> {
+ const editor = page.locator('.tiptap-editor .ProseMirror').first();
+ await expect(editor).toContainText(DOC_TEXT, { timeout: BOOT_TIMEOUT_MS });
+ await editor.click();
+ await expect(editor).toBeFocused();
+}
+
+async function seedDoc(api: ApiHelpers, slug: string): Promise<string> {
+ const name = `header-pane-${slug}-${test.info().workerIndex}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\n${DOC_TEXT}\n` }]);
+ return name;
+}
+
+async function openWeb(page: Page, api: ApiHelpers, slug: string): Promise<string> {
+ const name = await seedDoc(api, slug);
+ await stubAgentCatalog(page);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(headerPaneButton(page, 'agents')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect(headerPaneButton(page, 'terminal')).toHaveCount(0);
+ await expectPane(page, 'agents', 'hidden');
+ await focusDocument(page);
+ return name;
+}
+
+async function openDesktop(
+ page: Page,
+ api: ApiHelpers,
+ workerServer: WorkerServer,
+ slug: string,
+ {
+ viewport = { width: 1600, height: 900 },
+ host = {},
+ }: { viewport?: { width: number; height: number }; host?: DesktopHeaderHost } = {},
+): Promise<string> {
+ const name = await seedDoc(api, slug);
+ await stubAgentCatalog(page);
+ await page.setViewportSize(viewport);
+ await openDesktopHeader(page, workerServer, name, host);
+ await expect(headerPaneButton(page, 'terminal')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expectPane(page, 'agents', 'hidden');
+ await expectPane(page, 'terminal', 'hidden');
+ await focusDocument(page);
+ return name;
+}
+
+async function runPalette(page: Page, query: string, commandId: string): Promise<void> {
+ await focusDocument(page);
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await expect(input).toBeFocused();
+ await input.fill(query);
+ const row = page.getByTestId(`command-palette-${commandId}`);
+ await expect(row).toBeVisible();
+ await row.click();
+ await expect(page.locator('[data-slot="command-list"]')).toBeHidden();
+}
+
+async function openThread(page: Page, title: string): Promise<void> {
+ await page.waitForFunction(() => Boolean(window.__acpThreadHarness), null, {
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await page.evaluate((threadTitle) => {
+ const harness = window.__acpThreadHarness;
+ if (harness === undefined) throw new Error('ACP thread harness is not installed');
+ harness.openThread({
+ agent: { id: 'header-pane-agent', name: 'Header Pane Agent', source: 'registry' },
+ title: threadTitle,
+ });
+ }, 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');
+ return viewport;
+}
+
+type Rgb = readonly [number, number, number];
+
+interface ToggleLook {
+ readonly icon: Rgb;
+ readonly background: Rgb;
+ readonly outlineStyle: string;
+ readonly outlineWidthPx: number;
+ readonly outlineColor: Rgb;
+ readonly boxShadow: string;
+}
+
+interface ChromiumButton {
+ readonly role: unknown;
+ readonly internalRole: unknown;
+ readonly pressed: unknown;
+}
+
+interface DividerPaint {
+ readonly width: number;
+ readonly height: number;
+ readonly line: Rgb;
+ readonly backdrop: Rgb;
+ readonly fill: readonly [number, number, number, number];
+}
+
+const SHORTCUT_PLATFORMS = [
+ {
+ platform: 'darwin',
+ navigatorPlatform: 'MacIntel',
+ agents: { glyph: '⌘ L', spoken: 'Command L' },
+ terminal: { glyph: '⌘ J', spoken: 'Command J' },
+ },
+ {
+ platform: 'linux',
+ navigatorPlatform: 'Linux x86_64',
+ agents: { glyph: 'Ctrl L', spoken: 'Control L' },
+ terminal: { glyph: 'Ctrl J', spoken: 'Control J' },
+ },
+] as const;
+
+function contrastRatio(first: Rgb, second: Rgb): number {
+ const luminance = (color: Rgb) => {
+ const [red = 0, green = 0, blue = 0] = color.map((channel) => {
+ const normalized = channel / 255;
+ return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
+ };
+ const [lighter, darker] = [luminance(first), luminance(second)].sort((a, b) => b - a);
+ return ((lighter ?? 0) + 0.05) / ((darker ?? 0) + 0.05);
+}
+
+async function readToggleLook(button: Locator): Promise<ToggleLook> {
+ await expect
+ .poll(() => button.evaluate((element) => element.getAnimations({ subtree: true }).length))
+ .toBe(0);
+ return await button.evaluate((element) => {
+ const context = new OffscreenCanvas(1, 1).getContext('2d', { willReadFrequently: true });
+ if (context === null) throw new Error('the page has no color conversion context');
+ const toRgba = (color: string): [number, number, number, number] => {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ const [red = 0, green = 0, blue = 0, alpha = 0] = context.getImageData(0, 0, 1, 1).data;
+ return [red, green, blue, alpha / 255];
+ };
+ const layers: Array<[number, number, number, number]> = [];
+ for (let node: Element | null = element; node !== null; node = node.parentElement) {
+ const layer = toRgba(getComputedStyle(node).backgroundColor);
+ layers.push(layer);
+ if (layer[3] === 1) break;
+ }
+ const base = layers.pop();
+ if (base === undefined || base[3] !== 1) throw new Error('the button has no opaque backdrop');
+ const background = layers.reduceRight<[number, number, number]>(
+ (below, [red, green, blue, alpha]) => [
+ red * alpha + below[0] * (1 - alpha),
+ green * alpha + below[1] * (1 - alpha),
+ blue * alpha + below[2] * (1 - alpha),
+ ],
+ [base[0], base[1], base[2]],
+ );
+ const icon = element.querySelector('svg');
+ if (icon === null) throw new Error('the button has no icon');
+ const style = getComputedStyle(element);
+ const [iconRed, iconGreen, iconBlue] = toRgba(getComputedStyle(icon).color);
+ const [outlineRed, outlineGreen, outlineBlue] = toRgba(style.outlineColor);
+ return {
+ icon: [iconRed, iconGreen, iconBlue],
+ background: background.map(Math.round) as [number, number, number],
+ outlineStyle: style.outlineStyle,
+ outlineWidthPx: Number.parseFloat(style.outlineWidth),
+ outlineColor: [outlineRed, outlineGreen, outlineBlue],
+ boxShadow: style.boxShadow,
+ };
+ });
+}
+
+async function readDividerPaint(page: Page): Promise<DividerPaint> {
+ const divider = page.getByTestId('header-pane-divider');
+ await expect(divider).toBeVisible();
+ const box = await divider.boundingBox();
+ if (box === null) throw new Error('the divider has no layout box');
+ const clip = {
+ x: Math.floor(box.x) - 3,
+ y: Math.floor(box.y + box.height / 2),
+ width: Math.ceil(box.width) + 6,
+ height: 1,
+ };
+ const png = await page.screenshot({ clip, scale: 'css', animations: 'disabled' });
+ const { row, fill } = await divider.evaluate(async (element, base64) => {
+ const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
+ const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/png' }));
+ const context = new OffscreenCanvas(bitmap.width, bitmap.height).getContext('2d', {
+ willReadFrequently: true,
+ });
+ if (context === null) throw new Error('the page has no pixel reading context');
+ context.drawImage(bitmap, 0, 0);
+ const pixels = context.getImageData(0, 0, bitmap.width, 1).data;
+ const row = Array.from({ length: bitmap.width }, (_, column): [number, number, number] => [
+ pixels[column * 4] ?? 0,
+ pixels[column * 4 + 1] ?? 0,
+ pixels[column * 4 + 2] ?? 0,
+ ]);
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = getComputedStyle(element).backgroundColor;
+ context.fillRect(0, 0, 1, 1);
+ const [red = 0, green = 0, blue = 0, alpha = 0] = context.getImageData(0, 0, 1, 1).data;
+ return { row, fill: [red, green, blue, alpha / 255] as [number, number, number, number] };
+ }, png.toString('base64'));
+ const backdrop = row[0];
+ if (backdrop === undefined) throw new Error('the divider screenshot has no pixels');
+ const line = row.reduce(
+ (strongest, pixel) =>
+ contrastRatio(pixel, backdrop) > contrastRatio(strongest, backdrop) ? pixel : strongest,
+ backdrop,
+ );
+ return { width: box.width, height: box.height, line, backdrop, fill };
+}
+
+async function readChromiumHeaderButton(page: Page, name: string): Promise<ChromiumButton> {
+ const cdp = await page.context().newCDPSession(page);
+ try {
+ const { result } = await cdp.send('Runtime.evaluate', {
+ expression: "document.querySelector('header[data-app-header]')",
+ });
+ if (result.objectId === undefined) throw new Error('the app header is missing');
+ const { nodes } = await cdp.send('Accessibility.queryAXTree', {
+ objectId: result.objectId,
+ accessibleName: name,
+ role: 'button',
+ });
+ expect(nodes, `one "${name}" button in Chromium's header tree`).toHaveLength(1);
+ const node = nodes[0];
+ return {
+ role: node?.role?.value,
+ internalRole: node?.chromeRole?.value,
+ pressed: node?.properties?.find((property) => property.name === 'pressed')?.value.value,
+ };
+ } finally {
+ await cdp.detach();
+ }
+}
+
+function resourcesButton(page: Page): Locator {
+ return page
+ .locator('header[data-app-header]')
+ .getByRole('button', { name: 'Resources', exact: true });
+}
+
+async function tabFromResourcesTo(page: Page, pane: Pane | 'editor'): Promise<void> {
+ const tooltipBubbles = page.locator('[data-slot="tooltip-content"]');
+ await page.evaluate(() => {
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ });
+ await expect(tooltipBubbles).toHaveCount(0);
+ await resourcesButton(page).focus();
+ await expect(resourcesButton(page)).toBeFocused();
+ await expect(tooltipBubbles).toHaveCount(1);
+ const stepsAfterResources = { editor: 1, agents: 2, terminal: 3 } as const;
+ for (let step = 0; step < stepsAfterResources[pane]; step += 1) {
+ await page.keyboard.press('Tab');
+ }
+ await expect(headerPaneButton(page, pane)).toBeFocused();
+}
+
+async function expectFocusTooltip(
+ page: Page,
+ pane: Pane,
+ name: string,
+ shortcut: { readonly glyph: string; readonly spoken: string },
+): Promise<void> {
+ const button = headerPaneButton(page, pane);
+ await expect(button).toHaveAttribute('aria-describedby', /.+/);
+ const tooltipId = await button.getAttribute('aria-describedby');
+ const tooltip = page.getByRole('tooltip').and(page.locator(`[id="${tooltipId}"]`));
+ await expect(tooltip).toHaveText(`${name} ${shortcut.glyph}`);
+ const bubble = page.locator('[data-slot="tooltip-content"]').filter({ has: tooltip });
+ await expect(bubble).toBeVisible();
+ await expect(bubble.locator(':scope > kbd')).toHaveText(shortcut.glyph);
+ await expect(bubble.locator(':scope > kbd')).toHaveAttribute('aria-label', shortcut.spoken);
+ await expect(button).toHaveAccessibleDescription(`${name} ${shortcut.spoken}`);
+}
+
+async function movePointerOffHeader(page: Page): Promise<void> {
+ const { width, height } = viewportOf(page);
+ await page.mouse.move(width / 2, height - 40);
+}
+
+test.setTimeout(180_000);
+
+test.describe('the Agents button follows every chat show/hide path on the web', () => {
+ test('narrowing an Editor-only workspace keeps explicitly hidden Chat hidden', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'editor-only-narrow-chat');
+ await clickPaneButton(page, 'agents', 'shown');
+ await clickPaneButton(page, 'agents', 'hidden');
+ await page.setViewportSize({ width: 767, height: 800 });
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expectPane(page, 'agents', 'hidden');
+ });
+
+ test('a wide palette Editor reveal remains selected when narrowing', async ({ page, api }) => {
+ await openWeb(page, api, 'narrow-palette-editor');
+ await clickPaneButton(page, 'agents', 'shown');
+ await runPalette(page, 'editor', 'toggle-editor');
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
+ await expectPane(page, 'agents', 'shown');
+ await headerPaneButton(page, 'agents').focus();
+ await expect(headerPaneButton(page, 'agents')).toBeFocused();
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await expect(input).toBeFocused();
+ await input.fill('editor');
+ const showEditor = page.getByTestId('command-palette-toggle-editor');
+ await expect(showEditor).toContainText('Show Editor');
+ await showEditor.click();
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await page.setViewportSize({ width: 767, height: 800 });
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expectPane(page, 'agents', 'hidden');
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await expectPane(page, 'agents', 'shown');
+ });
+
+ test('palette Show Agents and Hide Agents', async ({ page, api }) => {
+ await openWeb(page, api, 'palette-agents');
+ await runPalette(page, 'agents', 'toggle-agent-panel');
+ await expectPane(page, 'agents', 'shown');
+ await runPalette(page, 'agents', 'toggle-agent-panel');
+ await expectPane(page, 'agents', 'hidden');
+ });
+
+ test('Cmd/Ctrl+L with nothing selected shows and hides chat', async ({ page, api }) => {
+ await openWeb(page, api, 'mod-l');
+ await page.keyboard.press('ControlOrMeta+l');
+ await expectPaneKeepingFocus(page, 'agents', 'shown');
+ await waitForFocusInPane(page, 'agents');
+ await page.keyboard.press('ControlOrMeta+l');
+ await expectPaneKeepingFocus(page, 'agents', 'hidden');
+ });
+
+ test('Shift+Cmd/Ctrl+J reveals chat and leaves an open chat open', async ({ page, api }) => {
+ await openWeb(page, api, 'new-session');
+ const agentSettings = page.getByTestId('settings-dialog');
+ await page.keyboard.press('ControlOrMeta+Shift+j');
+ await expectPaneKeepingFocus(page, 'agents', 'shown');
+ await expect(agentSettings).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(agentSettings).toBeHidden();
+ await focusDocument(page);
+ await page.keyboard.press('ControlOrMeta+Shift+j');
+ await expectPaneKeepingFocus(page, 'agents', 'shown');
+ });
+
+ test('a new live thread reveals chat, and closing the last tab hides it', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'auto-reveal');
+ await openThread(page, 'First header thread');
+ await expectPane(page, 'agents', 'shown');
+ await openThread(page, 'Second header thread');
+ await expectPane(page, 'agents', 'shown');
+ await expect(page.locator(AGENTS_MOUNT).getByRole('tab')).toHaveCount(2);
+ await page.getByRole('button', { name: 'Close Second header thread' }).click();
+ await expectPane(page, 'agents', 'shown');
+ await page.getByRole('button', { name: 'Close First header thread' }).click();
+ await expectPane(page, 'agents', 'hidden');
+ });
+
+ test('closing the last narrow chat thread does not reopen it with the wide layout', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'narrow-close-thread');
+ await openThread(page, 'Narrow close thread');
+ await expectPane(page, 'agents', 'shown');
+ await page.setViewportSize({ width: 767, height: 800 });
+ await headerPaneButton(page, 'agents').click();
+ await expectPane(page, 'agents', 'shown');
+ await page.getByRole('button', { name: 'Close Narrow close thread' }).click();
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await expectPane(page, 'agents', 'hidden');
+ });
+
+ test('sending a comment to the open chat reveals chat', async ({ page, api }) => {
+ const name = await openWeb(page, api, 'comment-send');
+ const created = await page.request.post('/api/comments', {
+ data: { docName: name, quote: 'brown fox', body: 'Is the fox really brown?' },
+ });
+ expect(created.ok()).toBe(true);
+ await openThread(page, 'Comment destination thread');
+ await expectPane(page, 'agents', 'shown');
+ await clickPaneButton(page, 'agents', 'hidden');
+
+ await page.getByRole('tab', { name: 'Comments' }).click();
+ const comments = page.locator('#panel-comments');
+ await expect(comments.getByTestId('thread-comment-body')).toHaveText(
+ 'Is the fox really brown?',
+ { timeout: BOOT_TIMEOUT_MS },
+ );
+ const queued = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === '/api/comment' &&
+ (response.request().postData() ?? '').includes('"queue"'),
+ );
+ await comments.getByRole('checkbox', { name: 'Send this comment' }).click();
+ expect((await queued).ok()).toBe(true);
+ await expect(comments.getByRole('checkbox', { name: "Don't send this comment" })).toBeVisible({
+ timeout: BOOT_TIMEOUT_MS,
+ });
+ await comments.getByRole('button', { name: 'Send to chat' }).click();
+ 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');
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expectPane(page, 'agents', 'shown');
+ await clickPaneButton(page, 'agents', 'hidden');
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expectPane(page, 'agents', 'hidden');
+ });
+});
+
+test.describe('the Terminal button follows every terminal show/hide path on the mocked desktop', () => {
+ test('narrowing keeps Terminal hidden after a wide keyboard Hide', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'narrow-keyboard-terminal-hide');
+ await page.keyboard.press('Control+Backquote');
+ await expectPaneKeepingFocus(page, 'terminal', 'shown');
+ await waitForFocusInPane(page, 'terminal');
+ await page.keyboard.press('Control+Backquote');
+ await expectPaneKeepingFocus(page, 'terminal', 'hidden');
+ await page.setViewportSize({ width: 767, height: 800 });
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expectPane(page, 'terminal', 'hidden');
+ });
+
+ test('narrowing an Editor-only workspace keeps a hidden Terminal hidden', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'editor-only-narrow');
+ await clickPaneButton(page, 'terminal', 'shown');
+ await clickPaneButton(page, 'terminal', 'hidden');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await page.setViewportSize({ width: 767, height: 800 });
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expectPane(page, 'terminal', 'hidden');
+ await expectPane(page, 'agents', 'hidden');
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expectPane(page, 'terminal', 'hidden');
+ });
+
+ test('a narrow terminal visit does not add Terminal to the restored wide layout', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await presetTerminalPlacement(page, 'bottom');
+ await openDesktop(page, api, workerServer, 'narrow-terminal-visit', {
+ viewport: { width: 769, height: 800 },
+ });
+ await clickPaneButton(page, 'agents', 'shown');
+ await page.setViewportSize({ width: 767, height: 800 });
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
+ await expectPane(page, 'agents', 'shown');
+
+ await headerPaneButton(page, 'terminal').click();
+ await expectPane(page, 'terminal', 'shown');
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
+ await expect(page.locator('[data-pane="agents"]')).toBeHidden();
+ await expect(page.locator('[data-pane="terminal"][data-placement="bottom"]')).toBeVisible();
+
+ await page.setViewportSize({ width: 769, height: 800 });
+ 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 page.setViewportSize({ width: 767, height: 800 });
+ await expectPane(page, 'terminal', 'shown');
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
+ });
+
+ test('palette Show Terminal and Hide Terminal', async ({ page, api, workerServer }) => {
+ await openDesktop(page, api, workerServer, 'palette-terminal');
+ await runPalette(page, 'terminal', 'toggle-terminal');
+ await expectPane(page, 'terminal', 'shown');
+ await runPalette(page, 'terminal', 'toggle-terminal');
+ await expectPane(page, 'terminal', 'hidden');
+ });
+
+ test('palette New Terminal shows the terminal and Kill Terminal on the last session hides it', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'new-kill');
+ await runPalette(page, 'new terminal', 'new-terminal');
+ await expectPane(page, 'terminal', 'shown');
+ await runPalette(page, 'new terminal', 'new-terminal');
+ await expectPane(page, 'terminal', 'shown');
+ const sessions = page.getByRole('tab', { name: /^Terminal/ });
+ await expect(sessions).toHaveCount(2);
+ await runPalette(page, 'kill terminal', 'kill-terminal');
+ await expect(sessions).toHaveCount(1);
+ await expectPane(page, 'terminal', 'shown');
+ await runPalette(page, 'kill terminal', 'kill-terminal');
+ await expectPane(page, 'terminal', 'hidden');
+ });
+
+ test('Ctrl+` shows and hides the terminal', async ({ page, api, workerServer }) => {
+ await openDesktop(page, api, workerServer, 'ctrl-backquote');
+ await page.keyboard.press('Control+Backquote');
+ await expectPaneKeepingFocus(page, 'terminal', 'shown');
+ await waitForFocusInPane(page, 'terminal');
+ await page.keyboard.press('Control+Backquote');
+ await expectPaneKeepingFocus(page, 'terminal', 'hidden');
+ });
+
+ for (const placement of ['bottom', 'right'] as const) {
+ test(`closing the last tab hides a ${placement} terminal`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await presetTerminalPlacement(page, placement);
+ await openDesktop(page, api, workerServer, `last-tab-${placement}`);
+ await clickPaneButton(page, 'terminal', 'shown');
+ await page.getByRole('button', { name: /^Close Terminal/ }).click();
+ await expectPane(page, 'terminal', 'hidden');
+ });
+ }
+
+ 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,
+ workerServer,
+ }) => {
+ const name = await openDesktop(page, api, workerServer, 'launch');
+ const docRow = page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${name}.md`, exact: true });
+ for (const before of ['hidden', 'shown'] as const) {
+ await expectPane(page, 'terminal', before);
+ await docRow.click({ button: 'right' });
+ await page.getByRole('menuitem', { name: 'Open with AI' }).click();
+ await page.getByTestId('file-tree-open-in-terminal-claude').click();
+ await expectPane(page, 'terminal', 'shown');
+ await waitForFocusInPane(page, 'terminal');
+ }
+ });
+
+ test('a narrow file action selects Terminal and preserves the wide layout', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = await openDesktop(page, api, workerServer, 'narrow-file-terminal-launch', {
+ viewport: { width: 767, height: 800 },
+ });
+ await page.locator('[data-sidebar="trigger"]').click();
+ const docRow = page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${name}.md`, exact: true });
+ await docRow.click({ button: 'right' });
+ await page.getByRole('menuitem', { name: 'Open with AI' }).click();
+ await page.getByTestId('file-tree-open-in-terminal-claude').click();
+
+ await expectPane(page, 'terminal', 'shown');
+ await expect
+ .poll(async () => (await readCapturedHandoff(page)).terminalCreateCalls.length)
+ .toBe(1);
+ const [terminalLaunch] = (await readCapturedHandoff(page)).terminalCreateCalls;
+ expect(terminalLaunch?.launchCli).toBe('claude');
+ expect(JSON.stringify(terminalLaunch?.launchCommand)).toContain(name);
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
+ await expect(page.locator('[data-pane="agents"]')).toBeHidden();
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'false');
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'false');
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await expectPane(page, 'terminal', 'hidden');
+ });
+
+ test('moving an open terminal between bottom and right keeps the button on', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await presetTerminalPlacement(page, 'bottom');
+ await openDesktop(page, api, workerServer, 'move');
+ await clickPaneButton(page, 'terminal', 'shown');
+ await waitForFocusInPane(page, 'terminal');
+ await expect(page.locator(BOTTOM_TERMINAL_PANEL)).toBeVisible();
+ await runPalette(page, 'move terminal', 'move-terminal');
+ await expect(page.locator(RIGHT_TERMINAL_MOUNT)).toBeVisible();
+ 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 expectPane(page, 'terminal', 'shown');
+ });
+});
+
+test.describe('the Agents button on the mocked desktop', () => {
+ test('the palette and the Agents button toggle chat and keep the button in step', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'desktop-agents');
+ await runPalette(page, 'agents', 'toggle-agent-panel');
+ await expectPane(page, 'agents', 'shown');
+ await clickPaneButton(page, 'agents', 'hidden');
+ await runPalette(page, 'agents', 'toggle-agent-panel');
+ await expectPane(page, 'agents', 'shown');
+ await runPalette(page, 'agents', 'toggle-agent-panel');
+ await expectPane(page, 'agents', 'hidden');
+ await expectPane(page, 'terminal', 'hidden');
+ });
+
+ test('Files yields so right Terminal and Chat remain open with a usable Editor', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await presetTerminalPlacement(page, 'right');
+ await openDesktop(page, api, workerServer, 'fit-rule', {
+ viewport: { width: 1100, height: 800 },
+ });
+ await clickPaneButton(page, 'terminal', 'shown');
+ await headerPaneButton(page, 'agents').click();
+ await expectPaneKeepingFocus(page, 'terminal', 'shown');
+ await expectPane(page, 'agents', 'shown');
+ await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ await expect
+ .poll(() =>
+ page
+ .locator('[data-editor-workspace-column]')
+ .evaluate((element) => element.getBoundingClientRect().width),
+ )
+ .toBeGreaterThanOrEqual(300);
+ });
+
+ test('information yields before a right Terminal is closed when Chat opens', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await presetTerminalPlacement(page, 'right');
+ await openDesktop(page, api, workerServer, 'info-fit-rule', {
+ viewport: { width: 1128, height: 800 },
+ });
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ await filesTrigger.click();
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'false');
+ await page.locator('[data-doc-panel-toggle]').click();
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await clickPaneButton(page, 'terminal', 'shown');
+ await headerPaneButton(page, 'agents').click();
+ await expectPaneKeepingFocus(page, 'terminal', 'shown');
+ await expectPane(page, 'agents', 'shown');
+ await expect(page.locator('#doc-panel')).not.toBeVisible();
+ await expect
+ .poll(() =>
+ page
+ .locator('[data-editor-workspace-column]')
+ .evaluate((element) => element.getBoundingClientRect().width),
+ )
+ .toBeGreaterThanOrEqual(300);
+ });
+});
+
+test('narrow Terminal Hide returns to Editor without opening Terminal in the wide layout', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ await openDesktop(page, api, workerServer, 'narrow-terminal-hide', {
+ viewport: { width: 767, height: 800 },
+ });
+ await headerPaneButton(page, 'terminal').click();
+ await expectPane(page, 'terminal', 'shown');
+ await page.keyboard.press('ControlOrMeta+k');
+ const input = page.locator('[data-slot="command-input"]');
+ await input.fill('terminal');
+ const toggle = page.getByTestId('command-palette-toggle-terminal');
+ await expect(toggle).toContainText('Hide Terminal');
+ await toggle.click();
+
+ await expectPane(page, 'terminal', 'hidden');
+ await expect(headerPaneButton(page, 'editor')).toHaveAttribute('aria-pressed', 'true');
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await expectPane(page, 'terminal', 'hidden');
+});
+
+test.describe('the pane buttons during the desktop restore wait', () => {
+ test('both buttons read off and stay clickable while the saved layout loads, and a click survives the restore', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = await seedDoc(api, 'restore-wait');
+ await stubAgentCatalog(page);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ const restoreTimeouts: string[] = [];
+ page.on('console', (message) => {
+ if (message.text().includes('dock-state restore exceeded')) {
+ restoreTimeouts.push(message.text());
+ }
+ });
+ let contentDir = workerServer.contentDir;
+ try {
+ contentDir = realpathSync(contentDir);
+ } catch {}
+ await installHandoffMocks(page, {
+ host: 'electron',
+ install: { claude: false, codex: false, cursor: false },
+ workerBaseURL: workerServer.baseURL,
+ workerContentDir: contentDir,
+ heldDockState: { terminalVisible: true, agentPanelVisible: false },
+ });
+ await page.goto(`/#/${name}`);
+
+ const agents = headerPaneButton(page, 'agents');
+ const terminal = headerPaneButton(page, 'terminal');
+ await expect(agents).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect.poll(() => readDockStateRequests(page)).toBeGreaterThan(0);
+ await expect(agents).toHaveAttribute('aria-pressed', 'false');
+ await expect(terminal).toHaveAttribute('aria-pressed', 'false');
+ await expect(agents).toBeEnabled();
+ await expect(terminal).toBeEnabled();
+
+ await agents.click();
+ await expect(agents).toHaveAttribute('aria-pressed', 'true');
+ await releaseHeldDockState(page);
+
+ await expectPane(page, 'terminal', 'shown');
+ await expectPane(page, 'agents', 'shown');
+ expect(restoreTimeouts).toEqual([]);
+ });
+
+ test('a narrow user selection survives a late desktop dock restore', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = await seedDoc(api, 'narrow-restore-wait');
+ await stubAgentCatalog(page);
+ await page.setViewportSize({ width: 767, height: 800 });
+ let contentDir = workerServer.contentDir;
+ try {
+ contentDir = realpathSync(contentDir);
+ } catch {}
+ await installHandoffMocks(page, {
+ host: 'electron',
+ install: { claude: false, codex: false, cursor: false },
+ workerBaseURL: workerServer.baseURL,
+ workerContentDir: contentDir,
+ heldDockState: { terminalVisible: true, agentPanelVisible: false },
+ });
+ await page.goto(`/#/${name}`);
+ await expect.poll(() => readDockStateRequests(page)).toBeGreaterThan(0);
+
+ await headerPaneButton(page, 'agents').click();
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'true');
+ await releaseHeldDockState(page);
+
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'true');
+ await expect(headerPaneButton(page, 'terminal')).toHaveAttribute('aria-pressed', 'false');
+ await page.setViewportSize({ width: 769, height: 800 });
+ await expect(headerPaneButton(page, 'terminal')).toHaveAttribute('aria-pressed', 'true');
+ await expect(headerPaneButton(page, 'agents')).toHaveAttribute('aria-pressed', 'false');
+ });
+});
+
+test.describe('the pane buttons for keyboard, screen-reader and high-contrast users on the mocked desktop', () => {
+ for (const shortcuts of SHORTCUT_PLATFORMS) {
+ test(`Tab from Resources reaches Editor, Agents then Terminal, 28px targets whose focus tooltip names the ${shortcuts.platform} shortcut in both states`, async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await page.addInitScript((platform) => {
+ Object.defineProperty(navigator, 'platform', { get: () => platform, configurable: true });
+ }, shortcuts.navigatorPlatform);
+ await openDesktop(page, api, workerServer, `keyboard-${shortcuts.platform}`, {
+ host: { platform: shortcuts.platform },
+ });
+
+ await tabFromResourcesTo(page, 'editor');
+ await page.keyboard.press('Tab');
+ await expect(headerPaneButton(page, 'agents')).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(headerPaneButton(page, 'terminal')).toBeFocused();
+ for (const pane of ['editor', 'agents', 'terminal'] as const) {
+ const box = await headerPaneButton(page, pane).boundingBox();
+ expect(box, `${pane} button bounds`).toMatchObject({ width: 28, height: 28 });
+ }
+
+ const names = { agents: 'Agents', terminal: 'Terminal' } as const;
+ for (const pane of ['agents', 'terminal'] as const) {
+ await tabFromResourcesTo(page, pane);
+ await expect(headerPaneButton(page, pane)).toHaveAttribute('aria-pressed', 'false');
+ await expectFocusTooltip(page, pane, names[pane], shortcuts[pane]);
+ await page.keyboard.press('Enter');
+ await expectPaneKeepingFocus(page, pane, 'shown');
+ await waitForFocusInPane(page, pane);
+ await tabFromResourcesTo(page, pane);
+ await expect(headerPaneButton(page, pane)).toHaveAttribute('aria-pressed', 'true');
+ await expectFocusTooltip(page, pane, names[pane], shortcuts[pane]);
+ }
+ });
+ }
+
+ test("the Panels group and Chromium's accessibility tree expose three toggle buttons whose pressed state follows the panes", async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await openDesktop(page, api, workerServer, 'ax-tree');
+ const group = page.getByRole('group', { name: 'Panels', exact: true });
+ await expect(group).toMatchAriaSnapshot(`
+ - group "Panels":
+ - button "Editor" [pressed]
+ - button "Agents" [pressed=false]
+ - button "Terminal" [pressed=false]
+ `);
+ const plainButton = await readChromiumHeaderButton(page, 'Resources');
+ expect(plainButton.role).toBe('button');
+ expect(plainButton.pressed).toBeUndefined();
+ const agentsBefore = await readChromiumHeaderButton(page, 'Agents');
+ expect(agentsBefore.role).toBe('button');
+ expect(agentsBefore.internalRole).not.toEqual(plainButton.internalRole);
+ expect(agentsBefore.pressed).toBe('false');
+ expect(await readChromiumHeaderButton(page, 'Terminal')).toEqual(agentsBefore);
+
+ await clickPaneButton(page, 'agents', 'shown');
+ await expect(group).toMatchAriaSnapshot(`
+ - group "Panels":
+ - button "Editor" [pressed]
+ - button "Agents" [pressed]
+ - button "Terminal" [pressed=false]
+ `);
+ expect(await readChromiumHeaderButton(page, 'Agents')).toEqual({
+ ...agentsBefore,
+ pressed: 'true',
+ });
+ expect(await readChromiumHeaderButton(page, 'Terminal')).toEqual(agentsBefore);
+
+ await clickPaneButton(page, 'terminal', 'shown');
+ expect(await readChromiumHeaderButton(page, 'Terminal')).toEqual({
+ ...agentsBefore,
+ pressed: 'true',
+ });
+ await clickPaneButton(page, 'agents', 'hidden');
+ expect(await readChromiumHeaderButton(page, 'Agents')).toEqual(agentsBefore);
+
+ const accessibility = await new AxeBuilder({ page })
+ .include('[data-testid="header-pane-buttons"]')
+ .analyze();
+ expect(accessibility.violations).toEqual([]);
+ });
+
+ for (const theme of ['light', 'dark'] as const) {
+ test(`on differs from off in icon and background and never looks like a hovered off button in the ${theme} theme`, async ({
+ page,
+ api,
+ }) => {
+ await page.emulateMedia({ colorScheme: theme });
+ await page.addInitScript((value) => window.localStorage.setItem('ok-theme-v1', value), theme);
+ await openWeb(page, api, `look-${theme}`);
+ await expect(page.locator('html')).toHaveClass(new RegExp(`\\b${theme}\\b`));
+ const agents = headerPaneButton(page, 'agents');
+
+ await movePointerOffHeader(page);
+ const off = await readToggleLook(agents);
+ await agents.hover();
+ const hoveredOff = await readToggleLook(agents);
+ await clickPaneButton(page, 'agents', 'shown');
+ await waitForFocusInPane(page, 'agents');
+ await movePointerOffHeader(page);
+ const on = await readToggleLook(agents);
+
+ expect(on.icon, 'on and off icons differ').not.toEqual(off.icon);
+ expect(on.background, 'on and off backgrounds differ').not.toEqual(off.background);
+ expect(hoveredOff.background).not.toEqual(off.background);
+ expect(hoveredOff.background).not.toEqual(on.background);
+ });
+
+ test(`every plain header button shows a hover background in the ${theme} theme`, async ({
+ page,
+ api,
+ }) => {
+ await page.emulateMedia({ colorScheme: theme });
+ await page.addInitScript((value) => window.localStorage.setItem('ok-theme-v1', value), theme);
+ await openWeb(page, api, `hover-${theme}`);
+ await expect(page.locator('html')).toHaveClass(new RegExp(`\\b${theme}\\b`));
+ const buttons = page.locator(
+ 'header[data-app-header] [data-variant^="ghost"]:not([aria-pressed="true"]):has(svg):visible',
+ );
+ const count = await buttons.count();
+ expect(count, 'header buttons to hover').toBeGreaterThanOrEqual(3);
+ for (let index = 0; index < count; index += 1) {
+ const button = buttons.nth(index);
+ const name = (await button.getAttribute('aria-label')) ?? (await button.innerText());
+ await movePointerOffHeader(page);
+ const off = await readToggleLook(button);
+ await button.hover();
+ const hovered = await readToggleLook(button);
+ expect(
+ contrastRatio(hovered.background, off.background),
+ `${name} hover against the header`,
+ ).toBeGreaterThanOrEqual(1.03);
+ }
+ });
+ }
+
+ test('forced colors and increased contrast outline the on button and leave the off button bare', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'high-contrast');
+ const agents = headerPaneButton(page, 'agents');
+ const readAfterClick = async (state: 'shown' | 'hidden') => {
+ await clickPaneButton(page, 'agents', state);
+ await movePointerOffHeader(page);
+ return await readToggleLook(agents);
+ };
+
+ expect((await readAfterClick('shown')).outlineStyle).toBe('none');
+ expect((await readAfterClick('hidden')).outlineStyle).toBe('none');
+
+ for (const { media, query } of [
+ { media: { forcedColors: 'active' }, query: '(forced-colors: active)' },
+ { media: { contrast: 'more' }, query: '(prefers-contrast: more)' },
+ ] as const) {
+ await page.emulateMedia({ forcedColors: 'none', contrast: 'no-preference', ...media });
+ expect(await page.evaluate((mediaQuery) => matchMedia(mediaQuery).matches, query)).toBe(true);
+ const on = await readAfterClick('shown');
+ expect(on.outlineStyle, query).toBe('solid');
+ expect(on.outlineWidthPx, query).toBeGreaterThanOrEqual(1);
+ expect(contrastRatio(on.outlineColor, on.background), query).toBeGreaterThanOrEqual(3);
+ expect(on.boxShadow, query).toBe('none');
+ const off = await readAfterClick('hidden');
+ expect(off.outlineStyle, query).toBe('none');
+ }
+ });
+
+ test('the pane divider stays a visible line against the header when the system forces colors', async ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'divider-forced-colors');
+ await movePointerOffHeader(page);
+
+ for (const colorScheme of ['light', 'dark'] as const) {
+ await page.emulateMedia({ forcedColors: 'none', colorScheme });
+ const normal = await readDividerPaint(page);
+ expect(normal.width, colorScheme).toBe(1);
+ const [fillRed, fillGreen, fillBlue, fillAlpha] = normal.fill;
+ const expectedLine = [fillRed, fillGreen, fillBlue].map(
+ (channel, index) => channel * fillAlpha + (normal.backdrop[index] ?? 0) * (1 - fillAlpha),
+ );
+ const lineDrift = Math.max(
+ ...normal.line.map((channel, index) => Math.abs(channel - (expectedLine[index] ?? 0))),
+ );
+ expect(
+ lineDrift,
+ `${colorScheme}: line ${normal.line.join(',')} vs border token ${expectedLine.map(Math.round).join(',')}`,
+ ).toBeLessThanOrEqual(2);
+
+ await page.emulateMedia({ forcedColors: 'active', colorScheme });
+ expect(await page.evaluate(() => matchMedia('(forced-colors: active)').matches)).toBe(true);
+ const forced = await readDividerPaint(page);
+ expect(forced.width, colorScheme).toBeGreaterThan(0);
+ expect(forced.height, colorScheme).toBeGreaterThan(0);
+ const ratio = contrastRatio(forced.line, forced.backdrop);
+ expect(
+ ratio,
+ `${colorScheme} forced colors: line ${forced.line.join(',')} on ${forced.backdrop.join(',')} is ${ratio.toFixed(2)}:1`,
+ ).toBeGreaterThanOrEqual(3);
+ }
+ });
+});
+
+interface SampledPane {
+ readonly pressed: boolean;
+ readonly onScreen: boolean;
+}
+
+type SampledFrame = Partial<Record<Pane, SampledPane>>;
+
+interface FrameSamplerWindow {
+ __paneFrameSampler?: { stop(): SampledFrame[] };
+}
+
+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);
+ };
+ requestAnimationFrame(tick);
+ (window as FrameSamplerWindow).__paneFrameSampler = {
+ stop: () => {
+ running = false;
+ observer.disconnect();
+ return frames;
+ },
+ };
+ },
+ {
+ agentsMount: AGENTS_MOUNT,
+ bottomPanel: BOTTOM_TERMINAL_PANEL,
+ rightMount: RIGHT_TERMINAL_MOUNT,
+ },
+ );
+ await settleFrames(page);
+}
+
+async function settleFrames(page: Page): Promise<void> {
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ let remaining = 5;
+ const next = () => {
+ remaining -= 1;
+ if (remaining === 0) resolve();
+ else requestAnimationFrame(next);
+ };
+ requestAnimationFrame(next);
+ }),
+ );
+}
+
+async function expectEveryFrameMatches(page: Page, panes: readonly Pane[]): Promise<void> {
+ await settleFrames(page);
+ const frames = await page.evaluate(() => {
+ const sampler = (window as FrameSamplerWindow).__paneFrameSampler;
+ if (sampler === undefined) throw new Error('the frame sampler is not running');
+ return sampler.stop();
+ });
+ expect(frames.length, 'frames sampled').toBeGreaterThan(10);
+ for (const pane of panes) {
+ const states = new Set(frames.map((frame) => frame[pane]?.pressed));
+ expect([...states].sort(), `${pane} was sampled both on and off`).toEqual([false, true]);
+ }
+ const mismatches = frames.flatMap((frame, index) =>
+ panes.flatMap((pane) => {
+ const sampled = frame[pane];
+ return sampled !== undefined && sampled.pressed !== sampled.onScreen
+ ? [`frame ${index}: ${pane} pressed=${sampled.pressed} on screen=${sampled.onScreen}`]
+ : [];
+ }),
+ );
+ expect(mismatches, `mismatched frames out of ${frames.length}`).toEqual([]);
+}
+
+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 ({
+ page,
+ api,
+ }) => {
+ await openWeb(page, api, 'frames-chat');
+ await startFrameSampler(page);
+
+ await clickPaneButton(page, 'agents', 'shown');
+ const preferredWidth = await paneExtentPx(page, 'agents');
+ 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 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 ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await presetTerminalPlacement(page, placement);
+ await openDesktop(page, api, workerServer, `frames-${placement}`);
+ await startFrameSampler(page);
+
+ 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 bringBackWithOneClick(page, 'terminal', preferredExtent);
+ await clickPaneButton(page, 'terminal', 'hidden');
+
+ await expectEveryFrameMatches(page, ['terminal']);
+ });
+ }
+
+ test('a saved layout restored late shows both panes with their buttons in the same frames', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = await seedDoc(api, 'frames-restore');
+ await stubAgentCatalog(page);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ let contentDir = workerServer.contentDir;
+ try {
+ contentDir = realpathSync(contentDir);
+ } catch {}
+ await installHandoffMocks(page, {
+ host: 'electron',
+ install: { claude: false, codex: false, cursor: false },
+ workerBaseURL: workerServer.baseURL,
+ workerContentDir: contentDir,
+ heldDockState: { terminalVisible: true, agentPanelVisible: true },
+ });
+ await page.goto(`/#/${name}`);
+ await expect(headerPaneButton(page, 'terminal')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await expect.poll(() => readDockStateRequests(page)).toBeGreaterThan(0);
+ await expectPane(page, 'agents', 'hidden');
+ await expectPane(page, 'terminal', 'hidden');
+ await startFrameSampler(page);
+
+ await releaseHeldDockState(page);
+ await expectPane(page, 'terminal', 'shown');
+ await expectPane(page, 'agents', 'shown');
+
+ await expectEveryFrameMatches(page, ['agents', 'terminal']);
+ });
+});
diff --git a/packages/app/tests/stress/sidebar-search-pill.e2e.ts b/packages/app/tests/stress/header-search-pill.e2e.ts
similarity index 84%
rename from packages/app/tests/stress/sidebar-search-pill.e2e.ts
rename to packages/app/tests/stress/header-search-pill.e2e.ts
index 6ba5ecb1a..253b71873 100644
--- a/packages/app/tests/stress/sidebar-search-pill.e2e.ts
+++ b/packages/app/tests/stress/header-search-pill.e2e.ts
@@ -3,10 +3,13 @@ import { expect, test } from './_helpers';
const DESKTOP_VIEWPORT = { width: 1440, height: 900 } as const;
-const pill = (page: Page) => page.locator('[data-telemetry-event="ok.sidebar.search_pill.click"]');
+const SEARCH_TELEMETRY_EVENT = 'ok.app_header.search.click';
+const appHeader = (page: Page) => page.locator('header[data-app-header]');
+const pill = (page: Page) =>
+ appHeader(page).locator(`[data-telemetry-event="${SEARCH_TELEMETRY_EVENT}"]`);
const cmdkRoot = (page: Page) => page.locator('[cmdk-root]');
const cmdkInput = (page: Page) => page.locator('[data-slot="command-input"]');
-const sidebarHeader = (page: Page) => page.locator('[data-slot="sidebar-header"]');
+const fileList = (page: Page) => page.locator('[data-slot="sidebar-container"]');
const projectActionsToolbar = (page: Page) =>
page
.locator('[data-sidebar-root-context]')
@@ -76,8 +79,8 @@ async function restoreRequiredFixtureEntries({
.toBe(true);
}
-test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', () => {
- test('icon button renders above FileTree on initial sidebar load with the locked telemetry attribute', async ({
+test.describe('header-search-pill — discovery, click, keyboard, semantics', () => {
+ test('icon button renders in the app header on initial load with the locked telemetry attribute', async ({
page,
api,
}) => {
@@ -99,10 +102,8 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
expect(childCount.hasKbd).toBe(false);
expect(childCount.hasLabelSpan).toBe(false);
- await expect(pill(page)).toHaveAttribute(
- 'data-telemetry-event',
- 'ok.sidebar.search_pill.click',
- );
+ await expect(pill(page)).toHaveAttribute('data-telemetry-event', SEARCH_TELEMETRY_EVENT);
+ await expect(page.locator(`[data-telemetry-event="${SEARCH_TELEMETRY_EVENT}"]`)).toHaveCount(1);
});
test('clicking the pill opens the CommandPalette and focuses its input', async ({
@@ -146,15 +147,15 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
await pill(page).click();
await expect(cmdkRoot(page)).toBeVisible({ timeout: 2_000 });
- await page.evaluate(() => {
+ await page.evaluate((telemetryEvent) => {
const btn = document.querySelector(
- 'button[data-telemetry-event="ok.sidebar.search_pill.click"]',
+ `header[data-app-header] button[data-telemetry-event="${telemetryEvent}"]`,
);
if (!(btn instanceof HTMLElement)) {
throw new Error('pill button not found in DOM');
}
btn.click();
- });
+ }, SEARCH_TELEMETRY_EVENT);
await expect
.poll(
@@ -183,7 +184,7 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
await expect(cmdkRoot(page)).toBeHidden({ timeout: 2_000 });
});
- test('project actions live under the project-root row and Search sits in SidebarHeader', async ({
+ test('project actions live under the project-root row and Search sits in the app header, not the file list', async ({
page,
api,
workerServer,
@@ -218,9 +219,12 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
timeout: 15_000,
});
- await expect(sidebarHeader(page).getByTestId('sidebar-toolbar')).toHaveCount(0);
- const searchInsideHeader = sidebarHeader(page).getByRole('button', { name: 'Search' });
- await expect(searchInsideHeader).toHaveCount(1);
+ await expect(fileList(page).locator('[data-slot="sidebar-header"]')).toHaveCount(0);
+ await expect(
+ fileList(page).locator('[data-sidebar-project-row]').getByTestId('sidebar-toolbar'),
+ ).toHaveCount(1);
+ await expect(fileList(page).getByRole('button', { name: 'Search' })).toHaveCount(0);
+ await expect(appHeader(page).getByRole('button', { name: 'Search' })).toHaveCount(1);
const toolbar = projectActionsToolbar(page);
await expect(toolbar).toBeVisible();
@@ -294,7 +298,7 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
});
});
-test.describe('sidebar-search-pill — visual anatomy and layout', () => {
+test.describe('header-search-pill — visual anatomy and layout', () => {
test('icon button has a small (non-pill) corner radius — NOT rounded-full', async ({
page,
api,
@@ -340,7 +344,7 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
}
});
- test('visual anatomy — icon-only, roughly square (~28px), right-aligned at the row trailing edge', async ({
+ test('visual anatomy — icon-only, roughly square (~28px), inside the header row and its leading group', async ({
page,
api,
}) => {
@@ -353,28 +357,30 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
const button = el as HTMLElement;
const rect = button.getBoundingClientRect();
const svg = button.querySelector('svg');
- const parent = button.parentElement;
- if (!svg || !parent) return { ok: false as const };
- const parentRect = parent.getBoundingClientRect();
+ const header = button.closest('header[data-app-header]');
+ const leading = button.closest('[data-app-header-leading]');
+ if (!svg || !header || !leading) return { ok: false as const };
+ const headerRect = header.getBoundingClientRect();
return {
ok: true as const,
height: rect.height,
width: rect.width,
- hasSvg: true,
- rightGap: parentRect.right - rect.right,
+ topGap: rect.top - headerRect.top,
+ bottomGap: headerRect.bottom - rect.bottom,
};
});
- if (!layout.ok) throw new Error('search icon button or its row parent missing');
+ if (!layout.ok) throw new Error('search icon button is not in the app header leading group');
expect(layout.height).toBeGreaterThanOrEqual(24);
expect(layout.height).toBeLessThanOrEqual(32);
expect(layout.width).toBeGreaterThanOrEqual(24);
expect(layout.width).toBeLessThanOrEqual(32);
- expect(layout.rightGap).toBeGreaterThanOrEqual(-1);
- expect(layout.rightGap).toBeLessThanOrEqual(12);
+ expect(layout.topGap).toBeGreaterThanOrEqual(0);
+ expect(layout.bottomGap).toBeGreaterThanOrEqual(0);
+ expect(Math.abs(layout.topGap - layout.bottomGap)).toBeLessThanOrEqual(1);
});
- test('desktop viewport (≥1280px) renders the pill cleanly within sidebar bounds', async ({
+ test('desktop viewport (≥1280px) renders the pill cleanly within the header leading group', async ({
page,
api,
}) => {
@@ -385,30 +391,25 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
const fit = await pill(page).evaluate((el) => {
const pillEl = el as HTMLElement;
- let parent: HTMLElement | null = pillEl.parentElement;
- while (parent && parent.dataset.slot !== 'sidebar') {
- parent = parent.parentElement;
- }
- if (!parent) return { ok: false as const };
+ const leading = pillEl.closest('[data-app-header-leading]');
+ if (!leading) return { ok: false as const };
const pillRect = pillEl.getBoundingClientRect();
- const sidebarRect = parent.getBoundingClientRect();
- const sidebarStyles = window.getComputedStyle(parent);
+ const leadingRect = leading.getBoundingClientRect();
return {
ok: true as const,
pillLeft: pillRect.left,
pillRight: pillRect.right,
- sidebarLeft: sidebarRect.left,
- sidebarRight: sidebarRect.right,
- overflowX: sidebarStyles.overflowX,
+ leadingLeft: leadingRect.left,
+ leadingRight: leadingRect.right,
};
});
- if (!fit.ok) throw new Error('sidebar container not found in DOM');
+ if (!fit.ok) throw new Error('app header leading group not found in DOM');
- expect(fit.pillLeft + 0.5).toBeGreaterThanOrEqual(fit.sidebarLeft);
- expect(fit.pillRight - 0.5).toBeLessThanOrEqual(fit.sidebarRight);
+ expect(fit.pillLeft + 0.5).toBeGreaterThanOrEqual(fit.leadingLeft);
+ expect(fit.pillRight - 0.5).toBeLessThanOrEqual(fit.leadingRight);
});
- test('small viewport (<1024px below partition) renders the pill cleanly without overflow', async ({
+ test('small viewport (<1024px below partition) renders the pill in the header without opening the file list', async ({
page,
api,
}) => {
@@ -416,17 +417,11 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
await page.setViewportSize({ width: 900, height: 800 });
await page.goto('/#/q013');
- await page.locator('[data-sidebar="trigger"]').first().click();
- await page
- .locator('[data-slot="sidebar"][data-state="expanded"]')
- .waitFor({ state: 'attached', timeout: 5_000 });
- await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
-
- await expect(pill(page)).toBeVisible();
+ await expect(pill(page)).toBeVisible({ timeout: 15_000 });
const fit = await pill(page).evaluate((el) => {
const pillEl = el as HTMLElement;
- const parent = pillEl.parentElement;
+ const parent = pillEl.closest('[data-app-header-leading]');
if (!parent) return { ok: false as const };
const pillRect = pillEl.getBoundingClientRect();
const parentRect = parent.getBoundingClientRect();
@@ -438,7 +433,7 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
rightDelta: parentRect.right - pillRect.right,
};
});
- if (!fit.ok) throw new Error('search icon button parent wrapper not found');
+ if (!fit.ok) throw new Error('app header leading group not found');
expect(fit.leftDelta).toBeGreaterThanOrEqual(-1);
expect(fit.rightDelta).toBeGreaterThanOrEqual(-1);
expect(fit.pillWidth).toBeGreaterThanOrEqual(24);
@@ -497,7 +492,7 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
});
});
-test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
+test.describe('header-search-pill — Electron host & sidebar-state', () => {
test('pill is interactive in browser mode (companion to source-level Electron no-drag class guard)', async ({
page,
api,
@@ -511,7 +506,7 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
await expect(cmdkRoot(page)).toBeVisible({ timeout: 2_000 });
});
- test('sidebar collapse changes sidebar state and moves the pill off-canvas (sidebar carries it away)', async ({
+ test('the pill stays put, and stays the only search button, while the file list collapses and reopens', async ({
page,
api,
}) => {
@@ -520,26 +515,37 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
await page.goto('/#/q020');
await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ const searchButtons = page.getByRole('button', { name: 'Search', exact: true });
+ const pillRect = () =>
+ pill(page).evaluate((el) => {
+ const { left, top } = (el as HTMLElement).getBoundingClientRect();
+ return { left, top };
+ });
await expect(pill(page)).toBeVisible();
- const startLeft = await pill(page).evaluate((el) => el.getBoundingClientRect().left);
- expect(startLeft).toBeGreaterThanOrEqual(0);
-
- await page.locator('[data-sidebar="trigger"]').first().click();
+ await expect(searchButtons).toHaveCount(1);
+ const expandedRect = await pillRect();
const sidebarLoc = page.locator('[data-slot="sidebar"]:not([data-mobile])').first();
+ await page.locator('[data-sidebar="trigger"]').first().click();
await expect
.poll(async () => await sidebarLoc.getAttribute('data-state'), {
timeout: 5_000,
})
.toBe('collapsed');
+ await expect(pill(page)).toBeVisible();
+ await expect(searchButtons).toHaveCount(1);
+ expect(await pillRect()).toEqual(expandedRect);
+
+ await page.locator('[data-sidebar="trigger"]').first().click();
await expect
- .poll(
- async () =>
- await pill(page).evaluate((el) => (el as HTMLElement).getBoundingClientRect().right),
- { timeout: 5_000 },
- )
- .toBeLessThanOrEqual(1);
+ .poll(async () => await sidebarLoc.getAttribute('data-state'), {
+ timeout: 5_000,
+ })
+ .toBe('expanded');
+
+ await expect(searchButtons).toHaveCount(1);
+ expect(await pillRect()).toEqual(expandedRect);
});
test('web-mode renders the project header alongside the pill', async ({ page, api }) => {
diff --git a/packages/app/tests/stress/hidden-chat-activity.e2e.ts b/packages/app/tests/stress/hidden-chat-activity.e2e.ts
new file mode 100644
index 000000000..acf1caa90
--- /dev/null
+++ b/packages/app/tests/stress/hidden-chat-activity.e2e.ts
@@ -0,0 +1,94 @@
+import { randomUUID } from 'node:crypto';
+import { acpCatalogBody, expect, test, waitForActiveProviderSynced } from './_helpers';
+import { startHiddenChatAgent } from './hidden-chat-transport.test-helper';
+
+const EDITOR_CARD = '[data-slot="pane-card"][data-pane="editor"]';
+const CHAT_CARD = '[data-slot="pane-card"][data-pane="agents"]';
+const THREAD_COMPOSER = '[data-testid="agent-thread-composer"]';
+
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
+test('hidden Chat retains a live draft and unread completed stream until the thread is viewed', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const docName = `hidden-chat-${randomUUID()}`;
+ await api.seedDocs([{ name: docName, markdown: '# Hidden Chat activity\n' }]);
+ const fixture = await startHiddenChatAgent(workerServer);
+ try {
+ await page.setViewportSize({ width: 767, height: 800 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const editorButton = page.getByTestId('header-pane-button-editor');
+ const chatButton = page.getByTestId('header-pane-button-agents');
+ const chatCard = page.locator(CHAT_CARD);
+ await chatButton.click();
+ await expect(chatCard).toBeVisible();
+ const threadTab = chatCard.locator(`[role="tab"][data-tab-id="${fixture.threadId}"]`);
+ await threadTab.click();
+ const composer = chatCard.getByRole('textbox', { name: 'Message Hidden activity fixture' });
+ const threadSurface = composer.locator('xpath=ancestor::*[@data-session-id][1]');
+ await expect(composer).toBeVisible();
+ await composer.click();
+ await page.keyboard.insertText('Start the controlled response');
+ await threadSurface.getByTestId('agent-thread-send').click();
+ await expect(threadSurface.getByTestId('agent-thread-agent-message')).toContainText(
+ 'Streaming',
+ );
+ await expect(threadTab).toContainText('Working');
+
+ await composer.click();
+ await page.keyboard.insertText('Draft survives the stream');
+ await expect(composer).toContainText('Draft survives the stream');
+ const sessionId = await threadSurface.getAttribute('data-session-id');
+ expect(sessionId).not.toBeNull();
+
+ await threadSurface.getByTestId('agent-thread-add-to-prompt').click();
+ const fileChooser = page.waitForEvent('filechooser');
+ await page.getByRole('menuitem', { name: 'Attach files' }).click();
+ await (await fileChooser).setFiles({
+ name: 'staged-note.txt',
+ mimeType: 'text/plain',
+ buffer: Buffer.from('Pending Chat context'),
+ });
+ await expect(
+ threadSurface.getByTestId('agent-thread-pending-images').getByTitle('staged-note.txt'),
+ ).toBeVisible();
+
+ await editorButton.click();
+ await expect(page.locator(EDITOR_CARD)).toBeVisible();
+ await expect(chatCard).toBeHidden();
+ await expect(chatCard).toHaveAttribute('inert', '');
+ fixture.release();
+ await fixture.waitForFinalChunk();
+ fixture.finish();
+ await expect(threadTab).toContainText('new activity');
+
+ await chatButton.click();
+ await expect(chatCard).toBeVisible();
+ await expect(threadSurface.getByTestId('agent-thread-agent-message')).toContainText(
+ 'Streaming and completed while hidden',
+ );
+ await expect(composer).toContainText('Draft survives the stream');
+ await expect(
+ threadSurface.getByTestId('agent-thread-pending-images').getByTitle('staged-note.txt'),
+ ).toBeVisible();
+ await expect(
+ chatCard.locator(`[data-session-id="${sessionId}"] ${THREAD_COMPOSER}`),
+ ).toBeVisible();
+ await expect(threadTab).not.toContainText('new activity');
+
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await expect(chatCard).toBeHidden();
+ await page.setViewportSize({ width: 767, height: 800 });
+ await expect(chatCard).toBeVisible();
+ await expect(composer).toContainText('Draft survives the stream');
+ } finally {
+ fixture.release();
+ fixture.finish();
+ await fixture.close();
+ }
+});
diff --git a/packages/app/tests/stress/hidden-chat-transport.test-helper.ts b/packages/app/tests/stress/hidden-chat-transport.test-helper.ts
new file mode 100644
index 000000000..73bb54d75
--- /dev/null
+++ b/packages/app/tests/stress/hidden-chat-transport.test-helper.ts
@@ -0,0 +1,199 @@
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type {
+ ThreadClientFrame,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type { WorkerServer } from './_helpers';
+
+interface HiddenChatAgent {
+ readonly agentId: string;
+ readonly threadId: string;
+ createThread(): Promise<string>;
+ release(): void;
+ waitForFinalChunk(targetThreadId?: string): Promise<void>;
+ finish(): void;
+ closeThread(threadId: string): Promise<void>;
+ close(): Promise<void>;
+}
+
+export async function startHiddenChatAgent(workerServer: WorkerServer): Promise<HiddenChatAgent> {
+ const localDir = join(workerServer.contentDir, '.ok', 'local');
+ mkdirSync(localDir, { recursive: true });
+ const agentId = `hidden-chat-${randomUUID()}`;
+ const scriptPath = join(localDir, `${agentId}.mjs`);
+ const releasePath = join(localDir, `${agentId}.release`);
+ const finishPath = join(localDir, `${agentId}.finish`);
+ writeFileSync(
+ scriptPath,
+ `import { existsSync, watch } from 'node:fs';
+import { dirname } from 'node:path';
+const releasePath = ${JSON.stringify(releasePath)};
+const finishPath = ${JSON.stringify(finishPath)};
+const write = (frame) => process.stdout.write(JSON.stringify(frame) + '\\n');
+const notify = (text) => write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'hidden-chat-session', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } } });
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let newline = buffer.indexOf('\\n');
+ while (newline !== -1) {
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ newline = buffer.indexOf('\\n');
+ if (!line.trim()) continue;
+ const frame = JSON.parse(line);
+ const reply = (result) => write({ jsonrpc: '2.0', id: frame.id, result });
+ if (frame.method === 'initialize') reply({ protocolVersion: 1, agentCapabilities: {} });
+ else if (frame.method === 'session/new') reply({ sessionId: 'hidden-chat-session' });
+ else if (frame.method === 'session/prompt') {
+ let released = false;
+ const watcher = watch(dirname(releasePath), { persistent: false }, () => complete());
+ const complete = () => {
+ if (released || !existsSync(releasePath)) return;
+ released = true;
+ watcher.close();
+ notify(' and completed while hidden');
+ const finishWatcher = watch(dirname(finishPath), { persistent: false }, () => finish());
+ const finish = () => {
+ if (!existsSync(finishPath)) return;
+ finishWatcher.close();
+ reply({ stopReason: 'end_turn' });
+ };
+ finish();
+ };
+ notify('Streaming');
+ complete();
+ } else if (frame.id !== undefined) reply({});
+ }
+});
+`,
+ );
+ const agentsPath = join(localDir, 'acp-agents.json');
+ const registeredAgents = existsSync(agentsPath)
+ ? (JSON.parse(readFileSync(agentsPath, 'utf8')) as unknown[])
+ : [];
+ writeFileSync(
+ agentsPath,
+ JSON.stringify([
+ ...registeredAgents,
+ {
+ id: agentId,
+ name: 'Hidden activity fixture',
+ command: process.execPath,
+ args: [scriptPath],
+ },
+ ]),
+ );
+
+ const socket = new WebSocket(`ws://127.0.0.1:${workerServer.port}/collab/thread`);
+ const frames: ThreadServerFrame[] = [];
+ const listeners = new Set<(frame: ThreadServerFrame) => void>();
+ socket.addEventListener('message', (event) => {
+ const frame = JSON.parse(String(event.data)) as ThreadServerFrame;
+ frames.push(frame);
+ for (const listener of listeners) listener(frame);
+ });
+ await new Promise<void>((resolve, reject) => {
+ socket.addEventListener('open', () => resolve(), { once: true });
+ socket.addEventListener('error', () => reject(new Error('thread fixture socket failed')), {
+ once: true,
+ });
+ });
+ const send = (frame: ThreadClientFrame) => socket.send(JSON.stringify(frame));
+ const waitForFrame = (matches: (frame: ThreadServerFrame) => boolean, fromIndex = 0) =>
+ new Promise<ThreadServerFrame>((resolve, reject) => {
+ const found = frames.slice(fromIndex).find(matches);
+ if (found !== undefined) {
+ resolve(found);
+ return;
+ }
+ const timer = setTimeout(() => {
+ listeners.delete(listener);
+ reject(
+ new Error(
+ `thread fixture frame timeout; saw ${frames.map((frame) => frame.op).join(', ')}`,
+ ),
+ );
+ }, 20_000);
+ const listener = (frame: ThreadServerFrame) => {
+ if (!matches(frame)) return;
+ clearTimeout(timer);
+ listeners.delete(listener);
+ resolve(frame);
+ };
+ listeners.add(listener);
+ });
+ const reqId = `create-${randomUUID()}`;
+ send({ op: 'create', reqId, agent: { source: 'custom', id: agentId } });
+ const created = await waitForFrame((frame) => frame.op === 'created' && frame.reqId === reqId);
+ if (created.op !== 'created') throw new Error('fixture thread did not return its created frame');
+ const threadId = created.info.threadId;
+ await waitForFrame(
+ (frame) =>
+ frame.op === 'info' && frame.info.threadId === threadId && frame.info.status === 'ready',
+ );
+
+ const closeThread = async (id: string) => {
+ const closeFromIndex = frames.length;
+ send({ op: 'close', threadId: id });
+ const closed = await waitForFrame((frame) => frame.op === 'threads', closeFromIndex);
+ if (closed.op !== 'threads') return;
+ if (closed.threads.some((thread) => thread.threadId === id && thread.archived === true)) {
+ const deleteFromIndex = frames.length;
+ send({ op: 'delete', threadId: id });
+ await waitForFrame(
+ (frame) =>
+ frame.op === 'threads' && !frame.threads.some((thread) => thread.threadId === id),
+ deleteFromIndex,
+ );
+ }
+ };
+
+ return {
+ agentId,
+ threadId,
+ createThread: async () => {
+ const nextReqId = `create-${randomUUID()}`;
+ send({ op: 'create', reqId: nextReqId, agent: { source: 'custom', id: agentId } });
+ const nextCreated = await waitForFrame(
+ (frame) => frame.op === 'created' && frame.reqId === nextReqId,
+ );
+ if (nextCreated.op !== 'created') throw new Error('fixture thread was not created');
+ return nextCreated.info.threadId;
+ },
+ release: () => writeFileSync(releasePath, 'ready'),
+ waitForFinalChunk: async (targetThreadId = threadId) => {
+ if (targetThreadId !== threadId) {
+ const subscribeFromIndex = frames.length;
+ send({ op: 'subscribe', threadId: targetThreadId, sinceSeq: 0 });
+ await waitForFrame(
+ (frame) => frame.op === 'subscribed' && frame.threadId === targetThreadId,
+ subscribeFromIndex,
+ );
+ }
+ await waitForFrame(
+ (frame) =>
+ frame.op === 'events' &&
+ frame.threadId === targetThreadId &&
+ frame.events.some(
+ (event) =>
+ event.kind === 'session_update' &&
+ event.update.sessionUpdate === 'agent_message_chunk' &&
+ event.update.content.type === 'text' &&
+ event.update.content.text === ' and completed while hidden',
+ ),
+ );
+ },
+ finish: () => writeFileSync(finishPath, 'ready'),
+ closeThread,
+ close: async () => {
+ try {
+ await closeThread(threadId);
+ } finally {
+ socket.close();
+ }
+ },
+ };
+}
diff --git a/packages/app/tests/stress/information-cover-doc-panel-host.e2e.ts b/packages/app/tests/stress/information-cover-doc-panel-host.e2e.ts
new file mode 100644
index 000000000..c9a1399f9
--- /dev/null
+++ b/packages/app/tests/stress/information-cover-doc-panel-host.e2e.ts
@@ -0,0 +1,62 @@
+import { randomUUID } from 'node:crypto';
+import { expect, test, waitForActiveProviderSynced } from './_helpers';
+
+test.use({ video: 'off', trace: 'off' });
+
+test('information cover keeps the same document panel content and selected tab through Back and widening', async ({
+ page,
+ api,
+}) => {
+ const suffix = randomUUID().slice(0, 8);
+ const docName = `cover-host-${suffix}`;
+ const heading = `Cover heading ${suffix}`;
+ await api.seedDocs([{ name: docName, markdown: `# ${heading}\n\nRetained body.\n` }]);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const panel = page.locator('#doc-panel');
+ await expect(panel).toBeVisible();
+ await expect(panel.getByRole('button', { name: heading })).toBeVisible();
+ const panelHeaderNode = await panel.locator('[data-doc-panel-header]').elementHandle();
+ if (panelHeaderNode == null) throw new Error('document panel content is missing');
+
+ try {
+ await page.setViewportSize({ width: 390, height: 800 });
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ await expect(cover.getByRole('button', { name: heading })).toBeVisible();
+ await expect
+ .poll(() =>
+ panelHeaderNode.evaluate(
+ (element) =>
+ element.isConnected &&
+ element === document.querySelector('[data-doc-panel-header]') &&
+ element.closest('[data-doc-panel-cover]') != null,
+ ),
+ )
+ .toBe(true);
+
+ await cover.getByRole('tab', { name: 'Links' }).click();
+ await expect(cover.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await cover.locator('[data-doc-panel-back]').click();
+ await expect(cover).toHaveCount(0);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await expect(panel).toBeVisible();
+ await expect(panel.getByRole('tab', { name: 'Links' })).toHaveAttribute('data-state', 'on');
+ await expect
+ .poll(() =>
+ panelHeaderNode.evaluate(
+ (element) =>
+ element.isConnected &&
+ element === document.querySelector('[data-doc-panel-header]') &&
+ element.closest('#doc-panel') != null &&
+ element.closest('[data-doc-panel-cover]') == null,
+ ),
+ )
+ .toBe(true);
+ } finally {
+ await panelHeaderNode.dispose();
+ }
+});
diff --git a/packages/app/tests/stress/information-cover-retention.e2e.ts b/packages/app/tests/stress/information-cover-retention.e2e.ts
new file mode 100644
index 000000000..e887c2590
--- /dev/null
+++ b/packages/app/tests/stress/information-cover-retention.e2e.ts
@@ -0,0 +1,140 @@
+import { randomUUID } from 'node:crypto';
+import type { Locator, Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced } from './_helpers';
+
+const labels = ['alpha', 'bravo', 'charlie', 'delta'];
+
+function paneTabs(page: Page): Locator {
+ return page.locator('[data-editor-header-tabs] [data-editor-pane-tabs]');
+}
+
+async function openDocFromSidebar(page: Page, docName: string): Promise<void> {
+ await page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${docName}.md`, exact: true })
+ .click();
+ await waitForActiveProviderSynced(page);
+ const tab = page.locator(
+ `[data-editor-pane-focused] [data-editor-tab-sortable][data-editor-tab-id="${docName}"]`,
+ );
+ if ((await tab.getAttribute('data-preview-tab')) === 'true') {
+ await tab.click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-keep-open').click();
+ }
+}
+
+async function dragTabToRightEdge(page: Page, tab: Locator, paneId: string): Promise<void> {
+ const tabBox = await tab.boundingBox();
+ if (!tabBox) throw new Error('tab has no box');
+ await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(tabBox.x + tabBox.width / 2 + 12, tabBox.y + tabBox.height / 2, {
+ steps: 2,
+ });
+ const edge = page.locator(`section[data-editor-pane-id="${paneId}"] [data-pane-edge="right"]`);
+ await expect(edge).toBeAttached();
+ const edgeBox = await edge.boundingBox();
+ if (!edgeBox) throw new Error('pane edge has no box');
+ await page.mouse.move(edgeBox.x + edgeBox.width / 2, edgeBox.y + edgeBox.height / 2, {
+ steps: 8,
+ });
+ await expect(edge).toHaveAttribute('data-pane-drop-side', 'right');
+ await page.mouse.up();
+}
+
+test.use({ video: 'off', trace: 'off' });
+
+test('dismissed information covers do not accumulate while four live editors survive responsive cycles', async ({
+ page,
+ api,
+}) => {
+ const runId = randomUUID().slice(0, 8);
+ const docs = labels.map((label) => ({
+ name: `cover-retention-${label}-${runId}`,
+ markdown: `# ${label}-${runId}\n\n${label} retained body\n`,
+ }));
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+
+ await api.seedDocs(docs);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await page.goto(`/#/${docs[0].name}`);
+ await waitForActiveProviderSynced(page);
+ for (const doc of docs.slice(1)) {
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, doc.name);
+ const ids = await paneTabs(page).evaluateAll((strips) =>
+ strips.map((strip) => strip.getAttribute('data-editor-pane-tabs')).filter((id) => id != null),
+ );
+ const paneId = ids.at(-1);
+ if (!paneId) throw new Error('focused pane is missing');
+ const tab = page.locator(
+ `[data-editor-pane-tabs="${paneId}"] [data-editor-tab-sortable][data-editor-tab-id="${doc.name}"]`,
+ );
+ await dragTabToRightEdge(page, tab, paneId);
+ await expect(paneTabs(page)).toHaveCount(ids.length + 1);
+ }
+
+ await expect(page.locator('[data-editor-activity-mount]')).toHaveCount(4);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toHaveCount(4);
+
+ const cdp = await page.context().newCDPSession(page);
+ try {
+ for (let cycle = 0; cycle < 4; cycle++) {
+ await page.setViewportSize({ width: 390, height: 800 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ await expect(selector).toBeVisible();
+ await selector.click();
+ await page.getByRole('option', { name: `Pane ${cycle + 1}` }).click();
+ await expect(
+ page.locator(`[data-editor-activity-mount][data-doc-name="${docs[cycle].name}"]`),
+ ).toBeVisible();
+ await page.locator('[data-sidebar="trigger"]').click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+Alt+KeyB');
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await page.locator('[data-doc-panel-back]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).toHaveCount(0);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await expect(paneTabs(page)).toHaveCount(4);
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ await expect(page.locator('[data-editor-activity-mount]')).toHaveCount(4);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toHaveCount(4);
+ }
+
+ for (const doc of docs) {
+ const response = await page.request.get(
+ `/api/document?docName=${encodeURIComponent(doc.name)}`,
+ );
+ expect(response.ok()).toBe(true);
+ expect((await response.json()) as { content: string }).toMatchObject({
+ content: expect.stringContaining(`${doc.name.split('-')[2]} retained body`),
+ });
+ }
+ expect(pageErrors).toEqual([]);
+
+ await cdp.send('HeapProfiler.collectGarbage');
+ const result = (await cdp.send('DOM.getDetachedDomNodes')) as {
+ detachedNodes: Array<{ treeNode: { nodeName: string; attributes?: string[] } }>;
+ };
+ const detachedInformationCovers = result.detachedNodes.filter(({ treeNode }) => {
+ const attributes = treeNode.attributes ?? [];
+ return (
+ treeNode.nodeName === 'SECTION' &&
+ attributes.some(
+ (attribute, index) => attribute === 'data-doc-panel-cover' && index % 2 === 0,
+ )
+ );
+ }).length;
+ await test.info().attach('cover-retention.json', {
+ body: JSON.stringify({ coverTransitions: 4, detachedInformationCovers }),
+ contentType: 'application/json',
+ });
+ expect(detachedInformationCovers).toBeLessThanOrEqual(1);
+ } finally {
+ await cdp.detach();
+ }
+});
diff --git a/packages/app/tests/stress/navigation-history.e2e.ts b/packages/app/tests/stress/navigation-history.e2e.ts
index 8a4c8ec0e..d0154af78 100644
--- a/packages/app/tests/stress/navigation-history.e2e.ts
+++ b/packages/app/tests/stress/navigation-history.e2e.ts
@@ -37,7 +37,9 @@ async function expectFolder(page: Page, hash: string, folderName: string): Promi
async function expectAsset(page: Page, hash: string, assetName: string): Promise<void> {
await expectHash(page, hash);
- await expect(page.getByRole('main', { name: assetName, exact: true })).toBeVisible({
+ await expect(
+ page.getByRole('main').getByRole('region', { name: assetName, exact: true }),
+ ).toBeVisible({
timeout: 15_000,
});
}
diff --git a/packages/app/tests/stress/outline-navigation.e2e.ts b/packages/app/tests/stress/outline-navigation.e2e.ts
index 3e8e3fa54..8a660a8fb 100644
--- a/packages/app/tests/stress/outline-navigation.e2e.ts
+++ b/packages/app/tests/stress/outline-navigation.e2e.ts
@@ -132,6 +132,50 @@ test('browser-style anchor hash opens the doc and scrolls to the matching WYSIWY
.toBeLessThan(250);
});
+test('choosing the same document heading again scrolls back to it', async ({ page, api }) => {
+ const docName = `repeat-heading-${randomUUID().slice(0, 8)}`;
+ const markdown = [
+ '# Navigation',
+ '',
+ '[Go to destination](#destination)',
+ '',
+ ...Array.from({ length: 24 }, () => FILLER),
+ '## Destination',
+ '',
+ 'Destination body.',
+ '',
+ ...Array.from({ length: 8 }, () => FILLER),
+ ].join('\n');
+ await api.seedDocs([{ name: docName, markdown }]);
+ await page.setViewportSize({ width: 767, height: 700 });
+ await page.goto(`/#/${docName}`);
+
+ const destination = page.locator('.ProseMirror h2', { hasText: 'Destination' });
+ const scroller = page.locator('[data-testid="editor-scroll-container"]').first();
+ const link = page.getByRole('link', { name: 'Link: #destination' });
+ await expect(link).toBeVisible();
+ await link.click();
+ await expect
+ .poll(() => destination.evaluate((element) => element.getBoundingClientRect().top))
+ .toBeLessThan(250);
+
+ await scroller.evaluate((element) => {
+ element.scrollTo({ top: 0, behavior: 'instant' });
+ });
+ await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeLessThan(10);
+ await expect
+ .poll(() => destination.evaluate((element) => element.getBoundingClientRect().top))
+ .toBeGreaterThan(500);
+ await link.click();
+ await expect
+ .poll(() => destination.evaluate((element) => element.getBoundingClientRect().top))
+ .toBeLessThan(250);
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+});
+
test('outline click in source mode puts cursor on the heading line, skipping frontmatter', async ({
page,
api,
diff --git a/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts b/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
index 3563edd17..32e2a8fa0 100644
--- a/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
+++ b/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
@@ -1,5 +1,11 @@
import type { Page } from '@playwright/test';
-import { expect, test, waitForActiveProviderSynced } from './_helpers';
+import {
+ type ApiHelpers,
+ acpCatalogBody,
+ expect,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
const SIDEBAR_PINS_KEY = 'ok-sidebar-pins-v2';
const SIDEBAR_STATE_COOKIE_NAME = 'sidebar_state';
@@ -44,6 +50,40 @@ async function docPanelOpen(page: Page): Promise<boolean> {
return expanded === 'true';
}
+async function expectEmbeddedHeaderAddsOnlyAgents(page: Page, api: ApiHelpers, slug: string) {
+ const name = `${slug}-${test.info().workerIndex}`;
+ await seedDoc(api, name);
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+ await page.setViewportSize(WIDE);
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible({
+ timeout: 30_000,
+ });
+
+ const agents = page.getByTestId('header-pane-button-agents');
+ const chat = page.locator('[data-agents-panel-mount]');
+ await expect(agents).toBeVisible();
+ await expect(agents).toHaveAttribute('aria-pressed', 'false');
+ await expect(chat).not.toBeVisible();
+ await expect(page.getByTestId('header-pane-button-terminal')).toHaveCount(0);
+ await expect(page.getByTestId('bottom-composer')).toHaveCount(0);
+
+ await page.locator('[data-sidebar="trigger"]').click();
+ await page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${name}.md`, exact: true })
+ .click({ button: 'right' });
+ await expect(page.getByRole('menuitem').first()).toBeVisible();
+ await expect(page.getByRole('menuitem', { name: 'Open with AI' })).toHaveCount(0);
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menuitem')).toHaveCount(0);
+
+ await agents.click();
+ await expect(agents).toHaveAttribute('aria-pressed', 'true');
+ await expect(chat).toBeVisible();
+}
+
async function seedDoc(
api: { seedDocs: (d: Array<{ name: string; markdown: string }>) => Promise<void> },
name: string,
@@ -137,7 +177,9 @@ test.describe('non-embedded UA', () => {
'false',
);
const pinsBefore = await readPinsFromPage(page);
- expect(pinsBefore).toEqual({ left: { above: 'collapsed' } });
+ expect(pinsBefore).toEqual({
+ left: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' },
+ });
await page.reload();
await waitForActiveProviderSynced(page);
expect(await leftSidebarState(page)).toBe('collapsed');
@@ -228,7 +270,7 @@ test.describe('non-embedded UA', () => {
await expect(docPanelHandle).toHaveAttribute('tabindex', '0');
});
- test('QA-013: focus inside left sidebar → narrow → focus on trigger (FR-9)', async ({
+ test('QA-013: focus inside left sidebar → too narrow to fit → focus on trigger (FR-9)', async ({
page,
api,
}) => {
@@ -238,7 +280,7 @@ test.describe('non-embedded UA', () => {
await waitForActiveProviderSynced(page);
const sidebarFirstButton = page.locator('#app-file-sidebar button').first();
await sidebarFirstButton.focus();
- await page.setViewportSize(NARROW);
+ await page.setViewportSize(VERY_NARROW);
const trigger = page.locator('[data-sidebar="trigger"]');
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
const focusOnTrigger = await page.evaluate(() => {
@@ -380,16 +422,11 @@ test.describe('non-embedded UA', () => {
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 - 20, box.y + box.height / 2, { steps: 5 });
- const dragging = await page
- .locator('[data-slot="resizable-panel-group"]')
- .first()
- .getAttribute('data-dragging');
+ const draggedRow = handle.locator('xpath=ancestor::*[@data-slot="resizable-panel-group"][1]');
+ const dragging = await draggedRow.getAttribute('data-dragging');
expect(dragging, 'data-dragging while pointer is held on handle').toBeTruthy();
await page.mouse.up();
- await expect(page.locator('[data-slot="resizable-panel-group"]').first()).not.toHaveAttribute(
- 'data-dragging',
- /.+/,
- );
+ await expect(draggedRow).not.toHaveAttribute('data-dragging', /.+/);
});
test('QA-024: no sidebar_state cookie after toggles', async ({ page, context, api }) => {
@@ -424,14 +461,16 @@ test.describe('non-embedded UA', () => {
await page.locator('[data-doc-panel-toggle]').click();
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
const pins = await readPinsFromPage(page);
- expect(pins).toEqual({ right: { above: 'collapsed' } });
+ expect(pins).toEqual({
+ right: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' },
+ });
await page.reload();
await waitForActiveProviderSynced(page);
expect(await leftSidebarState(page)).toBe('expanded');
expect(await docPanelOpen(page)).toBe(false);
});
- test('QA-027: pinned-open right at 800px and 560px — T2 honored at both (constraint clash resolved)', async ({
+ test('QA-027: pinned-open right docks at 800px and is only suppressed at 560px', async ({
page,
api,
}) => {
@@ -456,16 +495,17 @@ test.describe('non-embedded UA', () => {
await page.setViewportSize(VERY_NARROW);
await expect.poll(() => page.evaluate(() => window.innerWidth), { timeout: 2000 }).toBe(560);
- const probe560 = await page.evaluate(() => {
- const panel = document.querySelector('#doc-panel') as HTMLElement | null;
- const toggle = document.querySelector('[data-doc-panel-toggle]') as HTMLElement | null;
- return {
- panelWidth: panel ? panel.getBoundingClientRect().width : null,
- toggleAriaExpanded: toggle?.getAttribute('aria-expanded') ?? null,
- };
- });
- expect(probe560.toggleAriaExpanded, '560px aria-expanded (pin still honored)').toBe('true');
- expect(probe560.panelWidth, '560px panel ≥ minSize').toBeGreaterThanOrEqual(280);
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
+ expect(await readPinsFromPage(page)).toEqual({ right: { below: 'open' } });
+ await page.setViewportSize(NARROW);
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => document.querySelector('#doc-panel')?.getBoundingClientRect().width ?? 0,
+ ),
+ )
+ .toBeGreaterThanOrEqual(280);
});
test('QA-028: rapid resize across 1024 settles without thrash', async ({ page, api }) => {
@@ -563,7 +603,7 @@ test.describe('non-embedded UA', () => {
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
});
- test('QA-001: full responsive journey (narrow → toggle → reload → widen)', async ({
+ test('QA-001: full responsive journey (narrow → hide → reload → widen)', async ({
page,
api,
}) => {
@@ -574,18 +614,22 @@ test.describe('non-embedded UA', () => {
expect(await leftSidebarState(page)).toBe('expanded');
expect(await docPanelOpen(page)).toBe(true);
await page.setViewportSize(NARROW);
+ await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
+ await page.locator('[data-sidebar="trigger"]').click();
await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute(
'aria-expanded',
'false',
);
- await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
- await page.locator('[data-sidebar="trigger"]').click();
- await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute('aria-expanded', 'true');
await page.reload();
await waitForActiveProviderSynced(page);
- expect(await leftSidebarState(page)).toBe('expanded');
+ expect(await leftSidebarState(page)).toBe('collapsed');
await page.setViewportSize(WIDE);
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible();
});
@@ -731,7 +775,7 @@ test.describe('non-embedded UA', () => {
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
});
- test('QA-045: above slot does not apply to below partition → smartDefault collapses (D13)', async ({
+ test('QA-045: an information panel opened wide stays open below 1280px while it fits', async ({
page,
api,
}) => {
@@ -742,11 +786,28 @@ test.describe('non-embedded UA', () => {
await waitForActiveProviderSynced(page);
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
await page.setViewportSize(ABOVE_1024_BELOW_1280);
- await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('#doc-panel')).toBeVisible();
expect(await readPinsFromPage(page)).toEqual({ right: { above: 'open' } });
});
- test('QA-046: narrow→toggle-open→toggle-collapse→wide → right auto-expands (below slot does NOT carry to above)', async ({
+ test('an unpinned information panel reopens when a narrow-start window widens', async ({
+ page,
+ api,
+ }) => {
+ await seedDoc(api, 'qa-right-unpinned-widen');
+ await page.setViewportSize(ABOVE_1024_BELOW_1280);
+ await page.goto('/#/qa-right-unpinned-widen');
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
+ expect(await readPinsFromPage(page)).toBeNull();
+ await page.setViewportSize(WIDE);
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ expect(await readPinsFromPage(page)).toBeNull();
+ });
+
+ test('QA-046: information hidden below 1280px stays hidden after widening', async ({
page,
api,
}) => {
@@ -757,16 +818,19 @@ test.describe('non-embedded UA', () => {
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
await page.locator('[data-doc-panel-toggle]').click();
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
- expect(await readPinsFromPage(page)).toEqual({ right: { below: 'open' } });
+ expect(await readPinsFromPage(page)).toEqual({
+ right: { above: 'open', below: 'open', embedded: 'open' },
+ });
await page.locator('[data-doc-panel-toggle]').click();
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
- expect(await readPinsFromPage(page)).toEqual({ right: { below: 'collapsed' } });
+ const hidden = { right: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' } };
+ expect(await readPinsFromPage(page)).toEqual(hidden);
await page.setViewportSize(WIDE);
- await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
- expect(await readPinsFromPage(page)).toEqual({ right: { below: 'collapsed' } });
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
+ expect(await readPinsFromPage(page)).toEqual(hidden);
});
- test('QA-047: D13 — narrow `open` pin survives a wide round-trip with a contradictory `above` pin', async ({
+ test('QA-047: information hidden wide stays hidden after narrowing below 1280px', async ({
page,
api,
}) => {
@@ -776,19 +840,15 @@ test.describe('non-embedded UA', () => {
await waitForActiveProviderSynced(page);
await page.locator('[data-doc-panel-toggle]').click();
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
- expect(await readPinsFromPage(page)).toEqual({ right: { below: 'open' } });
await page.setViewportSize(WIDE);
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
await page.locator('[data-doc-panel-toggle]').click();
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
- expect(await readPinsFromPage(page)).toEqual({
- right: { above: 'collapsed', below: 'open' },
- });
+ const hidden = { right: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' } };
+ expect(await readPinsFromPage(page)).toEqual(hidden);
await page.setViewportSize(ABOVE_1024_BELOW_1280);
- await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
- expect(await readPinsFromPage(page)).toEqual({
- right: { above: 'collapsed', below: 'open' },
- });
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'false');
+ expect(await readPinsFromPage(page)).toEqual(hidden);
});
});
@@ -820,13 +880,6 @@ type HeaderProbe = {
controls: HeaderControlProbe[];
};
-type ShellGeometry = {
- viewportWidth: number;
- workspaceWidth: number;
- workspaceLeft: number;
- navigatorWidth: number;
-};
-
async function waitForShellLayoutSettled(page: Page) {
await page.evaluate(
(frameBudget) =>
@@ -838,7 +891,7 @@ async function waitForShellLayoutSettled(page: Page) {
widthOf('[data-slot="sidebar-inset"]'),
widthOf('[data-slot="sidebar-container"]'),
widthOf('[data-slot="sidebar-gap"]'),
- widthOf('header'),
+ widthOf('header[data-editor-header]'),
].join(':');
};
let previous = '';
@@ -888,19 +941,32 @@ async function probeHeader(page: Page, controlSelector: string): Promise<HeaderP
const text = nameOf(el);
return text == null ? '' : `text:${text}`;
};
- const header = document.querySelector('header');
+ const appHeader = document.querySelector('header[data-app-header]');
+ if (appHeader == null) {
+ throw new Error(
+ 'probeHeader: no <header data-app-header> in the document, so the trailing header ' +
+ 'actions it holds would go unprobed and every overflow guard below would be vacuous',
+ );
+ }
+ const header = document.querySelector('header[data-editor-header]');
if (header == null) {
- throw new Error('probeHeader: no <header> in the document, so every probe below is vacuous');
+ throw new Error(
+ 'probeHeader: no <header data-editor-header> in the document, so the file-navigator ' +
+ 'toggle it holds would go unprobed',
+ );
}
- const trailingRail = document.querySelector('[data-editor-header-actions]');
+ const trailingRail = appHeader.querySelector('[data-app-header-trailing]');
if (trailingRail == null) {
throw new Error(
- 'probeHeader: [data-editor-header-actions] is missing, so inTrailingRail would be ' +
+ 'probeHeader: [data-app-header-trailing] is missing, so inTrailingRail would be ' +
'false for every control and the overflow guards would pass without probing anything',
);
}
const toggleElement = header.querySelector('[data-sidebar="trigger"]');
- const all = Array.from(header.querySelectorAll(selector));
+ const all = [
+ ...Array.from(appHeader.querySelectorAll(selector)),
+ ...Array.from(header.querySelectorAll(selector)),
+ ];
const probeOf = (el: Element, index: number) => {
const box = el.getBoundingClientRect();
const hit = document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2);
@@ -926,7 +992,7 @@ async function probeHeader(page: Page, controlSelector: string): Promise<HeaderP
const toggleEntry = rendered.find(({ el }) => el === toggleElement) ?? null;
return {
viewportWidth: window.innerWidth,
- headerWidth: Math.round(header.getBoundingClientRect().width),
+ headerWidth: Math.round(appHeader.getBoundingClientRect().width),
navigatorExpanded: toggleElement?.getAttribute('aria-expanded') === 'true',
toggle: toggleEntry == null ? null : probeOf(toggleEntry.el, toggleEntry.index),
controls: rendered.map(({ el, index }) => probeOf(el, index)),
@@ -934,34 +1000,6 @@ async function probeHeader(page: Page, controlSelector: string): Promise<HeaderP
}, controlSelector);
}
-async function measureShellGeometry(page: Page): Promise<ShellGeometry> {
- return await page.evaluate(() => {
- const rectOf = (selector: string) =>
- document.querySelector(selector)?.getBoundingClientRect() ?? null;
- const workspace = rectOf('[data-slot="sidebar-inset"]');
- if (workspace == null) {
- throw new Error(
- 'measureShellGeometry: [data-slot="sidebar-inset"] is missing, so a zero substituted ' +
- 'here would read as overlay geometry rather than as a stale selector',
- );
- }
- const container = rectOf('[data-slot="sidebar-container"]');
- const gap = rectOf('[data-slot="sidebar-gap"]');
- if (container == null && gap == null) {
- throw new Error(
- 'measureShellGeometry: neither [data-slot="sidebar-container"] nor ' +
- '[data-slot="sidebar-gap"] is present, so navigatorWidth would be a fabricated zero',
- );
- }
- return {
- viewportWidth: window.innerWidth,
- workspaceWidth: Math.round(workspace.width),
- workspaceLeft: Math.round(workspace.x),
- navigatorWidth: Math.round(Math.max(container?.width ?? 0, gap?.width ?? 0)),
- };
- });
-}
-
async function visibleControlKeys(page: Page, selector: string): Promise<string[]> {
return await page.evaluate(
(sel) =>
@@ -1011,7 +1049,7 @@ function trailingHeaderActionKeys(probe: HeaderProbe): string[] {
test.describe('below-threshold header layout — controls must not occlude one another', () => {
test.use({ userAgent: CHROME_VANILLA, viewport: PHONE_STANDARD });
- test('MOBILE-HEADER-1: 393x852 — the file-navigator toggle stays hit-testable with the navigator open', async ({
+ test('MOBILE-HEADER-1: 393x852 — the Files cover keeps Back hit-testable and Hide Files reachable', async ({
page,
api,
}) => {
@@ -1021,25 +1059,29 @@ test.describe('below-threshold header layout — controls must not occlude one a
await waitForActiveProviderSynced(page);
await openFileNavigator(page);
- const probe = await probeHeader(page, HEADER_CONTROL_SELECTOR);
- expect(probe.toggle, 'the file-navigator toggle must be rendered in the header').not.toBeNull();
- expect(
- probe.toggle?.occluderInTrailingRail ?? false,
- `393x852 (header ${probe.headerWidth}px): the file-navigator toggle's own centre is owned ` +
- `by "${probe.toggle?.occludedBy ?? ''}" from the trailing rail`,
- ).toBe(false);
- expect(
- probe.toggle?.directlyReachable ?? false,
- `393x852 (header ${probe.headerWidth}px): the file-navigator toggle's own centre resolves ` +
- `to "${probe.toggle?.occludedBy ?? ''}" instead of the toggle`,
- ).toBe(true);
+ const cover = page.locator('[data-files-cover]');
+ await expect(cover).toBeVisible();
+ const back = cover.locator('[data-files-back]');
+ await expect(back).toBeVisible();
+ const backOwnsItsCentre = await back.evaluate((element) => {
+ const rect = element.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
+ return hit != null && element.contains(hit);
+ });
+ expect(backOwnsItsCentre, '393x852: the Files cover Back control owns its own centre').toBe(
+ true,
+ );
- const toggle = page.locator('[data-sidebar="trigger"]');
- await toggle.click({ timeout: 5_000 });
- await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ await cover.getByRole('button', { name: 'Tree view options' }).click();
+ await page.getByRole('menuitem', { name: 'Hide Files', exact: true }).click();
+ await expect(cover).not.toBeVisible();
+ await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
});
- test('MOBILE-HEADER-2: 393x852 — no header action is lost when the header cannot fit both rails', async ({
+ test('MOBILE-HEADER-2: a header too narrow for both of its groups loses no action', async ({
page,
api,
}) => {
@@ -1062,16 +1104,31 @@ test.describe('below-threshold header layout — controls must not occlude one a
'baseline: the roomy header must expose trailing actions',
).toBeGreaterThan(0);
- await page.setViewportSize(PHONE_STANDARD);
+ const crampedWidth = await page.evaluate(() => {
+ const widthOf = (selector: string) => {
+ const el = document.querySelector(selector);
+ if (el == null) throw new Error(`MOBILE-HEADER-2: ${selector} is not in the document`);
+ return el.getBoundingClientRect().width;
+ };
+ return Math.floor(
+ widthOf('[data-app-header-leading]') + widthOf('[data-app-header-trailing]'),
+ );
+ });
+ await page.setViewportSize({ width: crampedWidth, height: PHONE_STANDARD.height });
await waitForShellLayoutSettled(page);
const cramped = await probeHeader(page, HEADER_CONTROL_SELECTOR);
- expect(cramped.navigatorExpanded, 'the navigator must still be open after the resize').toBe(
- true,
- );
+ const at = `${cramped.viewportWidth}x${PHONE_STANDARD.height} (header ${cramped.headerWidth}px)`;
+ expect(
+ cramped.navigatorExpanded,
+ 'a docked navigator that no longer fits is temporarily suppressed by the resize',
+ ).toBe(false);
+ expect(await readPinsFromPage(page), 'suppression keeps the saved open choice').toEqual({
+ left: { above: 'open', below: 'open', embedded: 'open' },
+ });
await expect(
page.getByTestId('header-overflow-actions-trigger'),
- `393x852 (header ${cramped.headerWidth}px): the trailing rail did not collapse, so this ` +
- `test never exercised the overflow recovery path it exists to guard`,
+ `${at}: the trailing group did not collapse, so this test never exercised the ` +
+ `overflow recovery path it exists to guard`,
).toBeVisible();
const directlyReachable = cramped.controls
@@ -1087,8 +1144,7 @@ test.describe('below-threshold header layout — controls must not occlude one a
);
expect(
revealed.length,
- `393x852 (header ${cramped.headerWidth}px): opening the overflow trigger revealed nothing, ` +
- `so the recovery affordance is empty`,
+ `${at}: opening the overflow trigger revealed nothing, so the recovery affordance is empty`,
).toBeGreaterThan(0);
missing = actionsMissingFrom(revealed, missing);
await page.keyboard.press('Escape');
@@ -1096,8 +1152,8 @@ test.describe('below-threshold header layout — controls must not occlude one a
expect(
missing,
- `393x852 (header ${cramped.headerWidth}px): header actions available at 900px are neither ` +
- `directly hit-testable nor reachable through an overflow affordance. ` +
+ `${at}: header actions available at 900px are neither directly hit-testable nor ` +
+ `reachable through an overflow affordance. ` +
`Directly reachable now: [${directlyReachable.join(', ')}]`,
).toEqual([]);
});
@@ -1239,7 +1295,7 @@ test.describe('below-threshold header layout — controls must not occlude one a
test.describe('phone-width shell geometry — characterization of the shipped responsive model', () => {
test.use({ userAgent: CHROME_VANILLA, viewport: PHONE_STANDARD });
- test('MOBILE-PUSH-1: 393x852 — the open navigator displaces the workspace in flow (spec JR2)', async ({
+ test('MOBILE-PUSH-1: 393x852 — the open navigator is a full editor cover, not a push', async ({
page,
api,
}) => {
@@ -1249,24 +1305,33 @@ test.describe('phone-width shell geometry — characterization of the shipped re
await waitForActiveProviderSynced(page);
await openFileNavigator(page);
- const geometry = await measureShellGeometry(page);
- expect(geometry.navigatorWidth, 'the open navigator occupies width').toBeGreaterThan(0);
- expect(
- geometry.workspaceLeft,
- `393x852: the workspace starts at x=${geometry.workspaceLeft}, so the navigator ` +
- `(${geometry.navigatorWidth}px) no longer displaces it. Overlay geometry is deferred ` +
- `scope, not this fix — update this characterization deliberately, with a spec.`,
- ).toBeGreaterThanOrEqual(geometry.navigatorWidth - 1);
- expect(
- geometry.workspaceWidth,
- `393x852: the workspace must keep the residual width beside the navigator`,
- ).toBeGreaterThanOrEqual(
- geometry.viewportWidth - geometry.navigatorWidth - RESIDUAL_WORKSPACE_SLACK_PX,
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ const geometry = await page.evaluate(() => {
+ const workspace = document
+ .querySelector('[data-slot="sidebar-inset"]')
+ ?.getBoundingClientRect();
+ const cover = document.querySelector('[data-files-cover]')?.getBoundingClientRect();
+ if (workspace == null || cover == null)
+ throw new Error('MOBILE-PUSH-1: workspace or cover missing');
+ return {
+ viewportWidth: window.innerWidth,
+ workspaceLeft: Math.round(workspace.x),
+ workspaceRight: Math.round(workspace.right),
+ coverLeft: Math.round(cover.x),
+ coverRight: Math.round(cover.right),
+ coverWidth: Math.round(cover.width),
+ };
+ });
+ expect(geometry.workspaceLeft, '393x852: the workspace is not displaced').toBeLessThanOrEqual(
+ RESIDUAL_WORKSPACE_SLACK_PX,
);
+ expect(geometry.workspaceRight).toBeLessThanOrEqual(geometry.viewportWidth + 1);
+ expect(geometry.coverLeft).toBeGreaterThanOrEqual(geometry.workspaceLeft - 1);
+ expect(geometry.coverRight).toBeLessThanOrEqual(geometry.workspaceRight + 1);
expect(
- geometry.workspaceLeft + geometry.workspaceWidth,
- `393x852: the workspace must not extend past the viewport`,
- ).toBeLessThanOrEqual(geometry.viewportWidth + 1);
+ geometry.coverWidth,
+ '393x852: the Files cover spans the editor card',
+ ).toBeGreaterThanOrEqual(geometry.viewportWidth - 2 * RESIDUAL_WORKSPACE_SLACK_PX);
});
});
@@ -1286,7 +1351,7 @@ test.describe('Cursor UA (embedded)', () => {
await page.locator('[data-doc-panel-toggle]').click();
await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true');
const pins = await readPinsFromPage(page);
- expect(pins).toEqual({ right: { embedded: 'open' } });
+ expect(pins).toEqual({ right: { above: 'open', below: 'open', embedded: 'open' } });
await page.reload();
await waitForActiveProviderSynced(page);
expect(await docPanelOpen(page)).toBe(true);
@@ -1321,7 +1386,9 @@ test.describe('Cursor UA (embedded)', () => {
const railButton = page.locator('[data-sidebar="rail"]');
await expect(railButton).toHaveCount(1);
- await railButton.hover();
+ const railBox = await railButton.boundingBox();
+ if (railBox == null) throw new Error('QA-043: the collapsed rail has no box');
+ await page.mouse.move(railBox.x + railBox.width / 2, railBox.y + railBox.height / 2);
await page.mouse.down();
await page.mouse.move(500, 400, { steps: 10 });
await page.mouse.up();
@@ -1357,6 +1424,13 @@ test.describe('Cursor UA (embedded)', () => {
);
});
+ test('the header adds only the Agents button; chat starts closed and AI handoff stays hidden', async ({
+ page,
+ api,
+ }) => {
+ await expectEmbeddedHeaderAddsOnlyAgents(page, api, 'embedded-header-cursor');
+ });
+
test('QA-019: AI-handoff affordances hidden when embedded (palette + empty-state)', async ({
page,
}) => {
@@ -1408,13 +1482,20 @@ test.describe('Codex(Dev) UA — parenthetical-tolerant embedded', () => {
await page.locator('[data-sidebar="trigger"]').click();
await expect(page.locator('[data-sidebar="trigger"]')).toHaveAttribute('aria-expanded', 'true');
const pins = await readPinsFromPage(page);
- expect(pins).toEqual({ left: { embedded: 'open' } });
+ expect(pins).toEqual({ left: { above: 'open', below: 'open', embedded: 'open' } });
await page.setViewportSize(NARROW);
await page.reload();
await waitForActiveProviderSynced(page);
expect(await leftSidebarState(page)).toBe('expanded');
});
+ test('the header adds only the Agents button; chat starts closed and AI handoff stays hidden', async ({
+ page,
+ api,
+ }) => {
+ await expectEmbeddedHeaderAddsOnlyAgents(page, api, 'embedded-header-codex');
+ });
+
test('QA-038: embedded + install hidden + handoff hidden composite', async ({ page, api }) => {
await seedDoc(api, 'qa-038');
await page.setViewportSize(WIDE);
@@ -1450,4 +1531,11 @@ test.describe('Claude(Canary) UA — embedded', () => {
expect(await leftSidebarState(page)).toBe('collapsed');
expect(await docPanelOpen(page)).toBe(false);
});
+
+ test('the header adds only the Agents button; chat starts closed and AI handoff stays hidden', async ({
+ page,
+ api,
+ }) => {
+ await expectEmbeddedHeaderAddsOnlyAgents(page, api, 'embedded-header-claude');
+ });
});
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 17778c479..cc65ddc71 100644
--- a/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts
+++ b/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts
@@ -1,15 +1,20 @@
import type { Page } from '@playwright/test';
-import { AGENTS_COLUMN_ID } from '../../src/components/editor-area-rail-registry';
-import { expect, test, waitForActiveProviderSynced } from './_helpers';
-
-const RAIL_GROUP_SELECTOR = '[data-editor-area-panels] > [data-group]';
+import { AGENTS_COLUMN_ID, 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_REVEAL_TAB = '[data-terminal-reveal="right"]';
+const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
const VIEWPORT_HEIGHT = 800;
-const SWEEP_VIEWPORT_WIDTHS = [1281, 1367, 1451, 1610, 1733] as const;
+const SWEEP_VIEWPORT_WIDTHS = [1281, 1367, 1451, 1610, 1687, 1733, 1813, 1953, 1960] as const;
const PROPORTIONALITY_TOLERANCE_PX = 0.25;
-const MIN_RENDERED_RAIL_PANELS = 3;
+const MIN_RENDERED_ROW_PANELS = 2;
const BOOT_TIMEOUT_MS = 30_000;
const LAYOUT_SETTLE_TIMEOUT_MS = 10_000;
@@ -28,7 +33,7 @@ interface RailPanelSample {
readonly flexGrow: number;
}
-async function readRailPanels(page: Page): Promise<RailPanelSample[]> {
+async function readRowPanels(page: Page, selector: string): Promise<RailPanelSample[]> {
return page.evaluate((selector) => {
const group = document.querySelector(selector);
if (group == null) return [];
@@ -39,21 +44,25 @@ async function readRailPanels(page: Page): Promise<RailPanelSample[]> {
flexGrow: Number.parseFloat(panel.style.flexGrow || '0'),
}),
);
- }, RAIL_GROUP_SELECTOR);
+ }, selector);
}
async function railSpacePx(page: Page): Promise<number> {
- const panels = await readRailPanels(page);
+ const panels = await readRowPanels(page, OUTER_ROW_SELECTOR);
return panels.reduce((total, panel) => total + panel.widthPx, 0);
}
async function openAgentsColumn(page: Page): Promise<void> {
- const reveal = page.locator(AGENTS_REVEAL_TAB);
- await expect(reveal).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
- await reveal.click();
+ 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 });
}
+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 ({
page,
@@ -65,6 +74,9 @@ test.describe('right rail flex distribution law', () => {
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');
let previousSpacePx = 0;
let subPixelSplitSamples = 0;
@@ -78,40 +90,55 @@ test.describe('right rail flex distribution law', () => {
() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
);
- const panels = await readRailPanels(page);
- 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 agentsPanel = panels.find((panel) => panel.id === AGENTS_COLUMN_ID);
- previousSpacePx = spacePx;
-
- expect(
- totalGrow,
- `viewport ${viewportWidth}: the rail panels must carry flex-grow for the law to say anything`,
- ).toBeGreaterThan(0);
- expect(
- renderedPanels.length,
- `viewport ${viewportWidth}: the law only constrains a rail that is splitting its space across several rendered panels`,
- ).toBeGreaterThanOrEqual(MIN_RENDERED_RAIL_PANELS);
- expect(
- agentsPanel?.widthPx ?? 0,
- `viewport ${viewportWidth}: the agents column must be open so the sweep measures a px-pinned column 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;
+ 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);
expect(
- Math.abs(panel.widthPx - modelledPx),
- `viewport ${viewportWidth}, panel ${panel.id}: the real engine rendered ${panel.widthPx}px, but distributing the rail'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);
+ 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);
+ }
}
}
expect(
subPixelSplitSamples,
- 'the sweep must land on at least one sub-pixel rail split, otherwise the law is only pinned where every panel happens to fall on a whole pixel',
+ 'the sweep must land on at least one sub-pixel row split, otherwise the law is only pinned where every panel happens to fall on a whole pixel',
).toBeGreaterThan(0);
});
});
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
new file mode 100644
index 000000000..e8f9deed9
--- /dev/null
+++ b/packages/app/tests/stress/responsive-cycles-release-editor-callback-contexts.e2e.ts
@@ -0,0 +1,561 @@
+import { createHash, randomUUID } from 'node:crypto';
+import {
+ closeSync,
+ existsSync,
+ openSync,
+ readFileSync,
+ unlinkSync,
+ writeFileSync,
+ writeSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { CDPSession, Locator, Page } from '@playwright/test';
+import { expect, test } from './_helpers';
+
+const labels = ['alpha', 'bravo', 'charlie', 'delta'];
+
+type HeapSnapshot = {
+ snapshot: {
+ meta: {
+ node_fields: string[];
+ edge_fields: string[];
+ node_types: string[][];
+ edge_types: string[][];
+ };
+ };
+ nodes: number[];
+ edges: number[];
+ strings: string[];
+};
+
+function retainedContextDepth(path: string, docNames: string[]) {
+ const heap = JSON.parse(readFileSync(path, 'utf8')) as HeapSnapshot;
+ const { meta } = heap.snapshot;
+ const nodeWidth = meta.node_fields.length;
+ const edgeWidth = meta.edge_fields.length;
+ const nodeTypeField = meta.node_fields.indexOf('type');
+ const nodeNameField = meta.node_fields.indexOf('name');
+ const nodeIdField = meta.node_fields.indexOf('id');
+ const nodeEdgeCountField = meta.node_fields.indexOf('edge_count');
+ const edgeTypeField = meta.edge_fields.indexOf('type');
+ const edgeNameField = meta.edge_fields.indexOf('name_or_index');
+ const edgeTargetField = meta.edge_fields.indexOf('to_node');
+ const nodeTypes = meta.node_types[0] ?? [];
+ const edgeTypes = meta.edge_types[0] ?? [];
+ const nodeCount = heap.nodes.length / nodeWidth;
+ const starts = new Uint32Array(nodeCount);
+ let edgeIndex = 0;
+ for (let index = 0; index < nodeCount; index++) {
+ starts[index] = edgeIndex;
+ edgeIndex += heap.nodes[index * nodeWidth + nodeEdgeCountField] ?? 0;
+ }
+ const nodeType = (index: number) => nodeTypes[heap.nodes[index * nodeWidth + nodeTypeField] ?? 0];
+ const nodeName = (index: number) =>
+ heap.strings[heap.nodes[index * nodeWidth + nodeNameField] ?? 0];
+ const outgoing = (index: number) => {
+ const edges: Array<{ type: string | undefined; name: string | undefined; target: number }> = [];
+ const count = heap.nodes[index * nodeWidth + nodeEdgeCountField] ?? 0;
+ for (let offset = 0; offset < count; offset++) {
+ const edge = (starts[index] ?? 0) + offset;
+ const type = edgeTypes[heap.edges[edge * edgeWidth + edgeTypeField] ?? 0];
+ const nameIndex = heap.edges[edge * edgeWidth + edgeNameField] ?? 0;
+ edges.push({
+ type,
+ name:
+ type === 'property' || type === 'context' || type === 'internal'
+ ? heap.strings[nameIndex]
+ : undefined,
+ target: (heap.edges[edge * edgeWidth + edgeTargetField] ?? 0) / nodeWidth,
+ });
+ }
+ return edges;
+ };
+
+ const slots: number[] = [];
+ for (let index = 0; index < nodeCount; index++) {
+ if (nodeType(index) === 'native' && nodeName(index)?.includes('data-editor-file-list-slot')) {
+ slots.push(index);
+ }
+ }
+ expect(slots).toHaveLength(1);
+ const refs = slots.flatMap((slot) =>
+ outgoing(slot)
+ .filter((edge) => edge.type === 'property' && edge.name?.startsWith('__reactProps$'))
+ .flatMap((edge) =>
+ outgoing(edge.target)
+ .filter((candidate) => candidate.type === 'property' && candidate.name === 'ref')
+ .map((candidate) => candidate.target)
+ .filter((target) => nodeType(target) === 'closure'),
+ ),
+ );
+ expect(refs).toHaveLength(1);
+
+ const terminalHandles: number[] = [];
+ for (let index = 0; index < nodeCount; index++) {
+ if (nodeType(index) === 'native' && nodeName(index)?.includes('data-terminal-panel-handle')) {
+ terminalHandles.push(index);
+ }
+ }
+ expect(terminalHandles).toHaveLength(1);
+ const terminalHandleCallbacks = terminalHandles.flatMap((handle) =>
+ outgoing(handle)
+ .filter((edge) => edge.type === 'property' && edge.name?.startsWith('__reactFiber$'))
+ .flatMap((edge) =>
+ outgoing(edge.target)
+ .filter(
+ (candidate) => candidate.type === 'property' && candidate.name === 'memoizedProps',
+ )
+ .flatMap((candidate) =>
+ outgoing(candidate.target)
+ .filter(
+ (callback) => callback.type === 'property' && callback.name === 'onPointerDown',
+ )
+ .map((callback) => callback.target)
+ .filter((target) => nodeType(target) === 'closure'),
+ ),
+ ),
+ );
+ expect(terminalHandleCallbacks).toHaveLength(1);
+
+ const editorAreaPanels: number[] = [];
+ for (let index = 0; index < nodeCount; index++) {
+ if (nodeType(index) === 'native' && nodeName(index)?.includes('data-editor-area-panels')) {
+ editorAreaPanels.push(index);
+ }
+ }
+ expect(editorAreaPanels).toHaveLength(1);
+ const editorAreaDestinationCallbacks = editorAreaPanels.flatMap((panel) =>
+ outgoing(panel)
+ .filter((edge) => edge.type === 'property' && edge.name?.startsWith('__reactFiber$'))
+ .flatMap((edge) =>
+ outgoing(edge.target)
+ .filter((candidate) => candidate.type === 'property' && candidate.name === 'sibling')
+ .flatMap((candidate) =>
+ outgoing(candidate.target)
+ .filter((props) => props.type === 'property' && props.name === 'memoizedProps')
+ .flatMap((props) =>
+ outgoing(props.target)
+ .filter((nested) => nested.type === 'property' && nested.name === 'props')
+ .flatMap((nested) =>
+ outgoing(nested.target)
+ .filter(
+ (callback) =>
+ callback.type === 'property' &&
+ callback.name === 'onDestinationRequested',
+ )
+ .map((callback) => callback.target)
+ .filter((target) => nodeType(target) === 'closure'),
+ ),
+ ),
+ ),
+ ),
+ );
+ expect(editorAreaDestinationCallbacks).toHaveLength(1);
+
+ const appMainNodes: number[] = [];
+ for (let index = 0; index < nodeCount; index++) {
+ if (nodeType(index) === 'native' && nodeName(index)?.includes('data-app-main=""')) {
+ appMainNodes.push(index);
+ }
+ }
+ expect(appMainNodes).toHaveLength(1);
+ const appMainEffectCallbacks = appMainNodes.flatMap((node) =>
+ outgoing(node)
+ .filter((edge) => edge.type === 'property' && edge.name?.startsWith('__reactFiber$'))
+ .flatMap((edge) =>
+ outgoing(edge.target)
+ .filter((candidate) => candidate.type === 'property' && candidate.name === 'child')
+ .flatMap((candidate) =>
+ outgoing(candidate.target)
+ .filter((queue) => queue.type === 'property' && queue.name === 'updateQueue')
+ .flatMap((queue) =>
+ outgoing(queue.target)
+ .filter((effect) => effect.type === 'property' && effect.name === 'lastEffect')
+ .flatMap((effect) =>
+ outgoing(effect.target)
+ .filter((create) => create.type === 'property' && create.name === 'create')
+ .map((create) => create.target)
+ .filter((target) => nodeType(target) === 'closure'),
+ ),
+ ),
+ ),
+ ),
+ );
+ expect(appMainEffectCallbacks).toHaveLength(1);
+
+ const expectedQueryHashes = new Map(
+ docNames.map((docName) => [JSON.stringify(['page-headings', docName]), docName]),
+ );
+ const queryRoots = new Map<string, number[]>();
+ for (let index = 0; index < nodeCount; index++) {
+ if (nodeType(index) !== 'object') continue;
+ const edges = outgoing(index);
+ const queryHash = edges.find((edge) => edge.type === 'property' && edge.name === 'queryHash');
+ if (!queryHash) continue;
+ const docName = expectedQueryHashes.get(nodeName(queryHash.target) ?? '');
+ if (!docName) continue;
+ const options = edges.find((edge) => edge.type === 'property' && edge.name === 'options');
+ const observers = edges.find((edge) => edge.type === 'property' && edge.name === 'observers');
+ if (!options || !observers) continue;
+ const queryFn = outgoing(options.target).find(
+ (edge) => edge.type === 'property' && edge.name === 'queryFn',
+ );
+ if (!queryFn || nodeType(queryFn.target) !== 'closure') continue;
+ const roots = queryRoots.get(docName) ?? [];
+ roots.push(queryFn.target);
+ queryRoots.set(docName, roots);
+ }
+ for (const docName of docNames) expect(queryRoots.get(docName)).toHaveLength(1);
+
+ const depthFrom = (roots: number[], trace = false) => {
+ const visited = new Uint8Array(nodeCount);
+ const parents = trace ? new Uint32Array(nodeCount) : null;
+ const queue = roots.map((index) => ({ index, depth: 0 }));
+ for (const root of roots) visited[root] = 1;
+ let maxDepth = 0;
+ let front = 0;
+ let contexts = 0;
+ let deepest = roots[0] ?? 0;
+ while (front < queue.length) {
+ const { index, depth } = queue[front++] ?? { index: 0, depth: 0 };
+ if (depth > maxDepth) {
+ maxDepth = depth;
+ deepest = index;
+ }
+ if (nodeName(index) === 'system / Context') contexts++;
+ for (const edge of outgoing(index)) {
+ if (visited[edge.target]) continue;
+ const entersContext =
+ nodeType(index) === 'closure' &&
+ edge.type === 'internal' &&
+ edge.name === 'context' &&
+ nodeName(edge.target) === 'system / Context';
+ const entersClosure =
+ nodeName(index) === 'system / Context' &&
+ edge.type === 'context' &&
+ nodeType(edge.target) === 'closure';
+ if (!entersContext && !entersClosure) continue;
+ visited[edge.target] = 1;
+ if (parents) parents[edge.target] = index + 1;
+ queue.push({ index: edge.target, depth: depth + 1 });
+ }
+ }
+ if (!parents) return { maxDepth, contexts };
+ const chain = [];
+ for (let index = deepest; ; ) {
+ const parent = (parents[index] ?? 0) - 1;
+ const via =
+ parent < 0
+ ? null
+ : outgoing(parent).find((edge) => edge.target === index && edge.type !== 'weak');
+ chain.push({
+ id: heap.nodes[index * nodeWidth + nodeIdField] ?? 0,
+ type: nodeType(index),
+ name: nodeName(index),
+ via: via == null ? null : { type: via.type, name: via.name },
+ });
+ if (parent < 0) break;
+ index = parent;
+ }
+ chain.reverse();
+ return { maxDepth, contexts, chain: chain.slice(0, 256), chainTruncated: chain.length > 256 };
+ };
+
+ const pageHeadingsByDoc = Object.fromEntries(
+ docNames.map((docName) => [docName, depthFrom(queryRoots.get(docName) ?? [])]),
+ );
+ return {
+ files: depthFrom(refs),
+ terminalHandle: depthFrom(
+ terminalHandleCallbacks,
+ process.env.QA101_CONTEXT_CHAIN_TRACE === '1',
+ ),
+ editorAreaDestination: depthFrom(
+ editorAreaDestinationCallbacks,
+ process.env.QA101_CONTEXT_CHAIN_TRACE === '1',
+ ),
+ appMainEffect: depthFrom(appMainEffectCallbacks, process.env.QA101_CONTEXT_CHAIN_TRACE === '1'),
+ pageHeadings: {
+ maxDepth: Math.max(...Object.values(pageHeadingsByDoc).map((result) => result.maxDepth)),
+ byDoc: pageHeadingsByDoc,
+ },
+ };
+}
+
+async function snapshotDepth(cdp: CDPSession, path: string, docNames: string[]) {
+ await cdp.send('HeapProfiler.collectGarbage');
+ const fd = openSync(path, 'w');
+ let bytes = 0;
+ const onChunk = ({ chunk }: { chunk: string }) => {
+ bytes += writeSync(fd, chunk);
+ };
+ try {
+ cdp.on('HeapProfiler.addHeapSnapshotChunk', onChunk);
+ try {
+ await cdp.send('HeapProfiler.takeHeapSnapshot', { reportProgress: false });
+ } finally {
+ cdp.off('HeapProfiler.addHeapSnapshotChunk', onChunk);
+ closeSync(fd);
+ }
+ expect(bytes).toBeGreaterThan(0);
+ return retainedContextDepth(path, docNames);
+ } finally {
+ if (existsSync(path)) unlinkSync(path);
+ }
+}
+
+function paneTabs(page: Page): Locator {
+ return page.locator('[data-editor-header-tabs] [data-editor-pane-tabs]');
+}
+
+async function openDocFromSidebar(page: Page, docName: string, body: string) {
+ await page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${docName}.md`, exact: true })
+ .click();
+ await expect(
+ page.locator(`[data-editor-activity-mount][data-doc-name="${docName}"]`),
+ ).toContainText(body);
+ const tab = page.locator(
+ `[data-editor-pane-focused] [data-editor-tab-sortable][data-editor-tab-id="${docName}"]`,
+ );
+ if ((await tab.getAttribute('data-preview-tab')) === 'true') {
+ await tab.click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-keep-open').click();
+ }
+}
+
+async function dragTabToRightEdge(page: Page, tab: Locator, paneId: string) {
+ const tabBox = await tab.boundingBox();
+ if (!tabBox) throw new Error('tab has no box');
+ await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(tabBox.x + tabBox.width / 2 + 12, tabBox.y + tabBox.height / 2, {
+ steps: 2,
+ });
+ const edge = page.locator(`section[data-editor-pane-id="${paneId}"] [data-pane-edge="right"]`);
+ await expect(edge).toBeAttached();
+ const edgeBox = await edge.boundingBox();
+ if (!edgeBox) throw new Error('pane edge has no box');
+ await page.mouse.move(edgeBox.x + edgeBox.width / 2, edgeBox.y + edgeBox.height / 2, {
+ steps: 8,
+ });
+ await expect(edge).toHaveAttribute('data-pane-drop-side', 'right');
+ await page.mouse.up();
+}
+
+async function fullCycle(page: Page, docName: string, paneNumber: number) {
+ await page.setViewportSize({ width: 390, height: 800 });
+ const selector = page.getByRole('combobox', { name: 'Editor pane' });
+ await expect(selector).toBeVisible();
+ await selector.click();
+ await page.getByRole('option', { name: `Pane ${paneNumber}` }).click();
+ await expect(
+ page.locator(`[data-editor-activity-mount][data-doc-name="${docName}"]`),
+ ).toBeVisible();
+ await page.locator('[data-sidebar="trigger"]').click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+Alt+KeyB');
+ await expect(page.locator('[data-doc-panel-cover]')).toBeVisible();
+ await page.locator('[data-doc-panel-back]').click();
+ await expect(page.locator('[data-doc-panel-cover]')).toHaveCount(0);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await expect(paneTabs(page)).toHaveCount(4);
+ await expect(page.locator('#doc-panel')).toBeVisible();
+}
+
+async function verifyFileHostMovement(page: Page) {
+ const host = await page.locator('[data-file-list-host]').elementHandle();
+ if (!host) throw new Error('Files host is missing');
+ try {
+ await page.setViewportSize({ width: 390, height: 800 });
+ await expect(page.locator('[data-editor-file-list-slot] [data-file-list-host]')).toHaveCount(1);
+ await page.locator('[data-sidebar="trigger"]').click();
+ await expect(page.locator('[data-files-cover]')).toBeVisible();
+ await expect
+ .poll(() =>
+ host.evaluate(
+ (element) =>
+ element.isConnected &&
+ element === document.querySelector('[data-files-cover] [data-file-list-host]'),
+ ),
+ )
+ .toBe(true);
+ await page.locator('[data-files-back]').click();
+ await expect(page.locator('[data-files-cover]')).toHaveCount(0);
+ await expect
+ .poll(() =>
+ host.evaluate(
+ (element) =>
+ element.isConnected &&
+ element ===
+ document.querySelector('[data-editor-file-list-slot] [data-file-list-host]'),
+ ),
+ )
+ .toBe(true);
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ } finally {
+ await host.dispose();
+ }
+}
+
+async function verifyDestinationBranches(page: Page, docName: string, heading: string) {
+ const editor = page.locator(
+ `[data-editor-activity-mount][data-doc-name="${docName}"] .ProseMirror[contenteditable="true"]`,
+ );
+ await test.step('closed cover leaves the visible destination and outline focus intact', async () => {
+ const outlineButton = page.locator('#panel-outline').getByRole('button', {
+ name: heading,
+ exact: true,
+ });
+ await expect(outlineButton).toBeVisible();
+ await outlineButton.click();
+ await expect(page.locator('[data-doc-panel-cover]')).toHaveCount(0);
+ await expect(editor).toBeVisible();
+ await expect(outlineButton).toBeFocused();
+ });
+
+ await test.step('open cover closes and focuses the visible destination', async () => {
+ await page.setViewportSize({ width: 390, height: 800 });
+ await page.locator('[data-doc-panel-toggle]').click();
+ const cover = page.locator('[data-doc-panel-cover]');
+ await expect(cover).toBeVisible();
+ await cover.getByRole('button', { name: heading, exact: true }).click();
+ await expect(cover).toHaveCount(0);
+ await expect(editor).toBeVisible();
+ await expect(editor).toBeFocused();
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await expect(page.locator('#doc-panel')).toBeVisible();
+ });
+}
+
+const APP_DIST = join(dirname(fileURLToPath(import.meta.url)), '../../dist');
+
+test.use({ video: 'off', trace: 'off', workerServerEnv: { OK_TEST_PRODUCTION_SHELL: '1' } });
+
+test('responsive cycles release prior editor callback contexts', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ test.setTimeout(240_000);
+ expect(workerServer.launch?.mode).toBe('production');
+ expect(workerServer.launch?.command).toBe(process.execPath);
+ expect(workerServer.launch?.args.slice(1, 2)).toEqual(['start']);
+ expect(workerServer.launch?.args).toContain(APP_DIST);
+ const servedIndex = await (await fetch(`${workerServer.baseURL}/`)).text();
+ const entry = /<script[^>]+type="module"[^>]+src="\.?\/(assets\/[^"]+\.js)"/.exec(
+ servedIndex,
+ )?.[1];
+ if (!entry) throw new Error('production index served no hashed module entry');
+ expect(readFileSync(join(APP_DIST, 'index.html'), 'utf8')).toContain(entry);
+ const servedEntry = Buffer.from(
+ await (await fetch(`${workerServer.baseURL}/${entry}`)).arrayBuffer(),
+ );
+ expect(createHash('sha256').update(servedEntry).digest('hex')).toBe(
+ createHash('sha256')
+ .update(readFileSync(join(APP_DIST, entry)))
+ .digest('hex'),
+ );
+ expect(relative(tmpdir(), workerServer.contentDir).startsWith('..')).toBe(false);
+ const suffix = randomUUID().slice(0, 8);
+ const docs = labels.map((label) => ({
+ name: `qa101-context-${label}-${suffix}`,
+ markdown: `# ${label}-${suffix}\n\n${label} retained body\n`,
+ body: `${label} retained body`,
+ }));
+ const firstDoc = docs.at(0);
+ if (!firstDoc) throw new Error('missing first document');
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ for (const doc of docs) await api.createPage(`${doc.name}.md`);
+ for (const doc of docs) await api.replaceDoc(doc.name, doc.markdown);
+ await expect
+ .poll(() => docs.every((doc) => existsSync(join(workerServer.contentDir, `${doc.name}.md`))))
+ .toBe(true);
+
+ await page.setViewportSize({ width: 2400, height: 900 });
+ await page.goto(`/#/${firstDoc.name}`);
+ await expect(
+ page.locator(`[data-editor-activity-mount][data-doc-name="${firstDoc.name}"]`),
+ ).toContainText(firstDoc.body);
+ for (const doc of docs.slice(1)) {
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, doc.name, doc.body);
+ const ids = await paneTabs(page).evaluateAll((strips) =>
+ strips.map((strip) => strip.getAttribute('data-editor-pane-tabs')).filter((id) => id != null),
+ );
+ const paneId = ids.at(-1);
+ if (!paneId) throw new Error('focused pane is missing');
+ const tab = page.locator(
+ `[data-editor-pane-tabs="${paneId}"] [data-editor-tab-sortable][data-editor-tab-id="${doc.name}"]`,
+ );
+ await dragTabToRightEdge(page, tab, paneId);
+ await expect(paneTabs(page)).toHaveCount(ids.length + 1);
+ }
+ await expect(page.locator('[data-editor-activity-mount]')).toHaveCount(4);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toHaveCount(4);
+ await test.step('Files host survives cover movement', () => verifyFileHostMovement(page));
+ const lastDoc = docs.at(-1);
+ if (!lastDoc) throw new Error('missing last document');
+ await verifyDestinationBranches(page, lastDoc.name, `delta-${suffix}`);
+
+ const cdp = await page.context().newCDPSession(page);
+ try {
+ for (let cycle = 0; cycle < 4; cycle++) {
+ const doc = docs[cycle % docs.length];
+ if (!doc) throw new Error('missing cycle document');
+ await fullCycle(page, doc.name, (cycle % docs.length) + 1);
+ }
+ await page.evaluate(() => performance.clearMeasures());
+ await expect(page.locator('[data-editor-file-list-slot]')).toHaveCount(1);
+ const before = await snapshotDepth(
+ cdp,
+ test.info().outputPath('context-before.heapsnapshot'),
+ docs.map((doc) => doc.name),
+ );
+ for (let cycle = 4; cycle < 20; cycle++) {
+ const doc = docs[cycle % docs.length];
+ if (!doc) throw new Error('missing cycle document');
+ await fullCycle(page, doc.name, (cycle % docs.length) + 1);
+ }
+ await page.evaluate(() => performance.clearMeasures());
+ await expect(page.locator('[data-editor-activity-mount]')).toHaveCount(4);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toHaveCount(4);
+ await expect(page.locator('[data-editor-file-list-slot]')).toHaveCount(1);
+ const after = await snapshotDepth(
+ cdp,
+ test.info().outputPath('context-after.heapsnapshot'),
+ docs.map((doc) => doc.name),
+ );
+ const evidencePath = test.info().outputPath('context-retention.json');
+ writeFileSync(
+ evidencePath,
+ JSON.stringify({ before, after, cyclesBetween: 16, pageErrors }, null, 2),
+ );
+ await test.info().attach('context-retention.json', {
+ path: evidencePath,
+ contentType: 'application/json',
+ });
+ expect(pageErrors).toEqual([]);
+ 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)
+ .toBeLessThanOrEqual(8);
+ expect
+ .soft(after.editorAreaDestination.maxDepth - before.editorAreaDestination.maxDepth)
+ .toBeLessThanOrEqual(8);
+ expect
+ .soft(after.appMainEffect.maxDepth - before.appMainEffect.maxDepth)
+ .toBeLessThanOrEqual(8);
+ } finally {
+ await cdp.detach();
+ }
+});
diff --git a/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts b/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts
index 608350128..8bb5b344c 100644
--- a/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts
+++ b/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts
@@ -5,6 +5,7 @@ import type { Page } from '@playwright/test';
import { EDITOR_BUBBLE_MENU_KEY } from '../../src/editor/bubble-menu/bubble-menu-key';
import {
type ApiHelpers,
+ acpCatalogBody,
blockMarker,
expect,
generateTallDoc,
@@ -404,6 +405,9 @@ function expectPluginAgreesWithLoop(
).toBeLessThanOrEqual(1);
}
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
test('bubble bar stays in the pane when a tall selection scrolls behind the toolbar', async ({
page,
api,
diff --git a/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts b/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts
index 83265bcf3..1b574e3fb 100644
--- a/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts
+++ b/packages/app/tests/stress/sidebar-file-list-fills.e2e.ts
@@ -4,6 +4,7 @@ import { expect, resetContentToFixtureBaseline, test } from './_helpers';
const SIDEBAR = '[data-slot="sidebar-container"]';
const FOOTER = '[data-slot="sidebar-footer"]';
+const BODY = '[data-slot="sidebar-content"]';
const TREE_SCROLL =
'[data-slot="sidebar-group"] [data-slot="collapsible-content"] [data-file-tree-virtualized-scroll]';
@@ -45,7 +46,7 @@ test.describe('sidebar file list fills the body', () => {
const scroll = await boxOf(page, TREE_SCROLL);
const dockCount = await page.getByTestId('skills-dock').count();
- const below = await boxOf(page, dockCount > 0 ? '[data-testid="skills-dock"]' : FOOTER);
+ const below = await boxOf(page, dockCount > 0 ? '[data-testid="skills-dock"]' : BODY);
expect(below.y - (scroll.y + scroll.height)).toBeLessThan(ROW_HEIGHT);
const slack = scroll.y + scroll.height - (await lowestRowBottom(page));
@@ -73,8 +74,8 @@ test.describe('sidebar file list fills the body', () => {
}).toPass({ timeout: 15_000 });
const scroll = await boxOf(page, TREE_SCROLL);
- const footer = await boxOf(page, FOOTER);
- expect(scroll.y + scroll.height).toBeLessThanOrEqual(footer.y + 1);
+ const body = await boxOf(page, BODY);
+ expect(scroll.y + scroll.height).toBeLessThanOrEqual(body.y + body.height + 1);
});
test('a tall Conflicts section cannot squeeze the file list away', async ({ page, api }) => {
@@ -110,6 +111,56 @@ test.describe('sidebar file list fills the body', () => {
}).toPass({ timeout: 15_000 });
});
+ test('an empty footer takes no room below the Skills dock', async ({ page, api }) => {
+ await api.seedDocs([{ name: 'folder/note', markdown: '# Note\n' }]);
+ await page.goto('/#/folder/note');
+ await expect(page.locator(SIDEBAR).getByRole('treeitem', { name: 'note.md' })).toBeVisible({
+ timeout: 20_000,
+ });
+
+ const footer = page.locator(FOOTER);
+ await expect(footer).toHaveCount(1);
+ expect(await footer.evaluate((el) => el.childElementCount)).toBe(0);
+ await expect(footer).toBeHidden();
+ const body = await boxOf(page, BODY);
+ const inner = await boxOf(page, '[data-slot="sidebar-inner"]');
+ expect(Math.abs(inner.y + inner.height - (body.y + body.height))).toBeLessThanOrEqual(1);
+ });
+
+ test('a saved Skills dock taller than the room left fits on screen and keeps its saved height', async ({
+ page,
+ api,
+ }) => {
+ const savedHeight = '560';
+ await page.addInitScript((height: string) => {
+ localStorage.setItem('ok-skills-dock-expanded-v1', 'true');
+ localStorage.setItem('ok-skills-dock-height-v1', height);
+ }, savedHeight);
+ await page.setViewportSize({ width: 1280, height: 700 });
+ await api.seedDocs([{ name: 'folder/note', markdown: '# Note\n' }]);
+ await page.goto('/#/folder/note');
+ await expect(page.locator(SIDEBAR).getByRole('treeitem', { name: 'note.md' })).toBeVisible({
+ timeout: 20_000,
+ });
+ const dock = page.getByTestId('skills-dock');
+ await expect(dock.getByTestId('skills-dock-resize')).toBeVisible({ timeout: 10_000 });
+
+ await expect(async () => {
+ const body = await boxOf(page, '[data-slot="sidebar-content"]');
+ const dockBox = await boxOf(page, '[data-testid="skills-dock"]');
+ expect(dockBox.y + dockBox.height).toBeLessThanOrEqual(body.y + body.height + 1);
+ const bodyScrolls = await page
+ .locator('[data-slot="sidebar-content"]')
+ .evaluate((el) => el.scrollHeight > el.clientHeight + 1);
+ expect(bodyScrolls).toBe(false);
+ }).toPass({ timeout: 15_000 });
+ const files = await boxOf(page, '[data-slot="sidebar-content"] > .group\\/files');
+ expect(files.height).toBeGreaterThanOrEqual(192 - 1);
+ expect(await page.evaluate(() => localStorage.getItem('ok-skills-dock-height-v1'))).toBe(
+ savedHeight,
+ );
+ });
+
test('a round trip through Skills mode leaves the file list correctly sized', async ({
page,
api,
diff --git a/packages/app/tests/stress/text-doc-composer-inset.e2e.ts b/packages/app/tests/stress/text-doc-composer-inset.e2e.ts
index 6784bab7d..5a5021231 100644
--- a/packages/app/tests/stress/text-doc-composer-inset.e2e.ts
+++ b/packages/app/tests/stress/text-doc-composer-inset.e2e.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { expect, test } from './_helpers';
+import { acpCatalogBody, expect, test } from './_helpers';
const TEXT_DOC = '[data-text-doc-editor]';
const CM_CONTENT = `${TEXT_DOC} .cm-content`;
@@ -11,6 +11,9 @@ const COMPOSER_CARD = `${COMPOSER} > div`;
const LINE_COUNT = 400;
+test.beforeEach(async ({ page }) => {
+ await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
+});
test.describe('editable text doc reserves the Ask AI composer height', () => {
test('the last line of a code file scrolls clear of the composer card', async ({
page,
diff --git a/packages/app/tests/stress/theme-fade.e2e.ts b/packages/app/tests/stress/theme-fade.e2e.ts
index 09d4482d6..1a9f7d793 100644
--- a/packages/app/tests/stress/theme-fade.e2e.ts
+++ b/packages/app/tests/stress/theme-fade.e2e.ts
@@ -309,7 +309,7 @@ test('default light and dark modes fade surfaces without losing selection', asyn
`the settled surface equals the light one — the mode never switched.${detail}`,
).not.toBe(fade.beforeClick.body);
expect(fade.afterSettle.sidebar, `the settled token is not dark --sidebar.${detail}`).toBe(
- 'oklch(0.205 0 0)',
+ 'oklch(0.21 0 0)',
);
expect(
fade.connected,
diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.json
index 24e89a8be..568c2a1d5 100644
--- a/packages/app/tsconfig.json
+++ b/packages/app/tsconfig.json
@@ -91,11 +91,15 @@
"tests/stress/_helpers/acp-catalog.ts",
"tests/stress/_helpers/assertion-timeout",
"tests/stress/_helpers/boot-verdict",
+ "tests/stress/_helpers/card-surface.ts",
+ "tests/stress/_helpers/corner-stack.ts",
"tests/stress/_helpers/editor-state.ts",
+ "tests/stress/_helpers/feedback-nudge.ts",
"tests/stress/_helpers/image.ts",
"tests/stress/_helpers/loop-markers.ts",
"tests/stress/_helpers/prebuilt",
"tests/stress/_helpers/reuse",
+ "tests/stress/_helpers/subscribe-card.ts",
"tests/stress/_helpers/theme-fade.ts"
],
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.test.tsx"]
diff --git a/packages/app/uninstall.html b/packages/app/uninstall.html
index 0610c7d3c..c0c02bb6f 100644
--- a/packages/app/uninstall.html
+++ b/packages/app/uninstall.html
@@ -23,15 +23,10 @@
-->
<script>(() => { try { if (new URLSearchParams(location.search).get('theme') === 'dark') document.documentElement.classList.add('dark'); } catch {} })();</script>
<!--
- Paints the window background from the same `--sidebar` token the app chrome
- uses, so the frame between window-show and React's first paint isn't a
- white flash. Placeholders are substituted at build time by
- chromeTokensVitePlugin (same plugin, same values as index.html).
-
Single-line style body — same biome HTML-formatter constraint as the
script above.
-->
- <style>html { background-color: __OK_CHROME_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style>
+ <style>html { background-color: __OK_SIDEBAR_BG_LIGHT__ } html.dark { background-color: __OK_CANVAS_BG_DARK__ }</style>
</head>
<body class="antialiased">
diff --git a/packages/core/scripts/chrome-resolver.ts b/packages/core/scripts/chrome-resolver.ts
index f6f2a8911..31c5104ef 100644
--- a/packages/core/scripts/chrome-resolver.ts
+++ b/packages/core/scripts/chrome-resolver.ts
@@ -1,35 +1,14 @@
-/**
- * Resolve the `--sidebar` Tailwind v4 token from `packages/app/src/globals.css`
- * to sRGB hex strings. Single source of truth for desktop chrome background:
- *
- * - `packages/core/src/constants/chrome.ts` (regenerated by
- * `scripts/generate-chrome-tokens.ts`)
- * - `packages/app/index.html` inline `<style>` (placeholders substituted at
- * build time by `packages/app/src/build/chrome-tokens-vite-plugin.ts`)
- *
- * Drift between the parsed CSS and the committed `chrome.ts` constants is
- * caught by `packages/core/src/constants/chrome.uncached.test.ts`.
- *
- * Node-only — uses `node:fs` and the `culori` colorspace converter.
- */
import { readFileSync } from 'node:fs';
-import { formatHex, parse as parseColor } from 'culori';
+import { converter, formatHex, parse as parseColor } from 'culori';
export interface ChromeTokens {
- /** sRGB hex string for the light-mode chrome background (e.g. `#fafafa`). */
light: string;
- /** sRGB hex string for the dark-mode chrome background (e.g. `#171717`). */
+ lightSidebar: string;
dark: string;
+ darkSidebar: string;
+ darkCanvas: string;
}
-/**
- * Match `--sidebar: <value>;` inside a CSS block. The block matchers below
- * scope the search to `:root { ... }` (light) and `.dark { ... }` (dark)
- * blocks that contain a `--sidebar` declaration — a `.dark .descendant`
- * selector or a `:root` block that doesn't carry `--sidebar` is skipped.
- */
-const SIDEBAR_DECL_RE = /--sidebar:\s*([^;]+);/;
-
/**
* Find every top-level block matching the given selector exactly (e.g.
* `:root` matches `:root {` but not `:root .foo {`; `.dark` matches `.dark {`
@@ -72,15 +51,16 @@ export function findBlockBodies(css: string, selector: string): string[] {
return bodies;
}
-function extractSidebarValue(css: string, selector: string): string {
+function extractTokenValue(css: string, selector: string, token: string): string {
const bodies = findBlockBodies(css, selector);
+ const declaration = new RegExp(`--${token}:\\s*([^;]+);`);
for (const body of bodies) {
- const decl = body.match(SIDEBAR_DECL_RE);
+ const decl = body.match(declaration);
if (decl && decl[1] !== undefined) {
return decl[1].trim();
}
}
- throw new Error(`chrome-resolver: --sidebar declaration not found in any ${selector} block`);
+ throw new Error(`chrome-resolver: --${token} declaration not found in any ${selector} block`);
}
function resolveToHex(cssColor: string, label: string): string {
@@ -95,44 +75,68 @@ function resolveToHex(cssColor: string, label: string): string {
return hex;
}
-/**
- * Parse `--sidebar` from `:root` (light) and `.dark` blocks of the given CSS
- * file and resolve both to sRGB hex via culori.
- *
- * Throws on missing selector, missing declaration, unbalanced braces, or
- * unparseable color value. Callers handle once at build time — if any of
- * these fail, the build is the right thing to fail.
- */
+const SIDEBAR_LIGHTNESS_OFFSET = /^oklch\(from var\(--sidebar\) calc\(l - (\d*\.?\d+)\) c h\)$/;
+
+const toOklch = converter('oklch');
+
+function resolveSidebarOffsetToHex(
+ offsetValue: string,
+ sidebarValue: string,
+ label: string,
+): string {
+ const offset = offsetValue.match(SIDEBAR_LIGHTNESS_OFFSET)?.[1];
+ if (offset === undefined) {
+ throw new Error(
+ `chrome-resolver: ${label} must be oklch(from var(--sidebar) calc(l - <n>) c h), got: ${offsetValue}`,
+ );
+ }
+ const sidebar = parseColor(sidebarValue);
+ if (sidebar === undefined) {
+ throw new Error(
+ `chrome-resolver: culori failed to parse ${label} base --sidebar: ${sidebarValue}`,
+ );
+ }
+ const base = toOklch(sidebar);
+ const hex = formatHex({ ...base, l: base.l - Number(offset) });
+ if (hex === undefined) {
+ throw new Error(
+ `chrome-resolver: culori failed to convert ${label} to sRGB hex: ${offsetValue}`,
+ );
+ }
+ return hex;
+}
+
export function resolveChromeTokensFromCss(cssPath: string): ChromeTokens {
const css = readFileSync(cssPath, 'utf8');
- const lightValue = extractSidebarValue(css, ':root');
- const darkValue = extractSidebarValue(css, '.dark');
+ const lightSidebarValue = extractTokenValue(css, ':root', 'sidebar');
+ const lightDeskValue = extractTokenValue(css, ':root', 'desk');
+ const darkValue = extractTokenValue(css, 'html.dark:not([data-color-theme])', 'desk');
+ const darkSidebarValue = extractTokenValue(css, '.dark', 'sidebar');
+ const darkCanvasValue = extractTokenValue(css, '.dark', 'background');
return {
- light: resolveToHex(lightValue, 'light'),
+ light: resolveSidebarOffsetToHex(lightDeskValue, lightSidebarValue, 'light :root --desk'),
+ lightSidebar: resolveToHex(lightSidebarValue, 'light sidebar'),
dark: resolveToHex(darkValue, 'dark'),
+ darkSidebar: resolveToHex(darkSidebarValue, 'dark sidebar'),
+ darkCanvas: resolveToHex(darkCanvasValue, 'dark canvas'),
};
}
-/**
- * Render the resolved tokens as a TypeScript module body. Output stays byte-
- * stable so the regen script and the drift test can both anchor on it.
- */
export function renderChromeConstantsModule(tokens: ChromeTokens): string {
- return `/**
- * Chrome background sRGB hex constants. Regenerated by
- * \`packages/core/scripts/generate-chrome-tokens.ts\` from the
- * \`--sidebar\` Tailwind token in \`packages/app/src/globals.css\`. Drift
- * between this file and the CSS is caught by \`chrome.uncached.test.ts\`.
- *
- * Consumers:
- * - \`packages/app/index.html\` inline <style> (Vite plugin substitutes
- * placeholders at build time)
- * - \`packages/desktop/src/main/index.ts\` BrowserWindow chrome
- *
- * Do NOT hand-edit. Run \`bun run packages/core/scripts/generate-chrome-tokens.ts\`
- * after changing \`--sidebar\` in globals.css.
- */
-export const CHROME_BG_LIGHT = '${tokens.light}' as const;
+ return `export const CHROME_BG_LIGHT = '${tokens.light}' as const;
export const CHROME_BG_DARK = '${tokens.dark}' as const;
+export const SIDEBAR_BG_LIGHT = '${tokens.lightSidebar}' as const;
+export const SIDEBAR_BG_DARK = '${tokens.darkSidebar}' as const;
+export const CANVAS_BG_DARK = '${tokens.darkCanvas}' as const;
+
+const ROOT_FONT_SIZE_PX = 16;
+
+export const APP_HEADER_HEIGHT_PX = 44;
+
+export const APP_HEADER_HEIGHT = \`\${APP_HEADER_HEIGHT_PX / ROOT_FONT_SIZE_PX}rem\`;
+
+export const REDUCED_CHROME_HEADER_HEIGHT_PX = 48;
+
+export const REDUCED_CHROME_HEADER_HEIGHT = \`\${REDUCED_CHROME_HEADER_HEIGHT_PX / ROOT_FONT_SIZE_PX}rem\`;
`;
}
diff --git a/packages/core/scripts/generate-chrome-tokens.ts b/packages/core/scripts/generate-chrome-tokens.ts
index f7f444758..b97998a3c 100644
--- a/packages/core/scripts/generate-chrome-tokens.ts
+++ b/packages/core/scripts/generate-chrome-tokens.ts
@@ -1,14 +1,3 @@
-/**
- * One-shot regenerator for `src/constants/chrome.ts`. Reads `--sidebar` from
- * `packages/app/src/globals.css`, resolves OKLCH→sRGB via culori, writes the
- * constants module verbatim. Run via:
- *
- * bun run packages/core/scripts/generate-chrome-tokens.ts
- *
- * After running, diff the output — landing it should only flip values when
- * `--sidebar` itself moved. The drift test in
- * `packages/core/src/constants/chrome.uncached.test.ts` enforces parity at CI time.
- */
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -24,3 +13,6 @@ writeFileSync(OUTPUT, moduleBody, 'utf8');
console.log(`chrome-tokens: wrote ${OUTPUT}`);
console.log(` CHROME_BG_LIGHT = ${tokens.light}`);
console.log(` CHROME_BG_DARK = ${tokens.dark}`);
+console.log(` SIDEBAR_BG_LIGHT = ${tokens.lightSidebar}`);
+console.log(` SIDEBAR_BG_DARK = ${tokens.darkSidebar}`);
+console.log(` CANVAS_BG_DARK = ${tokens.darkCanvas}`);
diff --git a/packages/core/src/commands/command-identity.ts b/packages/core/src/commands/command-identity.ts
index e679f12aa..e92ae6c57 100644
--- a/packages/core/src/commands/command-identity.ts
+++ b/packages/core/src/commands/command-identity.ts
@@ -93,7 +93,8 @@ export interface CommandStateToggle {
| 'sidebarVisible'
| 'docPanelVisible'
| 'terminalVisible'
- | 'agentPanelVisible';
+ | 'agentPanelVisible'
+ | 'editorVisible';
readonly defaultVisible: boolean;
readonly overrideKey?: MenuLabelKey;
readonly overrideField?: 'hasEditorSelection';
@@ -474,6 +475,21 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
palette: { group: 'view', visibility: 'search-only' },
menu: [{ section: 'view-panels', order: 1, accelerator: 'CmdOrCtrl+Alt+B' }],
},
+ {
+ id: 'toggle-editor',
+ menuActionId: 'toggle-editor',
+ labelKey: 'editorShow',
+ keywords: ['editor', 'document', 'pane', 'panel', 'show editor', 'hide editor'],
+ stateToggle: {
+ showKey: 'editorShow',
+ hideKey: 'editorHide',
+ stateField: 'editorVisible',
+ defaultVisible: true,
+ },
+ availability: { singleFileHidden: true },
+ palette: { group: 'view', visibility: 'search-only' },
+ menu: [{ section: 'view-panels', order: 2 }],
+ },
{
id: 'toggle-terminal',
menuActionId: 'toggle-terminal',
@@ -499,7 +515,7 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
},
availability: { host: 'desktop', requiresTerminalCapability: true },
palette: { group: 'view', visibility: 'search-only' },
- menu: [{ section: 'view-panels', order: 2, accelerator: 'CmdOrCtrl+J' }],
+ menu: [{ section: 'view-panels', order: 3, accelerator: 'CmdOrCtrl+J' }],
},
{
id: 'toggle-agent-panel',
@@ -517,7 +533,7 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
},
availability: {},
palette: { group: 'view', visibility: 'search-only' },
- menu: [{ section: 'view-panels', order: 3, accelerator: 'CmdOrCtrl+L' }],
+ menu: [{ section: 'view-panels', order: 4, accelerator: 'CmdOrCtrl+L' }],
},
{
id: 'toggle-show-hidden-files',
diff --git a/packages/core/src/constants/chrome.ts b/packages/core/src/constants/chrome.ts
index 69c2d9f20..691dce73a 100644
--- a/packages/core/src/constants/chrome.ts
+++ b/packages/core/src/constants/chrome.ts
@@ -1,2 +1,15 @@
-export const CHROME_BG_LIGHT = '#fafafa' as const;
-export const CHROME_BG_DARK = '#171717' as const;
+export const CHROME_BG_LIGHT = '#f5f5f5' as const;
+export const CHROME_BG_DARK = '#292929' as const;
+export const SIDEBAR_BG_LIGHT = '#fafafa' as const;
+export const SIDEBAR_BG_DARK = '#181818' as const;
+export const CANVAS_BG_DARK = '#151515' as const;
+
+const ROOT_FONT_SIZE_PX = 16;
+
+export const APP_HEADER_HEIGHT_PX = 44;
+
+export const APP_HEADER_HEIGHT = `${APP_HEADER_HEIGHT_PX / ROOT_FONT_SIZE_PX}rem`;
+
+export const REDUCED_CHROME_HEADER_HEIGHT_PX = 48;
+
+export const REDUCED_CHROME_HEADER_HEIGHT = `${REDUCED_CHROME_HEADER_HEIGHT_PX / ROOT_FONT_SIZE_PX}rem`;
diff --git a/packages/core/src/constants/chrome.uncached.test.ts b/packages/core/src/constants/chrome.uncached.test.ts
index 8525bf60c..b985058e0 100644
--- a/packages/core/src/constants/chrome.uncached.test.ts
+++ b/packages/core/src/constants/chrome.uncached.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -7,7 +7,13 @@ import {
renderChromeConstantsModule,
resolveChromeTokensFromCss,
} from '../../scripts/chrome-resolver.ts';
-import { CHROME_BG_DARK, CHROME_BG_LIGHT } from './chrome.ts';
+import {
+ CANVAS_BG_DARK,
+ CHROME_BG_DARK,
+ CHROME_BG_LIGHT,
+ SIDEBAR_BG_DARK,
+ SIDEBAR_BG_LIGHT,
+} from './chrome.ts';
const HERE = dirname(fileURLToPath(import.meta.url));
const GLOBALS_CSS = resolve(HERE, '../../../app/src/globals.css');
@@ -15,17 +21,34 @@ const GLOBALS_CSS = resolve(HERE, '../../../app/src/globals.css');
describe('chrome.ts drift-check', () => {
const tokens = resolveChromeTokensFromCss(GLOBALS_CSS);
- test('CHROME_BG_LIGHT matches resolved --sidebar from :root', () => {
+ test('CHROME_BG_LIGHT matches the light --desk derived from :root --sidebar', () => {
expect(CHROME_BG_LIGHT).toBe(tokens.light);
+ expect(tokens.light).toBe('#f5f5f5');
+ });
+
+ test('SIDEBAR_BG_LIGHT matches resolved --sidebar from :root', () => {
+ expect(SIDEBAR_BG_LIGHT).toBe(tokens.lightSidebar);
+ expect(tokens.lightSidebar).toBe('#fafafa');
});
- test('CHROME_BG_DARK matches resolved --sidebar from .dark', () => {
+ test('CHROME_BG_DARK matches the default dark --desk', () => {
expect(CHROME_BG_DARK).toBe(tokens.dark);
});
+ test('SIDEBAR_BG_DARK matches resolved --sidebar from .dark', () => {
+ expect(SIDEBAR_BG_DARK).toBe(tokens.darkSidebar);
+ });
+
+ test('CANVAS_BG_DARK matches resolved --background from .dark', () => {
+ expect(CANVAS_BG_DARK).toBe(tokens.darkCanvas);
+ });
+
test('hex values are sRGB 6-digit lowercase format', () => {
expect(CHROME_BG_LIGHT).toMatch(/^#[0-9a-f]{6}$/);
+ expect(SIDEBAR_BG_LIGHT).toMatch(/^#[0-9a-f]{6}$/);
expect(CHROME_BG_DARK).toMatch(/^#[0-9a-f]{6}$/);
+ expect(SIDEBAR_BG_DARK).toMatch(/^#[0-9a-f]{6}$/);
+ expect(CANVAS_BG_DARK).toMatch(/^#[0-9a-f]{6}$/);
});
test('chrome constants are visually distinct (light != dark)', () => {
@@ -36,6 +59,17 @@ describe('chrome.ts drift-check', () => {
const body = renderChromeConstantsModule(tokens);
expect(body).toContain(`CHROME_BG_LIGHT = '${tokens.light}'`);
expect(body).toContain(`CHROME_BG_DARK = '${tokens.dark}'`);
+ expect(body).toContain(`SIDEBAR_BG_LIGHT = '${tokens.lightSidebar}'`);
+ expect(body).toContain(`SIDEBAR_BG_DARK = '${tokens.darkSidebar}'`);
+ expect(body).toContain(`CANVAS_BG_DARK = '${tokens.darkCanvas}'`);
+ expect(body).toContain('export const APP_HEADER_HEIGHT_PX = 44;');
+ expect(body).toContain('export const REDUCED_CHROME_HEADER_HEIGHT_PX = 48;');
+ });
+
+ test('the checked-in chrome.ts is exactly what the generator renders', () => {
+ expect(readFileSync(resolve(HERE, 'chrome.ts'), 'utf8')).toBe(
+ renderChromeConstantsModule(tokens),
+ );
});
});
@@ -47,6 +81,7 @@ describe('chrome-resolver: selector matching is exact (not wildcard)', () => {
const cssPath = join(tmpDir, 'globals.css');
const css = `
:root {
+ --desk: oklch(from var(--sidebar) calc(l - 0.015) c h);
--sidebar: oklch(0.985 0 0);
}
@@ -54,15 +89,57 @@ Xdark {
--sidebar: oklch(0.5 0 0);
}
+htmlXdark:not([data-color-theme]) {
+ --desk: oklch(0.5 0 0);
+}
+
.dark {
+ --background: oklch(0.195 0 0);
--sidebar: oklch(0.205 0 0);
}
+
+html.dark:not([data-color-theme]) {
+ --desk: oklch(0.28 0 0);
+}
`;
writeFileSync(cssPath, css, 'utf8');
try {
const tokens = resolveChromeTokensFromCss(cssPath);
- expect(tokens.light).toBe('#fafafa');
- expect(tokens.dark).toBe('#171717');
+ expect(tokens.light).toBe('#f5f5f5');
+ expect(tokens.lightSidebar).toBe('#fafafa');
+ expect(tokens.dark).toBe('#292929');
+ expect(tokens.darkSidebar).toBe('#171717');
+ expect(tokens.darkCanvas).toBe('#151515');
+ } finally {
+ rmSync(tmpDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('chrome-resolver: light --desk shape', () => {
+ test('a :root --desk that is not a lightness offset from --sidebar is rejected', () => {
+ const tmpDir = mkdtempSync(join(tmpdir(), 'chrome-resolver-test-'));
+ const cssPath = join(tmpDir, 'globals.css');
+ writeFileSync(
+ cssPath,
+ `:root {
+ --desk: oklch(from var(--sidebar) l c h / 0.5);
+ --sidebar: oklch(0.985 0 0);
+}
+
+.dark {
+ --background: oklch(0.195 0 0);
+ --sidebar: oklch(0.205 0 0);
+}
+
+html.dark:not([data-color-theme]) {
+ --desk: oklch(0.28 0 0);
+}
+`,
+ 'utf8',
+ );
+ try {
+ expect(() => resolveChromeTokensFromCss(cssPath)).toThrow(/--desk/);
} finally {
rmSync(tmpDir, { recursive: true, force: true });
}
diff --git a/packages/core/src/constants/menu-labels.ts b/packages/core/src/constants/menu-labels.ts
index 15f17b3b2..79a1337c5 100644
--- a/packages/core/src/constants/menu-labels.ts
+++ b/packages/core/src/constants/menu-labels.ts
@@ -55,6 +55,8 @@ export const MENU_LABELS = {
terminalHide: 'Hide Terminal',
terminalMoveRight: 'Move Terminal to right',
terminalMoveBottom: 'Move Terminal to bottom',
+ editorShow: 'Show Editor',
+ editorHide: 'Hide Editor',
agentPanelShow: 'Show Agents',
agentPanelHide: 'Hide Agents',
agentPanelAskSelection: 'Ask AI About Selection',
diff --git a/packages/core/src/constants/preview-theme-tokens.ts b/packages/core/src/constants/preview-theme-tokens.ts
index 40a90ba5d..31c9c4e69 100644
--- a/packages/core/src/constants/preview-theme-tokens.ts
+++ b/packages/core/src/constants/preview-theme-tokens.ts
@@ -13,8 +13,8 @@ export const PREVIEW_THEME_TOKENS: readonly PreviewThemeToken[] = [
{ name: '--primary', light: 'oklch(0.5621 0.1983 259.59)', dark: '#69a3ff' },
{ name: '--primary-foreground', light: 'oklch(0.985 0 0)', dark: 'oklch(0.205 0 0)' },
{ name: '--foreground', light: 'oklch(0.145 0 0)', dark: 'oklch(0.985 0 0)' },
- { name: '--background', light: 'oklch(1 0 0)', dark: 'oklch(0.145 0 0)' },
- { name: '--card', light: 'oklch(1 0 0)', dark: 'oklch(0.205 0 0)' },
+ { name: '--background', light: 'oklch(1 0 0)', dark: 'oklch(0.195 0 0)' },
+ { name: '--card', light: 'oklch(1 0 0)', dark: 'oklch(0.245 0 0)' },
{ name: '--card-foreground', light: 'oklch(0.145 0 0)', dark: 'oklch(0.985 0 0)' },
{ name: '--muted-foreground', light: 'oklch(0.556 0 0)', dark: 'oklch(0.708 0 0)' },
{ name: '--border', light: 'oklch(0.922 0 0)', dark: 'oklch(1 0 0 / 10%)' },
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index e11de6b1f..c66aff99f 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -67,6 +67,7 @@ export interface OkTerminalRestartSnapshot {
export interface OkTerminalDockState {
terminalVisible: boolean;
agentPanelVisible: boolean;
+ editorVisible?: boolean;
terminal?: { order: string[]; activeKey: string | null };
terminalSnapshot?: OkTerminalRestartSnapshot;
agents?: { order: string[]; activeKey: string | null };
@@ -177,6 +178,7 @@ export type OkMenuAction =
| 'toggle-terminal'
| 'move-terminal'
| 'toggle-agent-panel'
+ | 'toggle-editor'
| 'new-terminal'
| 'kill-terminal'
| 'new-worktree'
@@ -754,10 +756,37 @@ export interface OkEditorViewMenuStateSnapshot {
readonly terminalPlacement?: TerminalPlacement;
readonly terminalLive?: boolean;
readonly agentPanelVisible?: boolean;
+ readonly editorVisible?: boolean;
readonly canViewInSource?: boolean;
readonly hasEditorSelection?: boolean;
}
+export interface OkEditorWideVisibility {
+ readonly editorVisible?: boolean;
+ readonly terminalVisible?: boolean;
+ readonly agentPanelVisible?: boolean;
+}
+
+type OkEditorDockVisibilityKey = keyof OkEditorWideVisibility;
+
+type OkEditorOnlyPane<K extends OkEditorDockVisibilityKey> = { readonly [P in K]: boolean } & {
+ readonly [P in Exclude<OkEditorDockVisibilityKey, K>]?: never;
+};
+
+type OkEditorDockVisibilityChange = {
+ [K in OkEditorDockVisibilityKey]: OkEditorOnlyPane<K> & {
+ readonly wideIntent: OkEditorOnlyPane<K>;
+ };
+}[OkEditorDockVisibilityKey];
+
+export type OkEditorViewMenuStateChange = Partial<
+ Omit<OkEditorViewMenuStateSnapshot, OkEditorDockVisibilityKey>
+> &
+ (
+ | OkEditorDockVisibilityChange
+ | ({ readonly [K in OkEditorDockVisibilityKey]?: never } & { readonly wideIntent?: never })
+ );
+
export type OkMenuDispatchRole =
| 'undo'
| 'redo'
@@ -1434,7 +1463,7 @@ export interface OkDesktopBridge {
editor: {
notifyActiveTargetChanged(target: OkEditorActiveTargetSnapshot): void;
- notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;
+ notifyViewMenuStateChanged(state: OkEditorViewMenuStateChange): void;
notifyBackgroundThrottle(signal: { hasPendingWork: boolean; enabled: boolean }): void;
};
diff --git a/packages/core/src/desktop-bridge.type-tests.ts b/packages/core/src/desktop-bridge.type-tests.ts
new file mode 100644
index 000000000..55fd1f773
--- /dev/null
+++ b/packages/core/src/desktop-bridge.type-tests.ts
@@ -0,0 +1,40 @@
+import type { OkEditorViewMenuStateChange } from './desktop-bridge.ts';
+
+const _paired: OkEditorViewMenuStateChange = {
+ agentPanelVisible: false,
+ wideIntent: { agentPanelVisible: true },
+};
+void _paired;
+
+const _menuOnly: OkEditorViewMenuStateChange = { sidebarVisible: true };
+void _menuOnly;
+
+// @ts-expect-error -- an empty intent would update the menu and persist nothing for the changed pane.
+const _emptyIntent: OkEditorViewMenuStateChange = { terminalVisible: true, wideIntent: {} };
+void _emptyIntent;
+
+// @ts-expect-error -- an intent for another pane leaves the changed pane unpersisted.
+const _mismatchedIntent: OkEditorViewMenuStateChange = {
+ editorVisible: true,
+ wideIntent: { terminalVisible: false },
+};
+void _mismatchedIntent;
+
+// @ts-expect-error -- a dock visibility change without its intent is the unpersisted case this type exists to reject.
+const _missingIntent: OkEditorViewMenuStateChange = { editorVisible: true };
+void _missingIntent;
+
+const _strayIntent: OkEditorViewMenuStateChange = {
+ editorVisible: true,
+ // @ts-expect-error -- an intent for a pane the change does not name would persist a pane the menu did not change.
+ wideIntent: { editorVisible: true, terminalVisible: false },
+};
+void _strayIntent;
+
+// @ts-expect-error -- one change names one pane; every sender reports each pane separately.
+const _twoPanes: OkEditorViewMenuStateChange = {
+ editorVisible: true,
+ terminalVisible: false,
+ wideIntent: { editorVisible: true },
+};
+void _twoPanes;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 45606e0f3..26e37fbe3 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -398,7 +398,16 @@ export {
stripMdExt,
templateContentDocName,
} from './constants/cc1.ts';
-export { CHROME_BG_DARK, CHROME_BG_LIGHT } from './constants/chrome.ts';
+export {
+ APP_HEADER_HEIGHT,
+ APP_HEADER_HEIGHT_PX,
+ CHROME_BG_DARK,
+ CHROME_BG_LIGHT,
+ REDUCED_CHROME_HEADER_HEIGHT,
+ REDUCED_CHROME_HEADER_HEIGHT_PX,
+ SIDEBAR_BG_DARK,
+ SIDEBAR_BG_LIGHT,
+} from './constants/chrome.ts';
export {
CODE_FILE_BARE_NAMES_TO_LANGUAGE,
CODE_FILE_EXTENSIONS_TO_LANGUAGE,
diff --git a/packages/desktop/electron.vite.config.ts b/packages/desktop/electron.vite.config.ts
index 517be20c2..b9fff4652 100644
--- a/packages/desktop/electron.vite.config.ts
+++ b/packages/desktop/electron.vite.config.ts
@@ -129,10 +129,6 @@ export default defineConfig({
renderer: {
root: appRoot,
plugins: [
- // Substitutes __OK_CHROME_BG_LIGHT__ / __OK_CHROME_BG_DARK__ placeholders
- // in app/index.html with sRGB hex resolved from globals.css `--sidebar`.
- // Same plugin used by packages/app/vite.config.ts so dev (`bun run dev`)
- // and electron renderer build resolve identically.
chromeTokensVitePlugin({ globalsCssPath: resolve(appRoot, 'src/globals.css') }),
react(),
// Lingui macro + React Compiler share one Babel pass, options shared
diff --git a/packages/desktop/src/main/agent-panel-level-persistence.test.ts b/packages/desktop/src/main/agent-panel-level-persistence.test.ts
index 95b3c71b2..1de88c260 100644
--- a/packages/desktop/src/main/agent-panel-level-persistence.test.ts
+++ b/packages/desktop/src/main/agent-panel-level-persistence.test.ts
@@ -6,7 +6,7 @@ import {
setTerminalDockState,
} from './state-store';
import {
- applyAgentPanelVisibilityUpdate,
+ applyDockVisibilityUpdate,
commitTerminalDockState,
resolveRestoredAgentPanelVisible,
} from './terminal-dock-persistence';
@@ -137,13 +137,13 @@ describe('resolveRestoredAgentPanelVisible', () => {
});
});
-describe('applyAgentPanelVisibilityUpdate', () => {
+describe('applyDockVisibilityUpdate', () => {
test('a level update is remembered for the window and persisted', () => {
const rememberForWindow = vi.fn();
const persist = vi.fn(() => ({ ok: true }) as const);
const warnPersistFailed = vi.fn();
- applyAgentPanelVisibilityUpdate({ rememberForWindow, persist, warnPersistFailed }, true);
+ applyDockVisibilityUpdate({ rememberForWindow, persist, warnPersistFailed }, true);
expect(rememberForWindow).toHaveBeenCalledWith(true);
expect(persist).toHaveBeenCalledWith(true);
@@ -155,7 +155,7 @@ describe('applyAgentPanelVisibilityUpdate', () => {
const persist = vi.fn(() => ({ ok: false, reason: 'persist-failed' }) as const);
const warnPersistFailed = vi.fn();
- applyAgentPanelVisibilityUpdate({ rememberForWindow, persist, warnPersistFailed }, false);
+ applyDockVisibilityUpdate({ rememberForWindow, persist, warnPersistFailed }, false);
expect(rememberForWindow).toHaveBeenCalledWith(false);
expect(persist).toHaveBeenCalledWith(false);
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index e66eff458..db8b3ba39 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -516,9 +516,9 @@ import {
readTerminalShellSetting,
} from './terminal-consent.ts';
import {
- applyAgentPanelVisibilityUpdate,
commitTerminalDockState,
resolveRestoredAgentPanelVisible,
+ resolveRestoredEditorVisible,
} from './terminal-dock-persistence.ts';
import { observeTerminalLaunch } from './terminal-gate-observation.ts';
import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';
@@ -574,7 +574,15 @@ import { migrateLegacyUserDataDir } from './userdata-migration.ts';
import { buildUtilityForkEnv } from './utility-fork-env.ts';
import { computeFirstLaunchAfterUpgrade } from './version-drift.ts';
import { buildViewMenuStateDeps, EditorViewMenuStateRegistry } from './view-menu-state.ts';
-import { applyThemeToWindow, buildNonDarwinChromeOpts } from './window-chrome.ts';
+import { handleViewMenuStateChange } from './view-menu-state-change.ts';
+import {
+ applyThemeToWindow,
+ buildNonDarwinChromeOpts,
+ DEFAULT_WINDOW_CHROME_KIND,
+ rememberWindowChromeKind,
+ TRAFFIC_LIGHT_POSITION,
+ windowChromeOptsForKind,
+} from './window-chrome.ts';
import {
type BrowserWindowLike,
bringWindowToFront,
@@ -649,7 +657,7 @@ const DEFAULT_WIN_OPTS: BrowserWindowConstructorOptions = {
...(process.platform === 'darwin'
? {
titleBarStyle: 'hiddenInset',
- trafficLightPosition: { x: 22, y: 24 },
+ trafficLightPosition: TRAFFIC_LIGHT_POSITION,
vibrancy: VIBRANCY_DEFAULT,
visualEffectState: 'followWindow',
transparent: true,
@@ -1043,6 +1051,7 @@ function sweepConsoleHostsBeforeUpdate(): WindowsUpdateSurvivorSweepResult {
const slidesDeckRegistry = createSlidesDeckRegistry();
const dockVisibleForWindow = new Map<number, boolean>();
const agentPanelVisibleForWindow = new Map<number, boolean>();
+const editorVisibleForWindow = new Map<number, boolean>();
type DockOrderRecord = { order: string[]; activeKey: string | null };
const dockOrderForWindow = new Map<
number,
@@ -1061,6 +1070,7 @@ function persistTerminalDockForWindow(
terminalVisible: boolean;
terminalSnapshot: OkTerminalRestartSnapshot;
agentPanelVisible: boolean;
+ editorVisible: boolean;
}>,
): OkTerminalDockStateWriteResult {
const stateKey = terminalStateKey(win);
@@ -1496,8 +1506,10 @@ function ensureWindowManager() {
wm = new WindowManager({
createWindow: (opts) => {
+ const chromeKind = opts.chrome ?? DEFAULT_WINDOW_CHROME_KIND;
const win = new BrowserWindow({
...DEFAULT_WIN_OPTS,
+ ...windowChromeOptsForKind(chromeKind, process.platform, nativeTheme.shouldUseDarkColors),
minWidth: WINDOW_MIN_SIZE.EDITOR.width,
minHeight: WINDOW_MIN_SIZE.EDITOR.height,
title: opts.title,
@@ -1507,6 +1519,7 @@ function ensureWindowManager() {
preload: join(__dirname, '../preload/index.js'),
},
});
+ rememberWindowChromeKind(win, chromeKind);
win.on('page-title-updated', (e) => {
e.preventDefault();
});
@@ -1540,6 +1553,7 @@ function ensureWindowManager() {
wireWindowTerminalReap(win, terminalReaper, (windowId) => {
dockVisibleForWindow.delete(windowId);
agentPanelVisibleForWindow.delete(windowId);
+ editorVisibleForWindow.delete(windowId);
dockOrderForWindow.delete(windowId);
terminalSnapshotForWindow.delete(windowId);
});
@@ -2562,6 +2576,10 @@ async function runApplicationMenuRefresh(): Promise<void> {
onNavigateBack: () => sendMenuAction('navigate-back'),
onNavigateForward: () => sendMenuAction('navigate-forward'),
noteWindow: focusedWindow !== null && getNoteWindowContext(focusedWindow.id) !== undefined,
+ singleFileWindow:
+ focusedWindow !== null &&
+ wm?.getContextForBrowserWindow(focusedWindow as unknown as BrowserWindowLike)?.ephemeral !==
+ undefined,
activeTarget: currentActiveTarget(),
onOpenInNewWindow: () => {
const focused = BrowserWindow.getFocusedWindow();
@@ -4132,6 +4150,7 @@ function registerIpcHandlers() {
return {
terminalVisible: false,
agentPanelVisible: false,
+ editorVisible: true,
};
const stateKey = terminalStateKey(win);
const persisted = stateKey === null ? null : getTerminalDockState(appState, stateKey);
@@ -4142,6 +4161,10 @@ function registerIpcHandlers() {
inMemory: agentPanelVisibleForWindow.get(win.id),
persisted,
}),
+ editorVisible: resolveRestoredEditorVisible({
+ inMemory: editorVisibleForWindow.get(win.id),
+ persisted,
+ }),
terminal: orders?.terminal,
terminalSnapshot: terminalSnapshotForWindow.get(win.id) ?? persisted?.terminalSnapshot,
agents: orders?.agents,
@@ -4499,39 +4522,33 @@ function registerIpcHandlers() {
handle('ok:editor:view-menu-state-changed', async (event, state) => {
const win = BrowserWindow.fromWebContents(event.sender);
- if (win) editorViewMenuStates.update(win.id, state);
- if (state.terminalVisible !== undefined || state.agentPanelVisible !== undefined) {
- if (win) {
- if (state.terminalVisible !== undefined) {
- dockVisibleForWindow.set(win.id, state.terminalVisible);
- const result = persistTerminalDockForWindow(win, {
- terminalVisible: state.terminalVisible,
- });
- if (!result.ok) {
- getLogger('terminal').warn(
- { reason: result.reason },
- 'terminal visibility persistence failed',
- );
- }
- }
- if (state.agentPanelVisible !== undefined) {
- applyAgentPanelVisibilityUpdate(
- {
- rememberForWindow: (visible) => agentPanelVisibleForWindow.set(win.id, visible),
- persist: (visible) =>
- persistTerminalDockForWindow(win, { agentPanelVisible: visible }),
- warnPersistFailed: (reason) =>
- getLogger('terminal').warn(
- { reason },
- 'agents panel visibility persistence failed',
- ),
- },
- state.agentPanelVisible,
- );
- }
- }
- }
- refreshApplicationMenu();
+ handleViewMenuStateChange(
+ {
+ windowId: win?.id ?? null,
+ state,
+ },
+ {
+ updateMenuState: (windowId, partial) => editorViewMenuStates.update(windowId, partial),
+ rememberEditorVisible: (windowId, visible) => editorVisibleForWindow.set(windowId, visible),
+ rememberTerminalVisible: (windowId, visible) => dockVisibleForWindow.set(windowId, visible),
+ rememberAgentPanelVisible: (windowId, visible) =>
+ agentPanelVisibleForWindow.set(windowId, visible),
+ persist: (update) =>
+ win === null
+ ? { ok: false, reason: 'no-window-context' }
+ : persistTerminalDockForWindow(win, update),
+ warnPersistFailed: (kind, reason) => {
+ const message =
+ kind === 'editor'
+ ? 'editor visibility persistence failed'
+ : kind === 'terminal'
+ ? 'terminal visibility persistence failed'
+ : 'agents panel visibility persistence failed';
+ getLogger('terminal').warn({ reason }, message);
+ },
+ refreshApplicationMenu,
+ },
+ );
return undefined;
});
@@ -7106,6 +7123,7 @@ function bootPrimaryInstance(): void {
desktopProcessObservability = null;
dockVisibleForWindow.clear();
agentPanelVisibleForWindow.clear();
+ editorVisibleForWindow.clear();
dockOrderForWindow.clear();
terminalSnapshotForWindow.clear();
autoUpdaterHandle?.destroy();
diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.ts
index b351a6a88..df3e4e9a6 100644
--- a/packages/desktop/src/main/ipc/bug-report.test.ts
+++ b/packages/desktop/src/main/ipc/bug-report.test.ts
@@ -195,6 +195,7 @@ describe('handleBugReportCreate — agent chat transcript', () => {
const threadId = '0f5c0c0b-f439-4e49-84d6-6a6a97d675c6';
test("attaches the chosen chat's transcript with secrets scrubbed", async () => {
+ process.env.HOME = makeTmpDir('ok-bugreport-home-');
const threadsDir = makeTmpDir('ok-bugreport-threads-');
const secret = `ghp_${'a'.repeat(36)}`;
writeFileSync(
@@ -225,10 +226,9 @@ describe('handleBugReportCreate — agent chat transcript', () => {
lineCount: 1,
patterns: ['github-pat'],
};
- expect(result.summary.redactions).toContainEqual(audit);
- expect(JSON.parse(readZipEntry(result.zipPath, 'MANIFEST.json')).redactions).toContainEqual(
- audit,
- );
+ expect(result.summary.redactions).toEqual([audit]);
+ expect(result.summary.redactedLineCount).toBe(1);
+ expect(JSON.parse(readZipEntry(result.zipPath, 'MANIFEST.json')).redactions).toEqual([audit]);
expect(readZipEntry(result.zipPath, 'README.md')).toContain(
'1 line(s) were scrubbed across 1 file(s).',
);
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 46c48a6c6..a82911cf6 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -80,6 +80,9 @@ export interface MenuDeps {
agentPanelVisible?: boolean;
hasEditorSelection?: boolean;
onToggleAgentPanel?(): void;
+ singleFileWindow?: boolean;
+ editorVisible?: boolean;
+ onToggleEditor?(): void;
onNewTerminal?(): void;
onKillTerminal?(): void;
onNewTerminalWindow?(): void;
@@ -300,6 +303,11 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {
present: (d) => d.noteWindow !== true,
enabled: (d) => d.onToggleAgentPanel !== undefined,
},
+ 'toggle-editor': {
+ click: (d) => () => d.onToggleEditor?.(),
+ present: (d) => d.noteWindow !== true && d.singleFileWindow !== true,
+ enabled: (d) => d.onToggleEditor !== undefined,
+ },
'toggle-show-hidden-files': {
click: (d) => () => d.onToggleShowHiddenFiles?.(),
enabled: (d) => d.onToggleShowHiddenFiles !== undefined,
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index 4e97b0285..bbc5f5d3a 100644
--- a/packages/desktop/src/main/state-store.ts
+++ b/packages/desktop/src/main/state-store.ts
@@ -68,6 +68,7 @@ export interface PersistedTerminalDockState {
terminalVisible: boolean;
terminalSnapshot: OkTerminalRestartSnapshot;
agentPanelVisible: boolean;
+ editorVisible: boolean;
}
export type UpdateChannel = 'latest' | 'beta';
@@ -472,6 +473,7 @@ function emptyTerminalDockState(): PersistedTerminalDockState {
terminalVisible: false,
terminalSnapshot: { tabs: [], activeOrdinal: null },
agentPanelVisible: false,
+ editorVisible: true,
};
}
@@ -520,6 +522,7 @@ function parsePersistedTerminalDockState(raw: unknown): PersistedTerminalDockSta
terminalVisible: obj.terminalVisible === true,
terminalSnapshot: normalizeTerminalRestartSnapshot(obj.terminalSnapshot),
agentPanelVisible: obj.agentPanelVisible === true,
+ editorVisible: obj.editorVisible !== false,
};
}
diff --git a/packages/desktop/src/main/terminal-dock-persistence.test.ts b/packages/desktop/src/main/terminal-dock-persistence.test.ts
index a4f0af796..75ce505c1 100644
--- a/packages/desktop/src/main/terminal-dock-persistence.test.ts
+++ b/packages/desktop/src/main/terminal-dock-persistence.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test, vi } from 'vitest';
import { emptyState, getTerminalDockState, setTerminalDockState } from './state-store';
-import { commitTerminalDockState } from './terminal-dock-persistence';
+import { commitTerminalDockState, resolveRestoredEditorVisible } from './terminal-dock-persistence';
describe('commitTerminalDockState', () => {
test('publishes the new state only after the durable write succeeds', () => {
@@ -25,6 +25,7 @@ describe('commitTerminalDockState', () => {
terminalVisible: false,
terminalSnapshot: { tabs: [], activeOrdinal: null },
agentPanelVisible: false,
+ editorVisible: true,
});
});
@@ -49,6 +50,7 @@ describe('commitTerminalDockState', () => {
terminalVisible: true,
terminalSnapshot,
agentPanelVisible: false,
+ editorVisible: true,
});
const save = vi.fn(() => true);
@@ -63,3 +65,30 @@ describe('commitTerminalDockState', () => {
expect(outcome).toEqual({ state: current, result: { ok: true } });
});
});
+
+describe('resolveRestoredEditorVisible', () => {
+ test("prefers this window's in-memory level, then the saved one, and defaults to shown", () => {
+ const saved = getTerminalDockState(
+ setTerminalDockState(emptyState(), '/project', {
+ terminalVisible: false,
+ terminalSnapshot: { tabs: [], activeOrdinal: null },
+ agentPanelVisible: false,
+ editorVisible: false,
+ }),
+ '/project',
+ );
+ expect(resolveRestoredEditorVisible({ inMemory: true, persisted: saved })).toBe(true);
+ expect(resolveRestoredEditorVisible({ inMemory: undefined, persisted: saved })).toBe(false);
+ expect(resolveRestoredEditorVisible({ inMemory: undefined, persisted: null })).toBe(true);
+ });
+
+ test('an editor hide is saved per project', () => {
+ const outcome = commitTerminalDockState({
+ current: emptyState(),
+ stateKey: '/project',
+ update: { editorVisible: false },
+ save: () => true,
+ });
+ expect(getTerminalDockState(outcome.state, '/project').editorVisible).toBe(false);
+ });
+});
diff --git a/packages/desktop/src/main/terminal-dock-persistence.ts b/packages/desktop/src/main/terminal-dock-persistence.ts
index b1a874912..7923de65b 100644
--- a/packages/desktop/src/main/terminal-dock-persistence.ts
+++ b/packages/desktop/src/main/terminal-dock-persistence.ts
@@ -17,6 +17,7 @@ interface CommitTerminalDockStateInput {
terminalVisible: boolean;
terminalSnapshot: OkTerminalRestartSnapshot;
agentPanelVisible: boolean;
+ editorVisible: boolean;
}>;
readonly save: (state: AppState) => boolean;
}
@@ -49,16 +50,23 @@ export function resolveRestoredAgentPanelVisible({
return inMemory ?? persisted?.agentPanelVisible ?? false;
}
-export interface AgentPanelVisibilityUpdateDeps {
+export function resolveRestoredEditorVisible({
+ inMemory,
+ persisted,
+}: {
+ readonly inMemory: boolean | undefined;
+ readonly persisted: PersistedTerminalDockState | null | undefined;
+}): boolean {
+ return inMemory ?? persisted?.editorVisible ?? true;
+}
+
+export interface DockVisibilityUpdateDeps {
readonly rememberForWindow: (visible: boolean) => void;
readonly persist: (visible: boolean) => OkTerminalDockStateWriteResult;
readonly warnPersistFailed: (reason: string) => void;
}
-export function applyAgentPanelVisibilityUpdate(
- deps: AgentPanelVisibilityUpdateDeps,
- visible: boolean,
-): void {
+export function applyDockVisibilityUpdate(deps: DockVisibilityUpdateDeps, visible: boolean): void {
deps.rememberForWindow(visible);
const result = deps.persist(visible);
if (!result.ok) deps.warnPersistFailed(result.reason);
diff --git a/packages/desktop/src/main/view-menu-state-change.test.ts b/packages/desktop/src/main/view-menu-state-change.test.ts
new file mode 100644
index 000000000..de0adeac8
--- /dev/null
+++ b/packages/desktop/src/main/view-menu-state-change.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, test, vi } from 'vitest';
+import { emptyState, getTerminalDockState, setTerminalDockState } from './state-store';
+import { commitTerminalDockState } from './terminal-dock-persistence';
+import { EditorViewMenuStateRegistry } from './view-menu-state';
+import {
+ handleViewMenuStateChange,
+ type ViewMenuStateChangeDeps,
+ type ViewMenuStateChangeInput,
+} from './view-menu-state-change';
+
+const panes = ['editorVisible', 'terminalVisible', 'agentPanelVisible'] as const;
+
+type Pane = (typeof panes)[number];
+
+function paneChange(
+ pane: Pane,
+ shown: boolean,
+ intent: boolean,
+): ViewMenuStateChangeInput['state'] {
+ return { [pane]: shown, wideIntent: { [pane]: intent } } as ViewMenuStateChangeInput['state'];
+}
+
+function setup() {
+ const menu = new EditorViewMenuStateRegistry();
+ const editor = new Map<number, boolean>();
+ const terminal = new Map<number, boolean>();
+ const agents = new Map<number, boolean>();
+ let durable = setTerminalDockState(emptyState(), '/file', {
+ editorVisible: false,
+ terminalVisible: false,
+ agentPanelVisible: false,
+ terminalSnapshot: { tabs: [], activeOrdinal: null },
+ });
+ const save = vi.fn(() => true);
+ const warnPersistFailed = vi.fn();
+ const refreshApplicationMenu = vi.fn();
+ const deps: ViewMenuStateChangeDeps = {
+ updateMenuState: (id, partial) => menu.update(id, partial),
+ rememberEditorVisible: (id, visible) => editor.set(id, visible),
+ rememberTerminalVisible: (id, visible) => terminal.set(id, visible),
+ rememberAgentPanelVisible: (id, visible) => agents.set(id, visible),
+ persist: (update) => {
+ const result = commitTerminalDockState({
+ current: durable,
+ stateKey: '/file',
+ update,
+ save,
+ });
+ durable = result.state;
+ return result.result;
+ },
+ warnPersistFailed,
+ refreshApplicationMenu,
+ };
+ return {
+ deps,
+ menu,
+ editor,
+ terminal,
+ agents,
+ save,
+ warnPersistFailed,
+ refreshApplicationMenu,
+ saved: () => getTerminalDockState(durable, '/file'),
+ };
+}
+
+function push(
+ deps: ViewMenuStateChangeDeps,
+ state: ViewMenuStateChangeInput['state'],
+ windowId: number | null = 7,
+) {
+ handleViewMenuStateChange({ windowId, state }, deps);
+}
+
+describe('desktop view menu state changes', () => {
+ test('a narrow projection shows in the menu while the durable dock state keeps the wide intent', () => {
+ const h = setup();
+ for (const pane of panes) push(h.deps, paneChange(pane, true, false));
+
+ expect(h.menu.get(7)).toMatchObject({
+ editorVisible: true,
+ terminalVisible: true,
+ agentPanelVisible: true,
+ });
+ expect(h.saved()).toMatchObject({
+ editorVisible: false,
+ terminalVisible: false,
+ agentPanelVisible: false,
+ });
+ expect(h.refreshApplicationMenu).toHaveBeenCalledTimes(3);
+ });
+
+ test('the wide intent the renderer reports is persisted and kept out of the menu state', () => {
+ const h = setup();
+ for (const pane of panes) push(h.deps, paneChange(pane, true, true));
+
+ expect(h.menu.get(7)).toMatchObject({
+ editorVisible: true,
+ terminalVisible: true,
+ agentPanelVisible: true,
+ });
+ expect(h.menu.get(7)).not.toHaveProperty('wideIntent');
+ expect(h.saved()).toMatchObject({
+ editorVisible: true,
+ terminalVisible: true,
+ agentPanelVisible: true,
+ });
+ expect(h.editor.get(7)).toBe(true);
+ expect(h.terminal.get(7)).toBe(true);
+ expect(h.agents.get(7)).toBe(true);
+ expect(h.save).toHaveBeenCalledTimes(3);
+ expect(h.warnPersistFailed).not.toHaveBeenCalled();
+ });
+
+ test('closing the last session while narrow reaches the durable record and survives widening', () => {
+ const h = setup();
+ for (const pane of panes) push(h.deps, paneChange(pane, true, true));
+ push(h.deps, paneChange('terminalVisible', false, false));
+ push(h.deps, paneChange('agentPanelVisible', false, false));
+ push(h.deps, paneChange('editorVisible', true, true));
+
+ expect(h.saved()).toMatchObject({
+ editorVisible: true,
+ terminalVisible: false,
+ agentPanelVisible: false,
+ });
+ expect(h.terminal.get(7)).toBe(false);
+ expect(h.agents.get(7)).toBe(false);
+ });
+
+ test('a missing sender still refreshes the menu without a durable write', () => {
+ const h = setup();
+ push(h.deps, paneChange('terminalVisible', true, true), null);
+ expect(h.save).not.toHaveBeenCalled();
+ expect(h.refreshApplicationMenu).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/desktop/src/main/view-menu-state-change.ts b/packages/desktop/src/main/view-menu-state-change.ts
new file mode 100644
index 000000000..73bd8f3f4
--- /dev/null
+++ b/packages/desktop/src/main/view-menu-state-change.ts
@@ -0,0 +1,66 @@
+import type { OkTerminalDockStateWriteResult } from '@inkeep/open-knowledge-core/desktop-bridge';
+import type {
+ EditorViewMenuStateChange,
+ EditorViewMenuStateSnapshot,
+} from '../shared/ipc-channels';
+import { applyDockVisibilityUpdate } from './terminal-dock-persistence';
+
+type DockVisibilityUpdate = Partial<{
+ editorVisible: boolean;
+ terminalVisible: boolean;
+ agentPanelVisible: boolean;
+}>;
+
+export interface ViewMenuStateChangeInput {
+ readonly windowId: number | null;
+ readonly state: EditorViewMenuStateChange;
+}
+
+export interface ViewMenuStateChangeDeps {
+ readonly updateMenuState: (windowId: number, state: Partial<EditorViewMenuStateSnapshot>) => void;
+ readonly rememberEditorVisible: (windowId: number, visible: boolean) => void;
+ readonly rememberTerminalVisible: (windowId: number, visible: boolean) => void;
+ readonly rememberAgentPanelVisible: (windowId: number, visible: boolean) => void;
+ readonly persist: (update: DockVisibilityUpdate) => OkTerminalDockStateWriteResult;
+ readonly warnPersistFailed: (kind: 'editor' | 'terminal' | 'agents', reason: string) => void;
+ readonly refreshApplicationMenu: () => void;
+}
+
+export function handleViewMenuStateChange(
+ { windowId, state }: ViewMenuStateChangeInput,
+ deps: ViewMenuStateChangeDeps,
+): void {
+ const { wideIntent, ...menuState } = state;
+ if (windowId !== null) deps.updateMenuState(windowId, menuState);
+ if (windowId !== null && wideIntent?.editorVisible !== undefined) {
+ applyDockVisibilityUpdate(
+ {
+ rememberForWindow: (visible) => deps.rememberEditorVisible(windowId, visible),
+ persist: (visible) => deps.persist({ editorVisible: visible }),
+ warnPersistFailed: (reason) => deps.warnPersistFailed('editor', reason),
+ },
+ wideIntent.editorVisible,
+ );
+ }
+ if (windowId !== null && wideIntent?.terminalVisible !== undefined) {
+ applyDockVisibilityUpdate(
+ {
+ rememberForWindow: (visible) => deps.rememberTerminalVisible(windowId, visible),
+ persist: (visible) => deps.persist({ terminalVisible: visible }),
+ warnPersistFailed: (reason) => deps.warnPersistFailed('terminal', reason),
+ },
+ wideIntent.terminalVisible,
+ );
+ }
+ if (windowId !== null && wideIntent?.agentPanelVisible !== undefined) {
+ applyDockVisibilityUpdate(
+ {
+ rememberForWindow: (visible) => deps.rememberAgentPanelVisible(windowId, visible),
+ persist: (visible) => deps.persist({ agentPanelVisible: visible }),
+ warnPersistFailed: (reason) => deps.warnPersistFailed('agents', reason),
+ },
+ wideIntent.agentPanelVisible,
+ );
+ }
+ deps.refreshApplicationMenu();
+}
diff --git a/packages/desktop/src/main/view-menu-state.test.ts b/packages/desktop/src/main/view-menu-state.test.ts
index 7356dc5d9..a7846a193 100644
--- a/packages/desktop/src/main/view-menu-state.test.ts
+++ b/packages/desktop/src/main/view-menu-state.test.ts
@@ -171,6 +171,7 @@ describe('createDefaultEditorViewMenuState — pre-first-push menu state', () =>
terminalPlacement: 'bottom',
terminalLive: false,
agentPanelVisible: false,
+ editorVisible: true,
canViewInSource: false,
hasEditorSelection: false,
});
diff --git a/packages/desktop/src/main/view-menu-state.ts b/packages/desktop/src/main/view-menu-state.ts
index 88e021671..1f3082549 100644
--- a/packages/desktop/src/main/view-menu-state.ts
+++ b/packages/desktop/src/main/view-menu-state.ts
@@ -52,6 +52,7 @@ export function createDefaultEditorViewMenuState(): EditorViewMenuStateSnapshot
terminalPlacement: 'bottom',
terminalLive: false,
agentPanelVisible: false,
+ editorVisible: true,
canViewInSource: false,
hasEditorSelection: false,
};
@@ -71,6 +72,7 @@ type ViewMenuStateDeps = Pick<
| 'terminalPlacement'
| 'terminalLive'
| 'agentPanelVisible'
+ | 'editorVisible'
| 'hasEditorSelection'
| 'onToggleShowHiddenFiles'
| 'onToggleShowOkFolders'
@@ -81,6 +83,7 @@ type ViewMenuStateDeps = Pick<
| 'onToggleTerminal'
| 'onMoveTerminal'
| 'onToggleAgentPanel'
+ | 'onToggleEditor'
| 'onNewTerminal'
| 'onKillTerminal'
| 'onExpandAll'
@@ -104,6 +107,7 @@ export function buildViewMenuStateDeps(
terminalPlacement: state.terminalPlacement,
terminalLive: state.terminalLive,
agentPanelVisible: state.agentPanelVisible,
+ editorVisible: state.editorVisible,
hasEditorSelection: state.hasEditorSelection,
onToggleShowHiddenFiles: () => sendMenuAction('toggle-show-hidden-files'),
onToggleShowOkFolders: () => sendMenuAction('toggle-show-ok-folders'),
@@ -114,6 +118,7 @@ export function buildViewMenuStateDeps(
onToggleTerminal: () => sendMenuAction('toggle-terminal'),
onMoveTerminal: () => sendMenuAction('move-terminal'),
onToggleAgentPanel: () => sendMenuAction('toggle-agent-panel'),
+ onToggleEditor: () => sendMenuAction('toggle-editor'),
onNewTerminal: () => sendMenuAction('new-terminal'),
onKillTerminal: () => sendMenuAction('kill-terminal'),
onExpandAll: () => sendMenuAction('expand-all-tree'),
diff --git a/packages/desktop/src/main/window-chrome.test.ts b/packages/desktop/src/main/window-chrome.test.ts
index 07902b069..26174d247 100644
--- a/packages/desktop/src/main/window-chrome.test.ts
+++ b/packages/desktop/src/main/window-chrome.test.ts
@@ -1,14 +1,33 @@
+import { APP_HEADER_HEIGHT, REDUCED_CHROME_HEADER_HEIGHT } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
import type { OkChromeColors } from '../shared/bridge-contract.ts';
+import { noteWindowNativeChromeOptions } from './note-window.ts';
import {
+ APP_HEADER_TITLEBAR_OVERLAY_HEIGHT,
+ APP_HEADER_TRAFFIC_LIGHT_POSITION,
applyThemeToWindow,
buildNonDarwinChromeOpts,
CHROME_BG,
CHROME_SYMBOL,
computeTitleBarOverlay,
+ rememberWindowChromeKind,
+ SINGLE_FILE_WINDOW_CHROME_KIND,
TITLEBAR_OVERLAY_HEIGHT,
+ TRAFFIC_LIGHT_POSITION,
+ windowChromeOptsForKind,
} from './window-chrome.ts';
+const ROOT_FONT_SIZE_PX = 16;
+
+const MACOS_TRAFFIC_LIGHT_DIAMETER_PX = 14;
+
+function remToPx(rem: string): number {
+ expect(rem).toMatch(/^\d+(?:\.\d+)?rem$/);
+ return Number.parseFloat(rem) * ROOT_FONT_SIZE_PX;
+}
+
+const REDUCED_CHROME_BAR_PX = remToPx(REDUCED_CHROME_HEADER_HEIGHT);
+
const LIVE: OkChromeColors = { bg: '#282a36', symbol: '#f8f8f2' };
describe('computeTitleBarOverlay', () => {
@@ -28,13 +47,28 @@ describe('computeTitleBarOverlay', () => {
});
});
- test('overlay height matches the renderer chrome row (EditorHeader h-12)', () => {
- expect(TITLEBAR_OVERLAY_HEIGHT).toBe(48);
+ test('overlay height matches the renderer reduced-chrome top bar', () => {
+ expect(TITLEBAR_OVERLAY_HEIGHT).toBe(REDUCED_CHROME_BAR_PX);
+ });
+
+ test('the app-header overlay height is the renderer app header height', () => {
+ expect(APP_HEADER_HEIGHT).toMatch(/^\d+(?:\.\d+)?rem$/);
+ expect(Number.parseFloat(APP_HEADER_HEIGHT) * ROOT_FONT_SIZE_PX).toBe(
+ APP_HEADER_TITLEBAR_OVERLAY_HEIGHT,
+ );
+ });
+
+ test('an explicit height overrides the shared default', () => {
+ expect(computeTitleBarOverlay(false, undefined, APP_HEADER_TITLEBAR_OVERLAY_HEIGHT)).toEqual({
+ color: CHROME_BG.light,
+ symbolColor: CHROME_SYMBOL.light,
+ height: APP_HEADER_TITLEBAR_OVERLAY_HEIGHT,
+ });
});
test('chrome tokens stay in lockstep with the committed FOUC-guard values', () => {
- expect(CHROME_BG.light).toBe('#fafafa');
- expect(CHROME_BG.dark).toBe('#171717');
+ expect(CHROME_BG.light).toBe('#f5f5f5');
+ expect(CHROME_BG.dark).toBe('#292929');
});
test("the renderer's live colors take precedence over the default-theme snapshot", () => {
@@ -66,6 +100,59 @@ describe('buildNonDarwinChromeOpts', () => {
});
});
+describe('windowChromeOptsForKind', () => {
+ test('a compact window keeps every shared default on every platform', () => {
+ for (const platform of ['darwin', 'win32', 'linux'] as const) {
+ expect(windowChromeOptsForKind('compact', platform, true)).toEqual({});
+ }
+ expect(TRAFFIC_LIGHT_POSITION).toEqual({ x: 22, y: 24 });
+ });
+
+ test('an app-header window raises the macOS traffic lights into the 44px header and lines them up with the file list', () => {
+ expect(windowChromeOptsForKind('app-header', 'darwin', true)).toEqual({
+ trafficLightPosition: APP_HEADER_TRAFFIC_LIGHT_POSITION,
+ });
+ expect(APP_HEADER_TRAFFIC_LIGHT_POSITION).toEqual({ x: 16, y: 15 });
+ });
+
+ test('the app-header traffic lights sit as far above the header centre as the note window tunes them in its bar', () => {
+ const noteY = noteWindowNativeChromeOptions('darwin').trafficLightPosition?.y;
+ expect(noteY).toBeDefined();
+ const noteInsetFromCentre = TITLEBAR_OVERLAY_HEIGHT / 2 - (noteY ?? 0);
+ const appHeaderInsetFromCentre =
+ APP_HEADER_TITLEBAR_OVERLAY_HEIGHT / 2 - APP_HEADER_TRAFFIC_LIGHT_POSITION.y;
+ expect(appHeaderInsetFromCentre).toBe(noteInsetFromCentre);
+ });
+
+ test('a single-file window takes the chrome of the shared header it renders', () => {
+ expect(SINGLE_FILE_WINDOW_CHROME_KIND).toBe('app-header');
+ const position = windowChromeOptsForKind(
+ SINGLE_FILE_WINDOW_CHROME_KIND,
+ 'darwin',
+ true,
+ ).trafficLightPosition;
+ expect((position?.y ?? 0) + MACOS_TRAFFIC_LIGHT_DIAMETER_PX / 2).toBe(
+ remToPx(APP_HEADER_HEIGHT) / 2,
+ );
+ expect(windowChromeOptsForKind(SINGLE_FILE_WINDOW_CHROME_KIND, 'win32', true)).toEqual({
+ titleBarOverlay: computeTitleBarOverlay(true, undefined, remToPx(APP_HEADER_HEIGHT)),
+ });
+ });
+
+ test.each(['win32', 'linux'] as const)(
+ 'an app-header window shrinks the %s overlay to the header height',
+ (platform) => {
+ expect(windowChromeOptsForKind('app-header', platform, true)).toEqual({
+ titleBarOverlay: computeTitleBarOverlay(
+ true,
+ undefined,
+ APP_HEADER_TITLEBAR_OVERLAY_HEIGHT,
+ ),
+ });
+ },
+ );
+});
+
describe('applyThemeToWindow', () => {
function makeWin(overrides: { destroyed?: boolean; overlayThrows?: boolean } = {}) {
const calls: { bg: string[]; overlay: unknown[] } = { bg: [], overlay: [] };
@@ -116,6 +203,21 @@ describe('applyThemeToWindow', () => {
expect(calls.bg).toEqual([CHROME_BG.light]);
});
+ test('a theme repaint keeps an app-header window on the header-sized overlay', () => {
+ const { win, calls } = makeWin();
+ rememberWindowChromeKind(win, 'app-header');
+ applyThemeToWindow(win, 'win32', true);
+ expect(calls.overlay).toEqual([
+ computeTitleBarOverlay(true, undefined, APP_HEADER_TITLEBAR_OVERLAY_HEIGHT),
+ ]);
+ });
+
+ test('a theme repaint leaves an unregistered window on the shared 48px overlay', () => {
+ const { win, calls } = makeWin();
+ applyThemeToWindow(win, 'win32', true);
+ expect(calls.overlay).toEqual([computeTitleBarOverlay(true, undefined, 48)]);
+ });
+
test('win32 repaints background AND overlay from the live palette', () => {
const { win, calls } = makeWin();
applyThemeToWindow(win, 'win32', true, LIVE);
diff --git a/packages/desktop/src/main/window-chrome.ts b/packages/desktop/src/main/window-chrome.ts
index 75e1c2218..6ba04dc74 100644
--- a/packages/desktop/src/main/window-chrome.ts
+++ b/packages/desktop/src/main/window-chrome.ts
@@ -1,9 +1,38 @@
+import {
+ APP_HEADER_HEIGHT_PX,
+ CHROME_BG_DARK,
+ CHROME_BG_LIGHT,
+ REDUCED_CHROME_HEADER_HEIGHT_PX,
+} from '@inkeep/open-knowledge-core';
import type { BrowserWindowConstructorOptions } from 'electron';
import type { OkChromeColors } from '../shared/bridge-contract.ts';
-export const TITLEBAR_OVERLAY_HEIGHT = 48;
+export const TITLEBAR_OVERLAY_HEIGHT = REDUCED_CHROME_HEADER_HEIGHT_PX;
-export const CHROME_BG = { light: '#fafafa', dark: '#171717' } as const;
+export const APP_HEADER_TITLEBAR_OVERLAY_HEIGHT = APP_HEADER_HEIGHT_PX;
+
+export const TRAFFIC_LIGHT_POSITION = { x: 22, y: 24 } as const;
+
+const TRAFFIC_LIGHT_BUTTON_HEIGHT = 14;
+
+const FILE_LIST_CONTENT_INSET = 16;
+
+export const APP_HEADER_TRAFFIC_LIGHT_POSITION = {
+ x: FILE_LIST_CONTENT_INSET,
+ y: (APP_HEADER_TITLEBAR_OVERLAY_HEIGHT - TRAFFIC_LIGHT_BUTTON_HEIGHT) / 2,
+} as const;
+
+export type WindowChromeKind = 'app-header' | 'compact';
+
+export const SINGLE_FILE_WINDOW_CHROME_KIND: WindowChromeKind = 'app-header';
+
+export const DEFAULT_WINDOW_CHROME_KIND: WindowChromeKind = 'compact';
+
+function titleBarOverlayHeightForKind(kind: WindowChromeKind): number {
+ return kind === 'app-header' ? APP_HEADER_TITLEBAR_OVERLAY_HEIGHT : TITLEBAR_OVERLAY_HEIGHT;
+}
+
+export const CHROME_BG = { light: CHROME_BG_LIGHT, dark: CHROME_BG_DARK } as const;
export const CHROME_SYMBOL = { light: '#171717', dark: '#fafafa' } as const;
export interface TitleBarOverlayOptions {
@@ -22,12 +51,13 @@ function chromeColors(isDark: boolean, live?: OkChromeColors): OkChromeColors {
export function computeTitleBarOverlay(
isDark: boolean,
live?: OkChromeColors,
+ height: number = TITLEBAR_OVERLAY_HEIGHT,
): TitleBarOverlayOptions {
const { bg, symbol } = chromeColors(isDark, live);
return {
color: bg,
symbolColor: symbol,
- height: TITLEBAR_OVERLAY_HEIGHT,
+ height,
};
}
@@ -40,12 +70,34 @@ export function buildNonDarwinChromeOpts(isDark: boolean): BrowserWindowConstruc
};
}
+export function windowChromeOptsForKind(
+ kind: WindowChromeKind,
+ platform: NodeJS.Platform,
+ isDark: boolean,
+): BrowserWindowConstructorOptions {
+ if (kind === 'compact') return {};
+ if (platform === 'darwin') return { trafficLightPosition: APP_HEADER_TRAFFIC_LIGHT_POSITION };
+ return {
+ titleBarOverlay: computeTitleBarOverlay(isDark, undefined, titleBarOverlayHeightForKind(kind)),
+ };
+}
+
interface ThemeableWindow {
isDestroyed(): boolean;
setBackgroundColor(color: string): void;
setTitleBarOverlay?(options: TitleBarOverlayOptions): void;
}
+const windowChromeKinds = new WeakMap<ThemeableWindow, WindowChromeKind>();
+
+export function rememberWindowChromeKind(win: ThemeableWindow, kind: WindowChromeKind): void {
+ windowChromeKinds.set(win, kind);
+}
+
+function windowChromeKindOf(win: ThemeableWindow): WindowChromeKind {
+ return windowChromeKinds.get(win) ?? DEFAULT_WINDOW_CHROME_KIND;
+}
+
export function applyThemeToWindow(
win: ThemeableWindow,
platform: NodeJS.Platform,
@@ -61,8 +113,9 @@ export function applyThemeToWindow(
(platform === 'win32' || platform === 'linux') &&
typeof win.setTitleBarOverlay === 'function'
) {
+ const height = titleBarOverlayHeightForKind(windowChromeKindOf(win));
try {
- win.setTitleBarOverlay(computeTitleBarOverlay(isDark, live));
+ win.setTitleBarOverlay(computeTitleBarOverlay(isDark, live, height));
} catch {}
}
}
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index ea5c55883..32c1eb70e 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -39,6 +39,7 @@ import type { ShowGateRegistry } from './show-gate.ts';
import type { RestoredWindow } from './state-store.ts';
import type { ShareDeepLinkBranchSwitchPayload } from './url-scheme.ts';
import { classifyServerVersion } from './version-drift.ts';
+import { SINGLE_FILE_WINDOW_CHROME_KIND, type WindowChromeKind } from './window-chrome.ts';
const RESTART_SIGTERM_GRACE_MS = 3_000;
@@ -339,6 +340,7 @@ export interface WindowManagerDeps {
title: string;
projectPath?: string;
focusKey?: string;
+ chrome?: WindowChromeKind;
}): BrowserWindowLike;
forkUtility(
entry: string,
@@ -1514,6 +1516,7 @@ export class WindowManager {
additionalArguments,
title: formatEditorTitle(projectName),
projectPath,
+ chrome: 'app-header',
});
this.deps.startup?.markWindowCreated?.();
this.attachSafetyNet(window.webContents, apiOrigin, projectPath);
@@ -1876,6 +1879,7 @@ export class WindowManager {
],
title: formatEditorTitle(projectName),
focusKey: canonicalKey,
+ chrome: SINGLE_FILE_WINDOW_CHROME_KIND,
});
this.attachSafetyNet(window.webContents, apiOrigin, opts.contentDir);
@@ -2315,6 +2319,7 @@ export class WindowManager {
],
title: formatEditorTitle(projectName),
projectPath,
+ chrome: 'app-header',
});
this.deps.startup?.markWindowCreated?.();
this.attachSafetyNet(window.webContents, apiOrigin, projectPath);
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 8d3695218..e68cf5fdf 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -29,7 +29,7 @@ import type {
OkDesktopBridge,
OkDesktopConfig,
OkEditorActiveTargetSnapshot,
- OkEditorViewMenuStateSnapshot,
+ OkEditorViewMenuStateChange,
OkLocalOpAuthEvent,
OkLocalOpCloneEvent,
OkLocalOpStream,
@@ -286,6 +286,7 @@ const MENU_ACTION_BUFFER_POLICY: Record<OkMenuAction, MenuActionBufferPolicy> =
'toggle-doc-panel': 'parity',
'toggle-terminal': 'parity',
'toggle-agent-panel': 'parity',
+ 'toggle-editor': 'parity',
'toggle-show-hidden-files': 'parity',
'toggle-show-ok-folders': 'parity',
'toggle-show-only-markdown-files': 'parity',
@@ -850,7 +851,7 @@ const bridge: OkDesktopBridge = {
notifyActiveTargetChanged: (target: OkEditorActiveTargetSnapshot) => {
invoke('ok:editor:active-target-changed', target).catch(() => {});
},
- notifyViewMenuStateChanged: (state: Partial<OkEditorViewMenuStateSnapshot>) => {
+ notifyViewMenuStateChanged: (state: OkEditorViewMenuStateChange) => {
invoke('ok:editor:view-menu-state-changed', state).catch(() => {});
},
notifyBackgroundThrottle: (signal: { hasPendingWork: boolean; enabled: boolean }) => {
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 654d440ac..683372236 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -44,6 +44,7 @@ import type {
OkChromeColors,
OkDesktopConfig,
OkEditorActiveTargetSnapshot,
+ OkEditorViewMenuStateChange,
OkEditorViewMenuStateSnapshot,
OkLocalOpAuthReposResponse,
OkLocalOpAuthStatusResponse,
@@ -90,6 +91,7 @@ import type { EntryPoint } from './entry-point.ts';
export type EditorActiveTargetSnapshot = OkEditorActiveTargetSnapshot;
export type EditorViewMenuStateSnapshot = OkEditorViewMenuStateSnapshot;
+export type EditorViewMenuStateChange = OkEditorViewMenuStateChange;
export type { SkillCostTiers };
export type MenuDispatchRole = OkMenuDispatchRole;
export type MenuDispatchCommand = OkMenuDispatchCommand;
@@ -667,7 +669,7 @@ export interface RequestChannels {
result: undefined;
};
'ok:editor:view-menu-state-changed': {
- args: [state: Partial<EditorViewMenuStateSnapshot>];
+ args: [state: EditorViewMenuStateChange];
result: undefined;
};
'ok:editor:background-throttle': {
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index bf5bbd153..97eb08336 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -262,7 +262,8 @@ describe('M1 smoke', () => {
const coreMembers = extractLiteralUnion(readFileSync(corePath, 'utf-8'), 'OkMenuAction');
expect(coreMembers.size).toBeGreaterThan(0);
- expect(coreMembers.size).toBe(37);
+ expect(coreMembers.size).toBe(38);
+ expect(coreMembers.has('toggle-editor')).toBe(true);
expect(coreMembers.has('toggle-show-hidden-files')).toBe(true);
expect(coreMembers.has('toggle-show-ok-folders')).toBe(true);
expect(coreMembers.has('toggle-show-only-markdown-files')).toBe(true);
diff --git a/packages/desktop/tests/main/desktop-uninstall-handoff.test.ts b/packages/desktop/tests/main/desktop-uninstall-handoff.test.ts
index 5d9a70ba7..5cfb0f321 100644
--- a/packages/desktop/tests/main/desktop-uninstall-handoff.test.ts
+++ b/packages/desktop/tests/main/desktop-uninstall-handoff.test.ts
@@ -1716,7 +1716,9 @@ case "$1" in
esac
if [ "$1" = -- ]; then shift; fi
target=${'$'}{1-}
-record="sender=$PPID self=$$ signal=$signal target=$target"
+recordSender=$PPID
+if [ -n "${'$'}{OK_SIGNAL_RECORDER_REPLACE_UI:-}" ]; then recordSender=$$; fi
+record="sender=$recordSender self=$$ signal=$signal target=$target"
if [ "$#" -ne 1 ] || [ -z "$signal" ]; then
printf '%s refused=call\\n' "$record" >> '${recordsPath}'
exit 1
@@ -1733,6 +1735,9 @@ if [ "$signal" = 0 ]; then
/bin/kill -s 0 "$target" 2>/dev/null
status=$?
printf '%s probed=%s\\n' "$record" "$status" >> '${recordsPath}'
+ if [ -n "${'$'}{OK_SIGNAL_RECORDER_REPLACE_UI:-}" ]; then
+ exec /bin/sleep "$OK_SIGNAL_RECORDER_REPLACE_UI"
+ fi
exit "$status"
fi
if [ "${'$'}{1:-}" = "$PPID" ] || [ "${'$'}{1:-}" = "$$" ]; then
@@ -3900,8 +3905,8 @@ while [ -f "$profile/watched" ]; do
[ "$polls" -le ${inMilliseconds(STUCK_QUERY_SECONDS) / RECORDED_IDENTITY_POLL_MS} ] || exit 1
/bin/sleep ${RECORDED_IDENTITY_POLL_MS / 1000}
done
-'${recorder.path}' -s 0 "$$"
-exec /bin/sleep ${STUCK_QUERY_SECONDS}`,
+export OK_SIGNAL_RECORDER_REPLACE_UI=${STUCK_QUERY_SECONDS}
+exec '${recorder.path}' -s 0 "$$"`,
),
],
},
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 1c915c7ef..65017b106 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -1695,3 +1695,49 @@ describe('Window → Open in New Window', () => {
}
});
});
+
+describe('buildMenuTemplate — View → Show/Hide Editor', () => {
+ const viewLabels = (deps: Partial<MenuDeps>) => {
+ const sub = findByLabel(buildMenuTemplate(makeDeps(deps)), 'View')?.submenu as
+ | MenuItemConstructorOptions[]
+ | undefined;
+ return sub?.map((i) => (i.role ? `[role:${i.role}]` : (i.label ?? '[sep]'))) ?? [];
+ };
+
+ test('a project window offers Hide Editor while the editor shows and Show Editor once hidden, with no shortcut', () => {
+ const shown = buildMenuTemplate(makeDeps({ onToggleEditor: vi.fn(() => {}) }));
+ expect(findByLabel(shown, 'Hide Editor')).toBeDefined();
+ expect(findByLabel(shown, 'Hide Editor')?.accelerator).toBeUndefined();
+ const hidden = buildMenuTemplate(
+ makeDeps({ onToggleEditor: vi.fn(() => {}), editorVisible: false }),
+ );
+ expect(findByLabel(hidden, 'Show Editor')).toBeDefined();
+ expect(findByLabel(hidden, 'Hide Editor')).toBeUndefined();
+ });
+
+ test('clicking it sends the toggle to the renderer', () => {
+ const onToggleEditor = vi.fn(() => {});
+ const template = buildMenuTemplate(makeDeps({ onToggleEditor }));
+ (findByLabel(template, 'Hide Editor')?.click as (() => void) | undefined)?.();
+ expect(onToggleEditor).toHaveBeenCalledOnce();
+ });
+
+ test('sits before Terminal and Agents in the View panel cluster', () => {
+ const labels = viewLabels({
+ onToggleEditor: vi.fn(() => {}),
+ onToggleTerminal: vi.fn(() => {}),
+ onToggleAgentPanel: vi.fn(() => {}),
+ });
+ expect(labels.indexOf('Hide Editor')).toBeGreaterThanOrEqual(0);
+ expect(labels.indexOf('Hide Editor')).toBeLessThan(labels.indexOf('Show Terminal'));
+ expect(labels.indexOf('Show Terminal')).toBeLessThan(labels.indexOf('Show Agents'));
+ });
+
+ test('single-file and note windows do not offer it', () => {
+ for (const deps of [{ singleFileWindow: true }, { noteWindow: true }]) {
+ const labels = viewLabels({ ...deps, onToggleEditor: vi.fn(() => {}) });
+ expect(labels).not.toContain('Hide Editor');
+ expect(labels).not.toContain('Show Editor');
+ }
+ });
+});
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index 5122dc60d..6e62eece7 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -275,6 +275,7 @@ describe('state-store (terminal full-restart state)', () => {
terminalVisible: false,
terminalSnapshot: { tabs: [], activeOrdinal: null },
agentPanelVisible: false,
+ editorVisible: true,
});
});
@@ -289,6 +290,7 @@ describe('state-store (terminal full-restart state)', () => {
activeOrdinal: 1,
},
agentPanelVisible: false,
+ editorVisible: true,
});
const parsed = parseAppState(JSON.parse(JSON.stringify(state)));
expect(getTerminalDockState(parsed ?? emptyState(), '/tmp/project')).toEqual(
@@ -322,15 +324,36 @@ describe('state-store (terminal full-restart state)', () => {
activeOrdinal: null,
},
agentPanelVisible: false,
+ editorVisible: true,
});
});
+ test('a saved hidden editor round-trips, and a record from before the editor field reads as shown', () => {
+ const hidden = setTerminalDockState(emptyState(), '/tmp/project', {
+ terminalVisible: false,
+ terminalSnapshot: { tabs: [], activeOrdinal: null },
+ agentPanelVisible: false,
+ editorVisible: false,
+ });
+ const reparsed = parseAppState(JSON.parse(JSON.stringify(hidden)));
+ expect(getTerminalDockState(reparsed ?? emptyState(), '/tmp/project').editorVisible).toBe(
+ false,
+ );
+
+ const legacy = parseAppState({
+ recentProjects: [],
+ terminalDockStates: { '/tmp/project': { terminalVisible: true, agentPanelVisible: true } },
+ });
+ expect(getTerminalDockState(legacy ?? emptyState(), '/tmp/project').editorVisible).toBe(true);
+ });
+
test('removing a recent project also removes its terminal state', () => {
let state = addRecentProject(emptyState(), '/tmp/project', 'project');
state = setTerminalDockState(state, '/tmp/project', {
terminalVisible: true,
terminalSnapshot: { tabs: [{ ordinal: 1, customLabel: null }], activeOrdinal: 1 },
agentPanelVisible: false,
+ editorVisible: true,
});
expect(removeRecentProject(state, '/tmp/project').terminalDockStates).toEqual({});
});
diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
index a3d3baa2d..0887e5aea 100644
--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts
+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
@@ -2,6 +2,7 @@ import { setTimeout as wait } from 'node:timers/promises';
import { getLocalDir } from '@inkeep/open-knowledge-server';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
+import type { WindowChromeKind } from '../../src/main/window-chrome.ts';
import {
type BrowserWindowLike,
type EphemeralOpenIdentity,
@@ -64,7 +65,11 @@ function makeWindow(): FakeWindow {
interface EphemeralEnv {
deps: WindowManagerDeps;
windows: FakeWindow[];
- createWindowOpts: Array<{ additionalArguments: string[]; title: string }>;
+ createWindowOpts: Array<{
+ additionalArguments: string[];
+ title: string;
+ chrome?: WindowChromeKind;
+ }>;
spawnCalls: Array<{
contentDir: string;
reactShellDistDir: string;
@@ -81,7 +86,11 @@ interface EphemeralEnv {
function buildEphemeralEnv(): EphemeralEnv {
const windows: FakeWindow[] = [];
- const createWindowOpts: Array<{ additionalArguments: string[]; title: string }> = [];
+ const createWindowOpts: Array<{
+ additionalArguments: string[];
+ title: string;
+ chrome?: WindowChromeKind;
+ }> = [];
const spawnCalls: EphemeralEnv['spawnCalls'] = [];
const createTempCalls: string[] = [];
const removedDirs: string[] = [];
@@ -227,6 +236,7 @@ describe('createEphemeralWindow', () => {
expect(env.createWindowOpts[0]?.additionalArguments).toContain(`--ok-project-path=${PARENT}`);
expect(env.createWindowOpts[0]?.additionalArguments).toContain('--ok-single-file=1');
expect(env.createWindowOpts[0]?.additionalArguments).toContain('--ok-initial-doc=todo');
+ expect(env.createWindowOpts[0]?.chrome).toBe('app-header');
expect(ctx.ephemeral).toEqual({
projectDir: '/tmp/ok-ephemeral-1',
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index f70148425..6f315c540 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -9,6 +9,7 @@ import { failedOpenHolder, promptHolderStop } from '../../src/main/holder-stop-p
import { resolveLocalOpCliInvocation } from '../../src/main/local-op-cli-invocation.ts';
import { breakServerLockHeldBy } from '../../src/main/server-lock-break.ts';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
+import type { WindowChromeKind } from '../../src/main/window-chrome.ts';
import {
type BrowserWindowLike,
isOtherChannelHolderError,
@@ -129,6 +130,7 @@ interface TestEnv {
additionalArguments: string[];
title: string;
projectPath?: string;
+ chrome?: WindowChromeKind;
}>;
forkUtilityArgs: string[][];
forkUtilityOpts: Array<{ windowLifecycleBound?: boolean; serviceName: string }>;
@@ -147,6 +149,7 @@ function buildEnv(): TestEnv {
additionalArguments: string[];
title: string;
projectPath?: string;
+ chrome?: WindowChromeKind;
}> = [];
const forkUtilityArgs: string[][] = [];
const forkUtilityOpts: Array<{ windowLifecycleBound?: boolean; serviceName: string }> = [];
@@ -238,6 +241,14 @@ describe('WindowManager', () => {
expect(env.createWindowOpts[0]?.projectPath).toBe(ctx.projectPath);
});
+ test('createProjectWindow asks for the app-header window chrome', async () => {
+ const wm = new WindowManager(env.deps);
+ const promise = wm.createProjectWindow({ projectPath: '/tmp/dragon-wiki' });
+ env.utilities[0]?.fire({ type: 'ready', port: 52010, apiOrigin: 'http://localhost:52010' });
+ await promise;
+ expect(env.createWindowOpts[0]?.chrome).toBe('app-header');
+ });
+
test('createProjectWindow injects --ok-fresh-create=1 only when freshlyCreated is set', async () => {
const wmFresh = new WindowManager(env.deps);
const freshPromise = wmFresh.createProjectWindow({
@@ -1262,6 +1273,16 @@ describe('WindowManager', () => {
expect(env.createWindowOpts[0]?.projectPath).toBe(ctx.projectPath);
});
+ test('an attach-mode project window asks for the app-header window chrome', async () => {
+ enableAttachProbe();
+
+ const wm = new WindowManager(env.deps);
+ await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
+
+ expect(env.utilities.length).toBe(0);
+ expect(env.createWindowOpts[0]?.chrome).toBe('app-header');
+ });
+
test('an attach-mode window resolves to its project while its renderer loads', async () => {
enableAttachProbe();
let releaseLoad: (() => void) | undefined;
diff --git a/packages/desktop/tests/smoke/_helpers/dom-state.ts b/packages/desktop/tests/smoke/_helpers/dom-state.ts
new file mode 100644
index 000000000..a9892428c
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/dom-state.ts
@@ -0,0 +1,90 @@
+import type { ElectronApplication, Page, TestInfo } from '@playwright/test';
+
+const BOUND_MS = 5_000;
+
+function bounded<T>(work: Promise<T>, label: string): Promise<T> {
+ return Promise.race([
+ work,
+ new Promise<T>((_, reject) =>
+ setTimeout(() => reject(new Error(`${label} exceeded ${BOUND_MS}ms`)), BOUND_MS),
+ ),
+ ]);
+}
+
+function reasonOf(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+export async function describeDomState(page: Page): Promise<string> {
+ try {
+ return await bounded(
+ page.evaluate(() => {
+ const label = (el: Element) =>
+ `${el.tagName.toLowerCase()}[${el.getAttribute('role') ?? '-'}][${
+ el.getAttribute('data-testid') ?? el.getAttribute('data-slot') ?? (el.id || '-')
+ }]`;
+ const active = document.activeElement;
+ const paneButtons = document.querySelector(
+ 'header[data-app-header] [data-testid="header-pane-buttons"]',
+ );
+ return JSON.stringify({
+ hasFocus: document.hasFocus(),
+ activeElement: active ? label(active) : null,
+ ariaHiddenRoots: [...document.body.children]
+ .filter((el) => el.getAttribute('aria-hidden') === 'true')
+ .map(label),
+ openLayers: [...document.querySelectorAll('[data-state="open"]')].map(label).slice(0, 24),
+ menus: document.querySelectorAll('[role="menu"]').length,
+ dialogs: document.querySelectorAll('[role="dialog"], [role="alertdialog"]').length,
+ crashInviteDialog:
+ document.querySelector('[role="dialog"] [data-testid="report-bug-crash-invite"]') !==
+ null,
+ headerPaneButtons:
+ paneButtons === null
+ ? 'absent'
+ : paneButtons.closest('[aria-hidden="true"]')
+ ? 'inside an aria-hidden subtree'
+ : 'present',
+ });
+ }),
+ 'dom state',
+ );
+ } catch (error) {
+ return `unavailable: ${reasonOf(error)}`;
+ }
+}
+
+async function ariaSnapshotOf(page: Page): Promise<string> {
+ try {
+ return await bounded(page.locator('body').ariaSnapshot({ timeout: BOUND_MS }), 'aria snapshot');
+ } catch (error) {
+ return `unavailable: ${reasonOf(error)}`;
+ }
+}
+
+export async function attachDomState(testInfo: TestInfo, page: Page, name: string): Promise<void> {
+ const [state, aria] = await Promise.all([describeDomState(page), ariaSnapshotOf(page)]);
+ try {
+ await testInfo.attach(name, {
+ body: `${page.url()}\n\n${state}\n\n${aria}`,
+ contentType: 'text/plain',
+ });
+ } catch (error) {
+ console.warn(`[smoke-test] ${name} attach failed: ${reasonOf(error)}`);
+ }
+}
+
+export async function attachDomStateOnFailure(
+ testInfo: TestInfo,
+ apps: readonly ElectronApplication[],
+): Promise<void> {
+ if (testInfo.status === testInfo.expectedStatus) return;
+ let index = 0;
+ for (const app of apps) {
+ for (const page of app.windows()) {
+ if (page.isClosed()) continue;
+ index += 1;
+ await attachDomState(testInfo, page, `dom-state-${index}`);
+ }
+ }
+}
diff --git a/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts b/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
index b41b510bd..dc1de9e92 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
@@ -15,6 +15,7 @@ import { SPAWN_STARTUP_DEADLINE_MS } from '../../../src/shared/boot-narration.ts
import {
DEFAULT_LAUNCH_TIMEOUT_MS,
DEFAULT_LOCAL_PACKAGED_APP,
+ DESKTOP_ROOT,
desktopLaunchOptions,
executableForAppBundle,
PACKAGED_APP_ENV,
@@ -51,28 +52,62 @@ describe('resolveDesktopTarget', () => {
});
it('resolves the bundle executable when the override names an .app', () => {
- const target = resolveDesktopTarget({ env: { [PACKAGED_APP_ENV]: '/mnt/OpenKnowledge.app' } });
+ const target = resolveDesktopTarget({
+ env: { [PACKAGED_APP_ENV]: '/mnt/OpenKnowledge.app' },
+ platform: 'darwin',
+ });
expect(target.mode).toBe('packaged');
expect(target.appPath).toBe('/mnt/OpenKnowledge.app');
expect(target.targetPath).toBe('/mnt/OpenKnowledge.app/Contents/MacOS/OpenKnowledge');
});
it('falls back to the local packaged build for packaged-only suites', () => {
- const target = resolveDesktopTarget({ env: {}, requirePackaged: true });
+ const target = resolveDesktopTarget({ env: {}, requirePackaged: true, platform: 'darwin' });
expect(target.mode).toBe('packaged');
expect(target.appPath).toBe(DEFAULT_LOCAL_PACKAGED_APP);
});
+ it.each([
+ ['x64', 'linux-unpacked'],
+ ['arm64', 'linux-arm64-unpacked'],
+ ] as const)('resolves the canonical %s Linux packaged executable', (arch, directory) => {
+ const target = resolveDesktopTarget({
+ env: {},
+ requirePackaged: true,
+ platform: 'linux',
+ arch,
+ });
+ expect(target.mode).toBe('packaged');
+ expect(target.appPath).toBe(join(DESKTOP_ROOT, 'dist-desktop', directory));
+ expect(target.targetPath).toBe(join(DESKTOP_ROOT, 'dist-desktop', directory, 'openknowledge'));
+ });
+
+ it('resolves a Linux unpacked directory override to its packaged executable', () => {
+ const target = resolveDesktopTarget({
+ env: { [PACKAGED_APP_ENV]: '/mnt/linux-unpacked' },
+ requirePackaged: true,
+ platform: 'linux',
+ arch: 'x64',
+ });
+ expect(target.appPath).toBe('/mnt/linux-unpacked');
+ expect(target.targetPath).toBe('/mnt/linux-unpacked/openknowledge');
+ expect(target.exists).toBe(false);
+ });
+
it('lets the override win over the packaged-only fallback', () => {
const target = resolveDesktopTarget({
env: { [PACKAGED_APP_ENV]: '/mnt/OpenKnowledge.app' },
requirePackaged: true,
+ platform: 'darwin',
});
expect(target.appPath).toBe('/mnt/OpenKnowledge.app');
});
it('reports a mode-appropriate skip reason', () => {
- const missing = resolveDesktopTarget({ env: { [PACKAGED_APP_ENV]: '/nope/Absent.app' } });
+ const missing = resolveDesktopTarget({
+ env: { [PACKAGED_APP_ENV]: '/nope/Absent.app' },
+ platform: 'darwin',
+ });
expect(missing.missingReason).toContain('/nope/Absent.app/Contents/MacOS/Absent');
expect(resolveDesktopTarget({ env: {} }).missingReason).toContain('pnpm run build:desktop');
expect(resolveDesktopTarget({ env: {} }).missingReason).not.toContain('bun run');
@@ -83,6 +118,7 @@ describe('resolveDesktopTarget', () => {
try {
const target = resolveDesktopTarget({
env: { [PACKAGED_APP_ENV]: join(root, 'Absent.app') },
+ platform: 'darwin',
});
expect(target.exists).toBe(false);
mkdirSync(dirname(target.targetPath), { recursive: true });
diff --git a/packages/desktop/tests/smoke/_helpers/launch-desktop.ts b/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
index f0d946eb0..f0a87df7d 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
@@ -36,6 +36,8 @@ export interface DesktopTarget {
export interface ResolveDesktopTargetOptions {
env?: NodeJS.ProcessEnv;
requirePackaged?: boolean;
+ platform?: NodeJS.Platform;
+ arch?: NodeJS.Architecture;
}
export function executableForAppBundle(appPath: string): string {
@@ -51,18 +53,28 @@ function probedOnRead(target: Omit<DesktopTarget, 'exists'>): DesktopTarget {
};
}
+function defaultPackagedAppPath(platform: NodeJS.Platform, arch: NodeJS.Architecture): string {
+ if (platform !== 'linux') return DEFAULT_LOCAL_PACKAGED_APP;
+ if (arch === 'x64') return join(DESKTOP_ROOT, 'dist-desktop', 'linux-unpacked');
+ if (arch === 'arm64') return join(DESKTOP_ROOT, 'dist-desktop', 'linux-arm64-unpacked');
+ throw new Error(`No local Linux packaged desktop target for architecture ${arch}`);
+}
+
export function resolveDesktopTarget(options: ResolveDesktopTargetOptions = {}): DesktopTarget {
const env = options.env ?? process.env;
+ const platform = options.platform ?? process.platform;
+ const arch = options.arch ?? process.arch;
const override = env[PACKAGED_APP_ENV];
const appPath =
override && override.length > 0
? resolve(override)
: options.requirePackaged
- ? DEFAULT_LOCAL_PACKAGED_APP
+ ? defaultPackagedAppPath(platform, arch)
: undefined;
if (appPath !== undefined) {
- const targetPath = executableForAppBundle(appPath);
+ const targetPath =
+ platform === 'linux' ? join(appPath, 'openknowledge') : executableForAppBundle(appPath);
return probedOnRead({
mode: 'packaged',
appPath,
diff --git a/packages/desktop/tests/smoke/_helpers/platform-gate.ts b/packages/desktop/tests/smoke/_helpers/platform-gate.ts
index 046807382..ce86fed16 100644
--- a/packages/desktop/tests/smoke/_helpers/platform-gate.ts
+++ b/packages/desktop/tests/smoke/_helpers/platform-gate.ts
@@ -25,7 +25,7 @@ export function userDataDirFor(tmpHome: string): string {
export const SPEC_PLATFORM_GATES = {
'agent-patch-divergence-probe.e2e.ts': ['!PLATFORM_SUPPORTED'],
'background-throttle.e2e.ts': ['!PLATFORM_SUPPORTED'],
- 'cold-single-file-launch.e2e.ts': ['!DARWIN'],
+ 'cold-single-file-launch.e2e.ts': ['!DARWIN', '!DARWIN'],
'consent-dialog.e2e.ts': ['!PLATFORM_SUPPORTED'],
'create-new-project.e2e.ts': ['!PLATFORM_SUPPORTED'],
'deep-link.e2e.ts': ['!DARWIN'],
@@ -43,7 +43,6 @@ export const SPEC_PLATFORM_GATES = {
'share-receive-miss-terminal.e2e.ts': ['!PLATFORM_SUPPORTED'],
'share-receive-multi-worktree.e2e.ts': ['!DARWIN'],
'sidebar-create-rename-editable.e2e.ts': ['!DARWIN'],
- 'sidebar-pill-lockstep-fade.e2e.ts': ['!DARWIN'],
'skill-scope-roundtrip.e2e.ts': ['!DARWIN'],
'skills-studio.e2e.ts': ['!DARWIN'],
'slidev-render-readiness.e2e.ts': ['!PLATFORM_SUPPORTED'],
diff --git a/packages/desktop/tests/smoke/_helpers/smoke-test.ts b/packages/desktop/tests/smoke/_helpers/smoke-test.ts
index 9cc519c9a..6b01039a1 100644
--- a/packages/desktop/tests/smoke/_helpers/smoke-test.ts
+++ b/packages/desktop/tests/smoke/_helpers/smoke-test.ts
@@ -2,6 +2,7 @@ import type { ChildProcess } from 'node:child_process';
import { rmSync } from 'node:fs';
import { expect as baseExpect, test as baseTest, type ElectronApplication } from '@playwright/test';
import { emitBootGapLines } from './boot-gap-emit';
+import { attachDomStateOnFailure } from './dom-state';
import {
captureAppProcess,
cleanupIncompleteReport,
@@ -40,6 +41,7 @@ export const test = baseTest.extend<SmokeFixtures>({
}
});
await emitBootGapLines(apps, testInfo);
+ await attachDomStateOnFailure(testInfo, apps);
const { unclosed, survivors, closedAfterServerRelease } = await closeAppsThenAwaitServerRelease(
procs,
cleanupDirs,
diff --git a/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts b/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts
index 181225329..945ee956d 100644
--- a/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts
+++ b/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts
@@ -32,6 +32,12 @@ export interface TerminalSmokeShellCommands {
readEnvironment(name: string, label: string): string;
scroll(sentinel: string, start: string, prefix: string, count: number): string;
setEnvironment(name: string, value: string): string;
+ waitForFileThenOutput(
+ releasePath: string,
+ waitingPath: string,
+ acknowledgementPath: string,
+ waitingMarker: string,
+ ): string;
workingDirectory(marker: string): string;
}
@@ -58,6 +64,8 @@ export function terminalSmokeShellCommands(
validateEnvironmentName(name);
return `$env:${name}=${psQuoteArg(value)}`;
},
+ waitForFileThenOutput: (releasePath, waitingPath, acknowledgementPath, waitingMarker) =>
+ `Write-Output ${psQuoteArg(waitingMarker)}; Set-Content -LiteralPath ${psQuoteArg(waitingPath)} -Value ${psQuoteArg(waitingMarker)}; $okWait=0; while (-not (Test-Path -LiteralPath ${psQuoteArg(releasePath)}) -and $okWait -lt 300) { Start-Sleep -Milliseconds 100; $okWait++ }; if (Test-Path -LiteralPath ${psQuoteArg(releasePath)}) { $okResult=Get-Content -LiteralPath ${psQuoteArg(releasePath)}; Write-Output $okResult; Set-Content -LiteralPath ${psQuoteArg(acknowledgementPath)} -Value $okResult }`,
workingDirectory: (marker) =>
`Write-Output (${psQuoteArg(marker)} + '=[' + (Get-Location).Path + ']')`,
};
@@ -81,6 +89,8 @@ export function terminalSmokeShellCommands(
validateEnvironmentName(name);
return `export ${name}=${quotePosix(value)}`;
},
+ waitForFileThenOutput: (releasePath, waitingPath, acknowledgementPath, waitingMarker) =>
+ `printf '%s\\n' ${quotePosix(waitingMarker)}; printf '%s\\n' ${quotePosix(waitingMarker)} > ${quotePosix(waitingPath)}; ok_wait=0; while [ ! -f ${quotePosix(releasePath)} ] && [ "$ok_wait" -lt 300 ]; do sleep 0.1; ok_wait=$((ok_wait+1)); done; if [ -f ${quotePosix(releasePath)} ]; then cat ${quotePosix(releasePath)}; cp ${quotePosix(releasePath)} ${quotePosix(acknowledgementPath)}; fi`,
workingDirectory: (marker) => `printf '%s=[%s]\\n' ${quotePosix(marker)} "$PWD"`,
};
}
diff --git a/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts b/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts
index bca16b819..cad0ed1d5 100644
--- a/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts
+++ b/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts
@@ -1,5 +1,7 @@
import { execFileSync } from 'node:child_process';
import {
+ accessSync,
+ constants,
existsSync,
mkdirSync,
mkdtempSync,
@@ -7,17 +9,23 @@ import {
readFileSync,
realpathSync,
rmSync,
+ statSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, dirname, join } from 'node:path';
-import { expect, test } from '@playwright/test';
+import type { ElectronApplication, Page } from '@playwright/test';
+import { _electron as electron, expect } from '@playwright/test';
import {
configureEphemeralGitRepositories,
configureProjectGitRepositories,
readTestServerRepository,
} from '../support/git-fixture.test-helper';
-import { resolveDesktopTarget } from './_helpers/launch-desktop';
+import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
+import { homeEnv, userDataDirFor } from './_helpers/platform-gate';
+import { test } from './_helpers/smoke-test';
+import { waitForShellReady } from './_helpers/terminal-ready';
+import { terminalSmokeShellCommands } from './_helpers/terminal-smoke-shell';
const TARGET = resolveDesktopTarget({ requirePackaged: true });
const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
@@ -70,6 +78,22 @@ function makeLooseFile(): { dir: string; file: string } {
return { dir, file };
}
+async function readVisibleTerminalText(page: Page): Promise<string> {
+ return page
+ .locator('section[aria-label="Terminal"]:visible')
+ .first()
+ .evaluate((terminal) => {
+ const accessible = terminal.querySelector('.xterm-accessibility')?.textContent ?? '';
+ const rows = terminal.querySelector('.xterm-rows')?.textContent ?? '';
+ return `${accessible}\n${rows}`;
+ });
+}
+
+async function typeInVisibleTerminal(page: Page, command: string): Promise<void> {
+ await page.locator('section[aria-label="Terminal"]:visible .xterm').click();
+ await page.keyboard.type(`${command}\r`);
+}
+
interface BootRestoreDecisionLog {
urlLaunch: boolean;
action: string;
@@ -220,3 +244,238 @@ test.describe('cold launch with an explicit target owns the initial window set',
}
});
});
+
+test.describe('packaged single-file shared shell', () => {
+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
+ test.skip(!DARWIN, 'The packaged single-file shell case runs in the macOS packaged lane.');
+ test.skip(!TARGET.exists, TARGET.missingReason);
+
+ test('a packaged single-file window keeps its shared header above cards through narrow selection', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(180_000);
+ expect(statSync(TARGET.targetPath).isFile()).toBe(true);
+ accessSync(TARGET.targetPath, constants.X_OK);
+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), 'ok-single-file-shell-home-')));
+ const loose = makeLooseFile();
+ let app: ElectronApplication | null = null;
+ let registered = false;
+
+ try {
+ app = await electron.launch(
+ desktopLaunchOptions({
+ target: TARGET,
+ args: [
+ `--user-data-dir=${userDataDirFor(tmpHome)}`,
+ `openknowledge://open?file=${encodeURIComponent(loose.file)}`,
+ ],
+ env: {
+ ...process.env,
+ ...homeEnv(tmpHome),
+ OK_DESKTOP_E2E_SMOKE: '1',
+ },
+ }),
+ );
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, loose.dir] });
+ registered = true;
+ let editor: Page | undefined;
+ await expect
+ .poll(
+ async () => {
+ for (const page of app?.windows() ?? []) {
+ const singleFile = await page
+ .evaluate(() => window.okDesktop?.config.singleFile)
+ .catch(() => false);
+ if (singleFile === true) {
+ editor = page;
+ return true;
+ }
+ }
+ return false;
+ },
+ { timeout: 60_000 },
+ )
+ .toBe(true);
+ if (!editor) throw new Error('the single-file window disappeared after becoming ready');
+ const readyEditor = editor;
+ const consentSkip = editor.getByTestId('mcp-consent-skip');
+ await expect(consentSkip).toBeVisible();
+ await consentSkip.click();
+ await expect(consentSkip).toBeHidden();
+
+ const globalHeader = editor.locator('header[data-app-header]');
+ const editorCard = editor.locator('[data-slot="pane-card"][data-pane="editor"]');
+ const chatCard = editor.locator('[data-slot="pane-card"][data-pane="agents"]');
+ const editorButton = globalHeader.getByTestId('header-pane-button-editor');
+ const chatButton = globalHeader.getByTestId('header-pane-button-agents');
+ const terminalButton = globalHeader.getByTestId('header-pane-button-terminal');
+ await expect(globalHeader).toHaveCount(1);
+ await expect(editorCard).toHaveAttribute('data-variant', 'card');
+ await expect(chatCard).toHaveAttribute('data-variant', 'card');
+ await expect(editorCard.locator('header[data-editor-header]')).toContainText('standalone');
+ await expect(
+ editorCard.locator('header[data-editor-header] [data-doc-panel-toggle]'),
+ ).toBeVisible();
+ await expect(globalHeader.locator('[data-doc-panel-toggle]')).toHaveCount(0);
+ await expect(editor.getByTestId('project-switcher-trigger')).toHaveCount(0);
+ await expect(editor.getByTestId('share-button')).toHaveCount(0);
+ await expect(terminalButton).toBeVisible();
+ await expect(chatCard).toBeHidden();
+
+ const winHandle = await app.browserWindow(editor);
+ await winHandle.evaluate((win: unknown) => {
+ (
+ win as { setContentSize: (width: number, height: number, animate: boolean) => void }
+ ).setContentSize(1000, 600, false);
+ });
+ await expect.poll(() => readyEditor.evaluate(() => window.innerWidth)).toBe(1000);
+ const panelHandle = editor.locator('[data-doc-panel-handle]');
+ const handleBounds = await panelHandle.boundingBox();
+ if (!handleBounds) throw new Error('the docked document panel has no resize handle');
+ const handleY = handleBounds.y + handleBounds.height / 2;
+ await editor.mouse.move(handleBounds.x + handleBounds.width / 2, handleY);
+ await editor.mouse.down();
+ await editor.mouse.move(handleBounds.x - 280, handleY, { steps: 8 });
+ await editor.mouse.up();
+ await expect
+ .poll(async () => (await readyEditor.locator('#doc-panel').boundingBox())?.width ?? 0)
+ .toBeGreaterThan(500);
+ await winHandle.evaluate((win: unknown) => {
+ (
+ win as { setContentSize: (width: number, height: number, animate: boolean) => void }
+ ).setContentSize(767, 600, false);
+ });
+ await expect.poll(() => readyEditor.evaluate(() => window.innerWidth)).toBe(767);
+ await expect(editor.locator('#doc-panel')).toBeHidden();
+ await editorCard.locator('header[data-editor-header] [data-doc-panel-toggle]').click();
+ const informationCover = editor.locator('[data-doc-panel-cover]');
+ await expect(informationCover).toBeVisible();
+ for (const label of ['Outline', 'Problems', 'Comments']) {
+ await expect(informationCover.getByRole('tab', { name: label })).toBeVisible();
+ }
+ for (const label of ['Links', 'Graph', 'Timeline']) {
+ await expect(informationCover.getByRole('tab', { name: label })).toHaveCount(0);
+ }
+ await editor.locator('[data-doc-panel-back]').click();
+ await chatButton.click();
+ await expect(chatButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(editorCard).toBeHidden();
+ await expect(chatCard).toBeVisible();
+ await editorButton.click();
+ await expect(editorCard).toBeVisible();
+ await expect(chatCard).toBeHidden();
+ await terminalButton.click();
+ await expect(terminalButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(editorCard).toBeHidden();
+ await expect(chatCard).toBeHidden();
+ await expect(
+ editor.locator('[data-slot="pane-card"][data-pane="terminal"]:visible'),
+ ).toHaveCount(1);
+ const terminalStatus = editor.locator(
+ 'section[aria-label="Terminal"]:visible [data-terminal-status]',
+ );
+ await expect(terminalStatus).toHaveAttribute('data-terminal-status', 'running');
+ await waitForShellReady(
+ () => readVisibleTerminalText(readyEditor),
+ (command) => typeInVisibleTerminal(readyEditor, command),
+ );
+ const initialSessions = await editor.evaluate(() => window.okDesktop?.terminal.list());
+ expect(initialSessions).toHaveLength(1);
+ const ptyId = initialSessions?.[0]?.ptyId;
+ expect(ptyId).toBeTruthy();
+ const shell = terminalSmokeShellCommands();
+ await typeInVisibleTerminal(
+ readyEditor,
+ shell.setEnvironment('OK_SINGLE_FILE_SHELL', 'OK_SINGLE_FILE_SURVIVED_684'),
+ );
+ await typeInVisibleTerminal(
+ readyEditor,
+ shell.readEnvironment('OK_SINGLE_FILE_SHELL', 'before'),
+ );
+ await expect
+ .poll(() => readVisibleTerminalText(readyEditor))
+ .toContain('before=[OK_SINGLE_FILE_SURVIVED_684]');
+ const waitingPath = join(loose.dir, 'single-file-terminal-waiting');
+ const releasePath = join(loose.dir, 'single-file-terminal-release');
+ const acknowledgementPath = join(loose.dir, 'single-file-terminal-completed');
+ await typeInVisibleTerminal(
+ readyEditor,
+ shell.waitForFileThenOutput(
+ releasePath,
+ waitingPath,
+ acknowledgementPath,
+ 'OK_SINGLE_FILE_WAITING_684',
+ ),
+ );
+ await expect.poll(() => existsSync(waitingPath)).toBe(true);
+ await chatButton.click();
+ await expect(chatCard).toBeVisible();
+ await expect(terminalStatus).toBeHidden();
+ writeFileSync(releasePath, 'OK_SINGLE_FILE_COMPLETED_684\n');
+ await expect.poll(() => existsSync(acknowledgementPath)).toBe(true);
+ expect(readFileSync(acknowledgementPath, 'utf8')).toContain('OK_SINGLE_FILE_COMPLETED_684');
+ expect((await editor.evaluate(() => window.okDesktop?.terminal.list()))?.[0]?.ptyId).toBe(
+ ptyId,
+ );
+ await editorButton.click();
+ await expect(editorCard).toBeVisible();
+ await expect(
+ editor.locator('[data-slot="pane-card"][data-pane="terminal"]:visible'),
+ ).toHaveCount(0);
+ expect((await editor.evaluate(() => window.okDesktop?.terminal.list()))?.[0]?.ptyId).toBe(
+ ptyId,
+ );
+ expect(await editor.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
+ true,
+ );
+
+ await winHandle.evaluate((win: unknown) => {
+ (
+ win as { setContentSize: (width: number, height: number, animate: boolean) => void }
+ ).setContentSize(720, 480, false);
+ });
+ await expect.poll(() => readyEditor.evaluate(() => window.innerWidth)).toBe(720);
+ await expect(editorButton).toBeVisible();
+ await expect(chatButton).toBeVisible();
+ await expect(terminalButton).toBeVisible();
+ await expect(editorCard).toBeVisible();
+ expect(await editor.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
+ true,
+ );
+
+ await winHandle.evaluate((win: unknown) => {
+ (
+ win as { setContentSize: (width: number, height: number, animate: boolean) => void }
+ ).setContentSize(900, 600, false);
+ });
+ await expect.poll(() => readyEditor.evaluate(() => window.innerWidth)).toBe(900);
+ await expect(editorCard).toBeVisible();
+ await expect(chatCard).toBeHidden();
+ await chatButton.click();
+ await expect(editorCard).toBeVisible();
+ await expect(chatCard).toBeVisible();
+ await terminalButton.click();
+ await expect(terminalStatus).toHaveAttribute('data-terminal-status', 'running');
+ expect((await editor.evaluate(() => window.okDesktop?.terminal.list()))?.[0]?.ptyId).toBe(
+ ptyId,
+ );
+ await expect
+ .poll(() => readVisibleTerminalText(readyEditor))
+ .toContain('OK_SINGLE_FILE_COMPLETED_684');
+ await typeInVisibleTerminal(
+ readyEditor,
+ shell.readEnvironment('OK_SINGLE_FILE_SHELL', 'after'),
+ );
+ await expect
+ .poll(() => readVisibleTerminalText(readyEditor))
+ .toContain('after=[OK_SINGLE_FILE_SURVIVED_684]');
+ await expect(globalHeader).toHaveCount(1);
+ } finally {
+ void app?.close().catch(() => undefined);
+ if (!registered) {
+ rmSync(tmpHome, { recursive: true, force: true });
+ rmSync(loose.dir, { recursive: true, force: true });
+ }
+ }
+ });
+});
diff --git a/packages/desktop/tests/smoke/note-window.e2e.ts b/packages/desktop/tests/smoke/note-window.e2e.ts
index 02f98e62f..3be0e8d42 100644
--- a/packages/desktop/tests/smoke/note-window.e2e.ts
+++ b/packages/desktop/tests/smoke/note-window.e2e.ts
@@ -12,7 +12,7 @@ import {
SMOKE_ENABLED,
userDataDirFor,
} from './_helpers/platform-gate';
-import { expect, test } from './_helpers/smoke-test';
+import { expect, type SmokeFixtures, test } from './_helpers/smoke-test';
const TARGET = resolveDesktopTarget();
@@ -157,6 +157,18 @@ function track(...paths: string[]): void {
cleanup.push(...paths);
}
+function registerAppCleanup(
+ captureStderrFor: SmokeFixtures['captureStderrFor'],
+ app: ElectronApplication,
+ s: Seed,
+): void {
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ for (const path of [s.tmpHome, s.projectDir]) {
+ const index = cleanup.indexOf(path);
+ if (index >= 0) cleanup.splice(index, 1);
+ }
+}
+
test.describe('Popped-out note window — live Electron', () => {
test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
test.skip(!PLATFORM_SUPPORTED, PLATFORM_SKIP_REASON);
@@ -175,10 +187,11 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('open');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, app, s);
const editor = await findWindowByMode(app, 'editor');
await configureDesktopGitRepositories(editor, s.projectDir);
await openDocument(editor, 'start');
+ await expect(editor.getByTestId('header-pane-button-agents')).toBeVisible();
await popOutFrom(app, editor);
const note = await findWindowByMode(app, 'note');
@@ -190,8 +203,9 @@ test.describe('Popped-out note window — live Electron', () => {
await expect(note.locator('[data-sidebar="trigger"]')).toHaveCount(0);
await expect(note.locator('[data-editor-tab-scroll]')).toHaveCount(0);
await expect(note.locator('[data-doc-panel-toggle]')).toHaveCount(0);
- await expect(note.getByRole('button', { name: 'Open agents panel' })).toHaveCount(0);
await expect(note.getByRole('button', { name: 'Resources' })).toHaveCount(0);
+ await expect(note.locator('[data-testid^="header-pane-"]')).toHaveCount(0);
+ await expect(note.getByRole('group', { name: 'Panels', exact: true })).toHaveCount(0);
await expect(note.locator('[data-note-window-mode-toggle]')).toBeVisible();
const noteWindow = await app.browserWindow(note);
@@ -229,7 +243,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('handoff');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, app, s);
const editor = await findWindowByMode(app, 'editor');
await configureDesktopGitRepositories(editor, s.projectDir);
await openDocument(editor, 'start');
@@ -284,14 +298,16 @@ test.describe('Popped-out note window — live Electron', () => {
),
).toEqual({ ok: true });
await expect(editorBody(editor)).toContainText('Second', { timeout: 15_000 });
- await expect(editor.locator('#doc-panel')).toBeVisible({ timeout: 15_000 });
+ await expect(editor.locator('[role="tabpanel"]#panel-comments')).toBeVisible({
+ timeout: 15_000,
+ });
});
test('edits cross both live editor UIs in one app instance', async ({ captureStderrFor }) => {
const s = seed('sync');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, app, s);
const editor = await findWindowByMode(app, 'editor');
await configureDesktopGitRepositories(editor, s.projectDir);
await openDocument(editor, 'start');
@@ -315,7 +331,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('dedup');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, app, s);
const editor = await findWindowByMode(app, 'editor');
await configureDesktopGitRepositories(editor, s.projectDir);
await openDocument(editor, 'start');
@@ -334,7 +350,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('menu');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, app, s);
const editor = await findWindowByMode(app, 'editor');
await configureDesktopGitRepositories(editor, s.projectDir);
await openDocument(editor, 'start');
@@ -373,7 +389,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('cascade');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, app, s);
const editor = await findWindowByMode(app, 'editor');
await configureDesktopGitRepositories(editor, s.projectDir);
await openDocument(editor, 'start');
@@ -408,7 +424,7 @@ test.describe('Popped-out note window — live Electron', () => {
await first.close();
const second = await launchApp(s, { deepLink: false });
- captureStderrFor(second, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ registerAppCleanup(captureStderrFor, second, s);
const restored = await findWindowByMode(second, 'note', 30_000);
expect(await restored.evaluate(() => window.okDesktop?.config.projectPath)).toBe(s.projectDir);
diff --git a/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts b/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts
deleted file mode 100644
index abbb4a863..000000000
--- a/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { execSync } from 'node:child_process';
-import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { _electron as electron } from '@playwright/test';
-import { configureDesktopGitRepositories } from '../support/git-fixture.test-helper.ts';
-import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
-import { expect, test } from './_helpers/smoke-test';
-
-const TARGET = resolveDesktopTarget();
-
-const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
-const DARWIN = process.platform === 'darwin';
-
-function userDataDirFor(home: string): string {
- return join(home, 'electron-userdata');
-}
-
-async function expectDocument(
- page: import('@playwright/test').Page,
- docName: string,
- marker: string,
-): Promise<void> {
- await expect
- .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)))
- .toBe(`#/${docName}`);
- await expect(
- page.locator('.ProseMirror:not(.composer-prosemirror)', { hasText: marker }),
- ).toBeVisible({ timeout: 15_000 });
-}
-
-test.describe('sidebar search pill — Electron lockstep-fade smoke', () => {
- test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
- test.skip(!DARWIN, 'Driver uses macOS open(1) and chrome stack is darwin-only in v0.');
- test.skip(!TARGET.exists, TARGET.missingReason);
-
- test('navigation controls relocate on collapse while sidebar chrome fades in lockstep', async ({
- captureStderrFor,
- }) => {
- test.setTimeout(180_000);
- const docName = `sidebar-pill-${randomUUID()}`;
- const secondDocName = `sidebar-pill-second-${randomUUID()}`;
- const firstMarker = 'Sidebar Pill Lockstep Fade Smoke';
- const secondMarker = 'Sidebar Pill Navigation Second';
- const projectDir = mkdtempSync(join(tmpdir(), 'ok-sidebar-pill-'));
- mkdirSync(join(projectDir, '.ok'), { recursive: true });
- writeFileSync(
- join(projectDir, '.ok', 'config.yml'),
- "content:\n dir: '.'\n include: ['**/*.md']\n exclude: []\n",
- );
- writeFileSync(
- join(projectDir, `${docName}.md`),
- `# ${firstMarker}\n\nFixture for chrome-row collapse verification.\n`,
- );
- writeFileSync(
- join(projectDir, `${secondDocName}.md`),
- `# ${secondMarker}\n\nFixture for browser-history traversal.\n`,
- );
-
- const app = await electron.launch(
- desktopLaunchOptions({
- target: TARGET,
- args: [`--user-data-dir=${userDataDirFor(projectDir)}`],
- timeout: 30_000,
- }),
- );
- captureStderrFor(app, { cleanupDirs: [projectDir] });
-
- const firstWindow = await app.firstWindow({ timeout: 15_000 });
- expect(firstWindow).toBeDefined();
-
- const deepLink = `openknowledge://open?project=${encodeURIComponent(projectDir)}&doc=${encodeURIComponent(docName)}`;
- execSync(`open -g "${deepLink}"`, { stdio: 'pipe' });
-
- let editorPage: import('@playwright/test').Page | undefined;
- const expectedHashSuffix = `#/${docName}`;
- await expect(async () => {
- for (const page of app.windows()) {
- const hash = await page.evaluate(() => window.location.hash).catch(() => '');
- if (hash.endsWith(expectedHashSuffix)) {
- editorPage = page;
- return;
- }
- }
- throw new Error(`no window matches ${expectedHashSuffix} yet`);
- }).toPass({ timeout: 15_000 });
- if (!editorPage) throw new Error('unreachable');
- const page = editorPage;
- await configureDesktopGitRepositories(page, projectDir);
-
- const isElectronHost = await page.evaluate(
- () => typeof window !== 'undefined' && window.okDesktop != null,
- );
- expect(isElectronHost).toBe(true);
- await expectDocument(page, docName, firstMarker);
-
- const pill = page.getByRole('button', { name: /^Search/ });
- await pill.waitFor({ state: 'visible', timeout: 10_000 });
-
- const sidebarHeader = page.locator('[data-slot="sidebar-header"]');
- const editorHeaderLeadingActions = page.locator('[data-editor-header-leading-actions]');
- const backButtons = page.getByRole('button', { name: 'Back', exact: true });
- const forwardButtons = page.getByRole('button', { name: 'Forward', exact: true });
- const sidebarBack = sidebarHeader.getByRole('button', { name: 'Back', exact: true });
- const sidebarForward = sidebarHeader.getByRole('button', { name: 'Forward', exact: true });
- const headerBack = editorHeaderLeadingActions.getByRole('button', {
- name: 'Back',
- exact: true,
- });
- const headerForward = editorHeaderLeadingActions.getByRole('button', {
- name: 'Forward',
- exact: true,
- });
-
- await expect(sidebarBack).toHaveCount(1);
- await expect(sidebarForward).toHaveCount(1);
- await expect(headerBack).toHaveCount(0);
- await expect(headerForward).toHaveCount(0);
- await expect(backButtons).toHaveCount(1);
- await expect(forwardButtons).toHaveCount(1);
-
- await page
- .locator('[data-slot="sidebar-container"]')
- .getByRole('treeitem', { name: `${secondDocName}.md`, exact: true })
- .click();
- await expectDocument(page, secondDocName, secondMarker);
- await sidebarBack.click();
- await expectDocument(page, docName, firstMarker);
- await sidebarForward.click();
- await expectDocument(page, secondDocName, secondMarker);
-
- const collectFadeState = async () => {
- return page.evaluate(() => {
- const header = document.querySelector('[data-slot="sidebar-header"]') as HTMLElement | null;
- const pillButton = document.querySelector(
- 'button[data-telemetry-event="ok.sidebar.search_pill.click"]',
- );
- let pillRow: HTMLElement | null = null;
- if (pillButton) {
- let node: HTMLElement | null = pillButton.parentElement as HTMLElement | null;
- while (node) {
- const next = node.nextElementSibling as HTMLElement | null;
- if (next?.dataset?.slot === 'sidebar-content') {
- pillRow = node;
- break;
- }
- node = node.parentElement as HTMLElement | null;
- }
- }
- return {
- sidebarState:
- document.querySelector('[data-slot="sidebar"]')?.getAttribute('data-state') ?? null,
- headerHasOpacity0: header?.classList.contains('opacity-0') ?? null,
- headerHasTransition: header?.className.includes('motion-safe:transition-opacity') ?? null,
- pillRowHasOpacity0: pillRow?.classList.contains('opacity-0') ?? null,
- pillRowHasTransition:
- pillRow?.className.includes('motion-safe:transition-opacity') ?? null,
- pillRowFound: pillRow !== null,
- headerFound: header !== null,
- };
- });
- };
-
- const expanded = await collectFadeState();
- expect(expanded.headerFound).toBe(true);
- expect(expanded.pillRowFound).toBe(true);
- expect(expanded.sidebarState).toBe('expanded');
- expect(expanded.headerHasOpacity0).toBe(false);
- expect(expanded.pillRowHasOpacity0).toBe(false);
- expect(expanded.headerHasTransition).toBe(true);
- expect(expanded.pillRowHasTransition).toBe(true);
-
- await page.locator('[data-sidebar="trigger"]').first().click();
-
- await expect
- .poll(
- async () =>
- page.evaluate(() =>
- document.querySelector('[data-slot="sidebar"]')?.getAttribute('data-state'),
- ),
- { intervals: [50, 50, 100, 200, 500], timeout: 5_000 },
- )
- .toBe('collapsed');
-
- await expect
- .poll(
- async () => {
- const s = await collectFadeState();
- return s.headerHasOpacity0 && s.pillRowHasOpacity0;
- },
- { intervals: [50, 50, 100, 200], timeout: 2_000 },
- )
- .toBe(true);
-
- const collapsed = await collectFadeState();
- expect(collapsed.sidebarState).toBe('collapsed');
- expect(collapsed.headerHasOpacity0).toBe(true);
- expect(collapsed.pillRowHasOpacity0).toBe(true);
- expect(collapsed.headerHasTransition).toBe(true);
- expect(collapsed.pillRowHasTransition).toBe(true);
-
- await expect(sidebarBack).toHaveCount(0);
- await expect(sidebarForward).toHaveCount(0);
- await expect(headerBack).toHaveCount(1);
- await expect(headerForward).toHaveCount(1);
- await expect(backButtons).toHaveCount(1);
- await expect(forwardButtons).toHaveCount(1);
-
- await headerBack.click();
- await expectDocument(page, docName, firstMarker);
- await headerForward.click();
- await expectDocument(page, secondDocName, secondMarker);
- });
-});
diff --git a/packages/desktop/tests/smoke/terminal-collection-size.json b/packages/desktop/tests/smoke/terminal-collection-size.json
index 42df4d453..9f3968e3c 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": 93
+ "terminalSmokeTestCount": 103
}
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
index fb814ff36..d0c81069c 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 { attachDomState, describeDomState } from './_helpers/dom-state';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import { launchDesktopApp, readBootLog, waitForWindowByMode } from './_helpers/launch-readiness';
import { sumOfDeclaredBoundsMs } from './_helpers/parse-timeouts';
@@ -28,6 +29,7 @@ import {
userDataDirFor,
} from './_helpers/platform-gate';
import { expectCollapsedRailColumn } from './_helpers/rail-column';
+import { closeAppForRelaunch } from './_helpers/settings-surface';
import {
expectSettledReading,
pollSettledReading,
@@ -166,7 +168,13 @@ async function findEditorWindow(app: ElectronApplication): Promise<Page> {
}
async function dispatchRendererMenuAction(
- action: 'move-terminal' | 'toggle-agent-panel' | 'toggle-terminal',
+ action:
+ | 'kill-terminal'
+ | 'move-terminal'
+ | 'new-terminal'
+ | 'toggle-agent-panel'
+ | 'toggle-editor'
+ | 'toggle-terminal',
editorPage: Page,
): Promise<void> {
await editorPage.evaluate(async (menuAction) => {
@@ -266,6 +274,36 @@ async function clickViewAgentsItem(app: ElectronApplication, editorPage: Page):
});
}
+async function clickViewEditorItem(app: ElectronApplication, editorPage: Page): Promise<void> {
+ if (process.platform !== 'darwin') {
+ await dispatchRendererMenuAction('toggle-editor', editorPage);
+ return;
+ }
+ await app.evaluate(async ({ Menu }) => {
+ const view = Menu.getApplicationMenu()?.items.find((item) => item.label === 'View');
+ const item = view?.submenu?.items.find(
+ (candidate) => candidate.label === 'Show Editor' || candidate.label === 'Hide Editor',
+ );
+ if (!item) throw new Error('View menu is missing the Editor visibility item');
+ item.click();
+ });
+}
+
+async function viewMenuEditorLabel(app: ElectronApplication): Promise<string | undefined> {
+ return app.evaluate(({ Menu }) => {
+ const view = Menu.getApplicationMenu()?.items.find((item) => item.label === 'View');
+ return view?.submenu?.items.find((item) => ['Show Editor', 'Hide Editor'].includes(item.label))
+ ?.label;
+ });
+}
+
+function restoredDockState(page: Page) {
+ return page.evaluate(() => window.okDesktop?.terminal.getDockState());
+}
+
+const editorPaneButton = (page: Page) =>
+ page.locator('header[data-app-header]').getByRole('button', { name: 'Editor', exact: true });
+
const terminalSection = (page: Page) => page.locator('section[aria-label="Terminal"]');
const terminalStatus = (page: Page) => page.locator('[data-terminal-status]');
const readinessBanner = (page: Page) =>
@@ -405,7 +443,166 @@ async function readTerminalText(page: Page): Promise<string> {
});
}
+async function readTerminalRows(page: Page): Promise<string> {
+ return page.evaluate(
+ () => document.querySelector('section[aria-label="Terminal"] .xterm-rows')?.textContent ?? '',
+ );
+}
+
+type HeaderPane = 'Agents' | 'Terminal';
+
+const headerPaneButton = (page: Page, pane: HeaderPane) =>
+ page.locator('header[data-app-header]').getByRole('button', { name: pane, exact: true });
+
+async function expectHeaderPanes(
+ page: Page,
+ pressed: Readonly<Record<HeaderPane, boolean>>,
+ timeout = 10_000,
+): Promise<void> {
+ for (const pane of ['Agents', 'Terminal'] as const) {
+ await expect(headerPaneButton(page, pane)).toHaveAttribute(
+ 'aria-pressed',
+ String(pressed[pane]),
+ { timeout },
+ );
+ }
+}
+
+async function activeElementTestId(page: Page): Promise<string | null> {
+ return page.evaluate(() => {
+ const active = document.activeElement;
+ return active?.getAttribute('data-testid') ?? active?.tagName ?? null;
+ });
+}
+
+async function terminalHasFocus(page: Page): Promise<boolean> {
+ return page.evaluate(() => {
+ const sec = document.querySelector('section[aria-label="Terminal"]');
+ return sec?.contains(document.activeElement) ?? false;
+ });
+}
+
+async function viewMenuPaneLabels(
+ app: ElectronApplication,
+): Promise<{ agents: string | undefined; terminal: string | undefined }> {
+ return app.evaluate(({ Menu }) => {
+ const view = Menu.getApplicationMenu()?.items.find((item) => item.label === 'View');
+ const labelOf = (labels: readonly string[]) =>
+ view?.submenu?.items.find((item) => labels.includes(item.label))?.label;
+ return {
+ agents: labelOf(['Show Agents', 'Hide Agents']),
+ terminal: labelOf(['Show Terminal', 'Hide Terminal']),
+ };
+ });
+}
+
+async function clickTerminalMenuItem(
+ app: ElectronApplication,
+ page: Page,
+ item:
+ | { label: 'New Terminal'; action: 'new-terminal' }
+ | { label: 'Kill Terminal'; action: 'kill-terminal' },
+): Promise<void> {
+ if (process.platform !== 'darwin') {
+ await dispatchRendererMenuAction(item.action, page);
+ return;
+ }
+ await expect(async () => {
+ const clicked = await app.evaluate(({ Menu }, label) => {
+ const terminal = Menu.getApplicationMenu()?.items.find((i) => i.label === 'Terminal');
+ const menuItem = terminal?.submenu?.items.find((i) => i.label === label);
+ if (!menuItem?.enabled) return false;
+ menuItem.click();
+ return true;
+ }, item.label);
+ expect(clicked, `Terminal > ${item.label} is not enabled yet`).toBe(true);
+ }).toPass({ timeout: 10_000 });
+}
+
+const IN_WINDOW_MENU_RECOVERY = 'in-window-menu-recovery';
+
+function describeCoveringLayer(state: string): string {
+ try {
+ const parsed = JSON.parse(state) as { crashInviteDialog?: boolean; dialogs?: number };
+ if (parsed.crashInviteDialog === true)
+ return 'the crash-invite bug report dialog was covering the page';
+ if ((parsed.dialogs ?? 0) > 0) return 'a dialog was covering the page';
+ } catch {}
+ return 'no dialog was observed, but the header pane buttons were unreachable';
+}
+
+async function recordInWindowMenuRecovery(page: Page, moment: string): Promise<void> {
+ const info = test.info();
+ const ordinal =
+ info.annotations.filter((annotation) => annotation.type === IN_WINDOW_MENU_RECOVERY).length + 1;
+ const state = await describeDomState(page);
+ const layer = describeCoveringLayer(state);
+ info.annotations.push({
+ type: IN_WINDOW_MENU_RECOVERY,
+ description: `#${ordinal} ${moment}: ${layer}; Escape pressed. ${state}`,
+ });
+ await attachDomState(info, page, `${IN_WINDOW_MENU_RECOVERY}-${ordinal}`);
+ console.log(
+ `[smoke] ${IN_WINDOW_MENU_RECOVERY} #${ordinal} ${moment}: ${layer}; pressing Escape: ${state}`,
+ );
+}
+
+async function dismissCrashInviteIfShown(page: Page, moment: string): Promise<boolean> {
+ const invite = page.getByTestId('report-bug-crash-invite');
+ if (!(await invite.isVisible())) return false;
+ await recordInWindowMenuRecovery(page, moment);
+ await page.keyboard.press('Escape');
+ await expect(invite).toBeHidden({ timeout: 5_000 });
+ return true;
+}
+
+async function clickInWindowViewTerminalItem(page: Page): Promise<void> {
+ const trigger = page
+ .getByTestId('app-menubar')
+ .getByRole('menuitem', { name: 'View', exact: true });
+ const item = page.getByRole('menuitem', { name: /^(Show|Hide) Terminal/ });
+ try {
+ await expect(async () => {
+ await dismissCrashInviteIfShown(page, 'before opening the View menu');
+ if ((await trigger.getAttribute('data-state')) !== 'open') {
+ await trigger.focus();
+ await page.keyboard.press('Enter');
+ }
+ await expect(item).toBeVisible({ timeout: 2_000 });
+ await item.click({ timeout: 2_000 });
+ }).toPass({ timeout: 20_000 });
+ } catch (error) {
+ throw new Error(
+ `the in-window View menu did not open and select its Terminal item: ${await describeDomState(page)}`,
+ { cause: error },
+ );
+ }
+ await expect(page.getByRole('menu')).toHaveCount(0, { timeout: 5_000 });
+ await settleHeaderAfterInWindowMenu(page);
+}
+
+async function settleHeaderAfterInWindowMenu(page: Page): Promise<void> {
+ const agentsButton = headerPaneButton(page, 'Agents');
+ try {
+ await expect(agentsButton).toBeVisible({ timeout: 3_000 });
+ return;
+ } catch {}
+ if (!(await dismissCrashInviteIfShown(page, 'after the View menu closed'))) {
+ await recordInWindowMenuRecovery(page, 'after the View menu closed');
+ await page.keyboard.press('Escape');
+ }
+ try {
+ await expect(agentsButton).toBeVisible({ timeout: 5_000 });
+ } catch (error) {
+ throw new Error(
+ `the header pane buttons stayed unreachable after Escape: ${await describeDomState(page)}`,
+ { cause: error },
+ );
+ }
+}
+
const cleanup: string[] = [];
+
function track(...paths: string[]): void {
cleanup.push(...paths);
}
@@ -519,9 +716,7 @@ test.describe('Docked terminal — live Electron', () => {
.toBe('Move Terminal to right');
});
- test('Terminal header placement is symmetric and clears the Agents reveal tab', async ({
- captureStderrFor,
- }) => {
+ test('Terminal header placement is symmetric', async ({ captureStderrFor }) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
const s = seed('header-placement', { consent: true });
track(s.tmpHome, s.projectDir);
@@ -533,30 +728,17 @@ test.describe('Docked terminal — live Electron', () => {
await widenEditorWindow(app, page, 1900, 900);
await openTerminal(app, 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(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({
- timeout: 10_000,
- });
+ await expect(rightTerminal).toBeVisible({ timeout: 10_000 });
const moveBottomButton = page.getByRole('button', { name: 'Move Terminal to bottom' });
- const collapseButton = page.getByRole('button', { name: 'Collapse Terminal' });
- const revealAgentsButton = page.getByRole('button', { name: 'Open agents panel' });
await expect(moveBottomButton).toBeVisible();
- await expect(collapseButton).toBeVisible();
- await expect(revealAgentsButton).toBeVisible();
- const [moveBottomBox, collapseBox, revealAgentsBox] = await Promise.all([
- moveBottomButton.boundingBox(),
- collapseButton.boundingBox(),
- revealAgentsButton.boundingBox(),
- ]);
- if (!moveBottomBox || !collapseBox || !revealAgentsBox) {
- throw new Error('terminal rail controls did not produce measurable geometry');
- }
- expect(
- Math.max(moveBottomBox.x + moveBottomBox.width, collapseBox.x + collapseBox.width),
- ).toBeLessThanOrEqual(revealAgentsBox.x);
+ 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 ({
@@ -688,6 +870,7 @@ test.describe('Docked terminal — live Electron', () => {
);
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.',
@@ -699,10 +882,29 @@ test.describe('Docked terminal — live Electron', () => {
);
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 });
});
test('QA-022 toggle reveals the dock and mounts the terminal inside their liveness budgets', async ({
@@ -808,7 +1010,7 @@ test.describe('Docked terminal — live Electron', () => {
.toBeLessThanOrEqual(2);
});
- test('terminal tab strip exposes collapse without legacy dock chrome', async ({
+ test('terminal tab strip carries no collapse or legacy dock chrome while the header Terminal button reads on', async ({
captureStderrFor,
}) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
@@ -820,9 +1022,12 @@ test.describe('Docked terminal — live Electron', () => {
await configureDesktopGitRepositories(page, s.realProjectDir);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
- await expect(page.getByRole('button', { name: 'Collapse Terminal' })).toBeVisible({
- timeout: 10_000,
- });
+ await expect(page.getByTestId('header-pane-button-terminal')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ { timeout: 10_000 },
+ );
+ await expect(page.getByRole('button', { name: /^Collapse/ })).toHaveCount(0);
await expect(page.getByRole('button', { name: /Dock terminal to the/ })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Drag to dock the terminal' })).toHaveCount(0);
});
@@ -1322,4 +1527,379 @@ test.describe('Docked terminal — live Electron', () => {
expect(await readTerminalText(page)).toContain('Seed document');
expect(await readTerminalText(page)).not.toContain('OKSTAGE_REUSE_742');
});
+
+ test('the header Terminal button starts a focused shell and keeps it across a hide and show', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed('header-shell', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ const terminalButton = headerPaneButton(page, 'Terminal');
+
+ await expect(terminalButton).toHaveAttribute('aria-pressed', 'false', { timeout: 20_000 });
+ await expect(terminalSection(page)).toBeHidden();
+
+ await terminalButton.click();
+ await expect(terminalButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });
+ await expect.poll(() => terminalHasFocus(page), { timeout: 15_000 }).toBe(true);
+ await waitForStatus(page, 'running', 25_000);
+
+ await typeInTerminal(
+ page,
+ `${SHELL_COMMANDS.setEnvironment('OK_HEADER_MARKER', 'OKHEADER_KEPT_418')}\r`,
+ );
+ await typeInTerminal(page, `${SHELL_COMMANDS.readEnvironment('OK_HEADER_MARKER', 'before')}\r`);
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('before=[OKHEADER_KEPT_418]');
+
+ await terminalButton.click();
+ await expect(terminalButton).toHaveAttribute('aria-pressed', 'false');
+ await expect(terminalSection(page)).toBeHidden();
+ await expect
+ .poll(() => activeElementTestId(page), { timeout: 5_000 })
+ .toBe('header-pane-button-terminal');
+
+ await page.keyboard.press('Enter');
+ await expect(terminalButton).toHaveAttribute('aria-pressed', 'true');
+ await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });
+ await expect.poll(() => terminalHasFocus(page), { timeout: 15_000 }).toBe(true);
+ await expect(terminalStatus(page)).toHaveAttribute('data-terminal-status', 'running');
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('before=[OKHEADER_KEPT_418]');
+ await typeInTerminal(page, `${SHELL_COMMANDS.readEnvironment('OK_HEADER_MARKER', 'after')}\r`);
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('after=[OKHEADER_KEPT_418]');
+ });
+
+ test('a running shell completes output while Terminal is hidden at the native minimum', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed('narrow-shell-continuity', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await widenEditorWindow(app, page, 1000, 700);
+ await expect(terminalSection(page)).toBeHidden();
+ await headerPaneButton(page, 'Terminal').click();
+ await expect(terminalSection(page)).toBeVisible();
+ await waitForStatus(page, 'running', 25_000);
+
+ const initialSessions = await page.evaluate(() => window.okDesktop?.terminal.list());
+ expect(initialSessions).toHaveLength(1);
+ const ptyId = initialSessions?.[0]?.ptyId;
+ expect(ptyId).toBeTruthy();
+ await typeInTerminal(
+ page,
+ `${SHELL_COMMANDS.setEnvironment('OK_RESPONSIVE_SHELL', 'OK_SHELL_SURVIVED_628')}\r`,
+ );
+ await typeInTerminal(
+ page,
+ `${SHELL_COMMANDS.readEnvironment('OK_RESPONSIVE_SHELL', 'before')}\r`,
+ );
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('before=[OK_SHELL_SURVIVED_628]');
+
+ await widenEditorWindow(app, page, 720, 480);
+ await expect.poll(() => page.evaluate(() => window.innerWidth)).toBeLessThan(768);
+ await expect
+ .poll(() => app.browserWindow(page).then((win) => win.evaluate((w) => w.getSize())))
+ .toEqual([720, 480]);
+ await expect(headerPaneButton(page, 'Terminal')).toHaveAttribute('aria-pressed', 'true');
+ await expect(terminalSection(page)).toBeVisible();
+ await typeInTerminal(page, `${SHELL_COMMANDS.columns('NARROW_COLS')}\r`);
+ await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/NARROW_COLS=\d+/);
+ const narrowColumns = Number((await readTerminalText(page)).match(/NARROW_COLS=(\d+)/)?.[1]);
+ expect(narrowColumns).toBeGreaterThan(0);
+
+ const waitingPath = join(s.projectDir, 'terminal-waiting');
+ const releasePath = join(s.projectDir, 'terminal-release');
+ const acknowledgementPath = join(s.projectDir, 'terminal-completed');
+ await typeInTerminal(
+ page,
+ `${SHELL_COMMANDS.waitForFileThenOutput(releasePath, waitingPath, acknowledgementPath, 'OK_TERMINAL_WAITING_628')}\r`,
+ );
+ await expect.poll(() => existsSync(waitingPath), { timeout: 15_000 }).toBe(true);
+
+ await editorPaneButton(page).click();
+ await expect(terminalSection(page)).toBeHidden();
+ await expect(editorPaneButton(page)).toHaveAttribute('aria-pressed', 'true');
+ writeFileSync(releasePath, 'OK_TERMINAL_COMPLETED_628\n');
+ await expect.poll(() => existsSync(acknowledgementPath), { timeout: 15_000 }).toBe(true);
+ expect(readFileSync(acknowledgementPath, 'utf8')).toContain('OK_TERMINAL_COMPLETED_628');
+ expect((await page.evaluate(() => window.okDesktop?.terminal.list()))?.[0]?.ptyId).toBe(ptyId);
+
+ await headerPaneButton(page, 'Terminal').click();
+ await expect(terminalSection(page)).toBeVisible();
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('OK_TERMINAL_COMPLETED_628');
+ expect((await readTerminalRows(page)).split('OK_TERMINAL_COMPLETED_628')).toHaveLength(2);
+ await typeInTerminal(
+ page,
+ `${SHELL_COMMANDS.readEnvironment('OK_RESPONSIVE_SHELL', 'after')}\r`,
+ );
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('after=[OK_SHELL_SURVIVED_628]');
+
+ expect(await clickViewTerminalItem(app, page)).toBe('Hide Terminal');
+ await expect(terminalSection(page)).toBeHidden();
+ expect((await page.evaluate(() => window.okDesktop?.terminal.list()))?.[0]?.ptyId).toBe(ptyId);
+ await headerPaneButton(page, 'Terminal').click();
+ await expect(terminalSection(page)).toBeVisible();
+ await widenEditorWindow(app, page, 1000, 700);
+ await expect(terminalSection(page)).toBeVisible();
+ await expect.poll(() => restoredDockState(page)).toMatchObject({ terminalVisible: true });
+ expect((await page.evaluate(() => window.okDesktop?.terminal.list()))?.[0]?.ptyId).toBe(ptyId);
+ expect((await readTerminalRows(page)).split('OK_TERMINAL_COMPLETED_628')).toHaveLength(2);
+ await typeInTerminal(page, `${SHELL_COMMANDS.columns('WIDE_COLS')}\r`);
+ await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/WIDE_COLS=\d+/);
+ const wideColumns = Number((await readTerminalText(page)).match(/WIDE_COLS=(\d+)/)?.[1]);
+ expect(wideColumns).toBeGreaterThan(narrowColumns);
+ });
+
+ test('the header pane buttons follow the View and Terminal menus', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed('header-menus', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ const terminalTabs = page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');
+
+ await expectHeaderPanes(page, { Agents: false, Terminal: false }, 20_000);
+ expect(await viewTerminalLabel(app)).toBe('Show Terminal');
+
+ expect(await clickViewTerminalItem(app, page)).toBe('Show Terminal');
+ await expectHeaderPanes(page, { Agents: false, Terminal: true });
+ await waitForStatus(page, 'running', 25_000);
+ await expect.poll(() => viewTerminalLabel(app), { timeout: 8_000 }).toBe('Hide Terminal');
+ expect(await clickViewTerminalItem(app, page)).toBe('Hide Terminal');
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+
+ await clickViewAgentsItem(app, page);
+ await expectHeaderPanes(page, { Agents: true, Terminal: false });
+ await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
+ await expect
+ .poll(async () => (await viewMenuPaneLabels(app)).agents, { timeout: 8_000 })
+ .toBe('Hide Agents');
+ await clickViewAgentsItem(app, page);
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+
+ await clickTerminalMenuItem(app, page, { label: 'New Terminal', action: 'new-terminal' });
+ await expectHeaderPanes(page, { Agents: false, Terminal: true });
+ await expect(terminalTabs).toHaveCount(2, { timeout: 15_000 });
+ await clickTerminalMenuItem(app, page, { label: 'Kill Terminal', action: 'kill-terminal' });
+ await expect(terminalTabs).toHaveCount(1, { timeout: 15_000 });
+ await expectHeaderPanes(page, { Agents: false, Terminal: true });
+ await clickTerminalMenuItem(app, page, { label: 'Kill Terminal', action: 'kill-terminal' });
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+ await expect(terminalSection(page)).toBeHidden();
+
+ if (process.platform !== 'darwin') {
+ await clickInWindowViewTerminalItem(page);
+ await expectHeaderPanes(page, { Agents: false, Terminal: true });
+ await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });
+ await expect.poll(() => viewTerminalLabel(app), { timeout: 8_000 }).toBe('Hide Terminal');
+ await clickInWindowViewTerminalItem(page);
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+ }
+ });
+
+ test('narrow View menu Hide commands keep wide dock visibility while selecting Editor or Nothing Open', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed('narrow-view-menu', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await widenEditorWindow(app, page, 900, 700);
+ await expect(editorPaneButton(page)).toHaveAttribute('aria-pressed', 'true');
+ await expect
+ .poll(() => restoredDockState(page))
+ .toMatchObject({
+ editorVisible: true,
+ agentPanelVisible: false,
+ terminalVisible: false,
+ });
+
+ await widenEditorWindow(app, page, 720, 480);
+ await expect.poll(() => page.evaluate(() => window.innerWidth)).toBeLessThan(768);
+ await headerPaneButton(page, 'Agents').click();
+ await expectHeaderPanes(page, { Agents: true, Terminal: false });
+ await expect.poll(async () => (await viewMenuPaneLabels(app)).agents).toBe('Hide Agents');
+ await expect.poll(() => restoredDockState(page)).toMatchObject({ agentPanelVisible: false });
+
+ await clickViewAgentsItem(app, page);
+ await expect(editorPaneButton(page)).toHaveAttribute('aria-pressed', 'true');
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+ await expect.poll(() => restoredDockState(page)).toMatchObject({ agentPanelVisible: false });
+
+ await clickViewEditorItem(app, page);
+ await expect(page.getByRole('region', { name: 'Nothing open' })).toBeVisible();
+ await expect.poll(() => viewMenuEditorLabel(app)).toBe('Show Editor');
+ await expect.poll(() => restoredDockState(page)).toMatchObject({ editorVisible: true });
+
+ await clickViewEditorItem(app, page);
+ await expect(editorPaneButton(page)).toHaveAttribute('aria-pressed', 'true');
+ await headerPaneButton(page, 'Terminal').click();
+ await expectHeaderPanes(page, { Agents: false, Terminal: true });
+ await waitForStatus(page, 'running', 25_000);
+ await expect.poll(() => viewTerminalLabel(app)).toBe('Hide Terminal');
+ await expect.poll(() => restoredDockState(page)).toMatchObject({ terminalVisible: false });
+ await clickViewTerminalItem(app, page);
+ await expect(editorPaneButton(page)).toHaveAttribute('aria-pressed', 'true');
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+ await expect.poll(() => restoredDockState(page)).toMatchObject({ terminalVisible: false });
+ await widenEditorWindow(app, page, 900, 700);
+ await expectHeaderPanes(page, { Agents: false, Terminal: false });
+ await expect
+ .poll(() => restoredDockState(page))
+ .toMatchObject({
+ editorVisible: true,
+ agentPanelVisible: false,
+ terminalVisible: false,
+ });
+ });
+
+ test('the header hides Terminal while the project has it turned off and restores it on enable', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed('header-opt-out', { optOut: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+
+ await expect(headerPaneButton(page, 'Agents')).toBeVisible({ timeout: 20_000 });
+ await expect(headerPaneButton(page, 'Terminal')).toHaveCount(0, { timeout: 15_000 });
+
+ await revealTerminalSurface(app, page.getByRole('region', { name: 'Terminal disabled' }));
+ const enableTerminal = page.getByRole('button', { name: 'Enable terminal' });
+ await expect(enableTerminal).toBeVisible();
+ await expect(headerPaneButton(page, 'Terminal')).toHaveCount(0);
+
+ await page.evaluate(() => Reflect.set(window, '__okHeaderSameDocument', true));
+ await enableTerminal.click();
+ await expect(headerPaneButton(page, 'Terminal')).toHaveAttribute('aria-pressed', 'true', {
+ timeout: 15_000,
+ });
+ expect(await page.evaluate(() => Reflect.get(window, '__okHeaderSameDocument'))).toBe(true);
+ await waitForStatus(page, 'running', 25_000);
+ });
+
+ test('header show and hide survive a relaunch on the same profile', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(300_000);
+ const s = seed('header-relaunch', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const launchOnProfile = async (): Promise<{ app: ElectronApplication; page: Page }> => {
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ return { app, page: await findEditorWindow(app) };
+ };
+ const quitAfterMenuReads = async (
+ app: ElectronApplication,
+ labels: { agents: string; terminal: string },
+ ): Promise<void> => {
+ await expect.poll(() => viewMenuPaneLabels(app), { timeout: 8_000 }).toEqual(labels);
+ await closeAppForRelaunch(app);
+ };
+
+ const first = await launchOnProfile();
+ await expectHeaderPanes(first.page, { Agents: false, Terminal: false }, 20_000);
+ await headerPaneButton(first.page, 'Terminal').click();
+ await headerPaneButton(first.page, 'Agents').click();
+ await expectHeaderPanes(first.page, { Agents: true, Terminal: true });
+ await quitAfterMenuReads(first.app, { agents: 'Hide Agents', terminal: 'Hide Terminal' });
+
+ 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 headerPaneButton(second.page, 'Agents').click();
+ await expectHeaderPanes(second.page, { Agents: false, Terminal: true });
+ await quitAfterMenuReads(second.app, { agents: 'Show Agents', terminal: 'Hide Terminal' });
+
+ const third = await launchOnProfile();
+ await expect(headerPaneButton(third.page, 'Terminal')).toHaveAttribute('aria-pressed', 'true', {
+ timeout: 25_000,
+ });
+ await expect(headerPaneButton(third.page, 'Agents')).toHaveAttribute('aria-pressed', 'false');
+ await expectCollapsedRailColumn(third.page, '#agents-column');
+ await headerPaneButton(third.page, 'Agents').click();
+ await headerPaneButton(third.page, 'Terminal').click();
+ await expectHeaderPanes(third.page, { Agents: true, Terminal: false });
+ await quitAfterMenuReads(third.app, { agents: 'Hide Agents', terminal: 'Show Terminal' });
+
+ const fourth = await launchOnProfile();
+ await expect(headerPaneButton(fourth.page, 'Agents')).toHaveAttribute('aria-pressed', 'true', {
+ timeout: 25_000,
+ });
+ await expect(headerPaneButton(fourth.page, 'Terminal')).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ await expect(terminalSection(fourth.page)).toBeHidden();
+ });
+
+ test('a hidden editor survives a relaunch, and the View menu hides and shows it', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed('editor-relaunch', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const launchOnProfile = async (): Promise<{ app: ElectronApplication; page: Page }> => {
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ return { app, page: await findEditorWindow(app) };
+ };
+
+ const first = await launchOnProfile();
+ await expect(editorPaneButton(first.page)).toHaveAttribute('aria-pressed', 'true', {
+ timeout: 20_000,
+ });
+ await expect.poll(() => viewMenuEditorLabel(first.app), { timeout: 8_000 }).toBe('Hide Editor');
+ await clickViewEditorItem(first.app, first.page);
+ await expect(editorPaneButton(first.page)).toHaveAttribute('aria-pressed', 'false');
+ await expect.poll(() => viewMenuEditorLabel(first.app), { timeout: 8_000 }).toBe('Show Editor');
+ await closeAppForRelaunch(first.app);
+
+ const second = await launchOnProfile();
+ await expect
+ .poll(() => restoredDockState(second.page), { timeout: 25_000 })
+ .toMatchObject({ editorVisible: false });
+ await expect(editorPaneButton(second.page)).toHaveAttribute('aria-pressed', 'false', {
+ timeout: 25_000,
+ });
+ await expect(second.page.getByRole('region', { name: 'Nothing open' })).toBeVisible();
+ await expect
+ .poll(() => viewMenuEditorLabel(second.app), { timeout: 8_000 })
+ .toBe('Show Editor');
+ await clickViewEditorItem(second.app, second.page);
+ await expect(editorPaneButton(second.page)).toHaveAttribute('aria-pressed', 'true');
+ await closeAppForRelaunch(second.app);
+
+ const third = await launchOnProfile();
+ await expect(editorPaneButton(third.page)).toHaveAttribute('aria-pressed', 'true', {
+ timeout: 25_000,
+ });
+ await expect(third.page.getByRole('region', { name: 'Nothing open' })).toHaveCount(0);
+ });
});
diff --git a/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts b/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts
index 8200be879..5780260c6 100644
--- a/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts
@@ -121,6 +121,24 @@ async function findEditorWindow(app: ElectronApplication): Promise<Page> {
return waitForWindowByMode(app, 'editor');
}
+async function resizeEditorWindow(
+ app: ElectronApplication,
+ page: Page,
+ width: number,
+ height: number,
+): Promise<void> {
+ const nativeWindowHandle = await app.browserWindow(page);
+ await nativeWindowHandle.evaluate(
+ (nativeWindow: unknown, size) => {
+ (
+ nativeWindow as { setSize: (width: number, height: number, animate: boolean) => void }
+ ).setSize(size.width, size.height, false);
+ },
+ { width, height },
+ );
+ await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(width);
+}
+
async function clickViewTerminalItem(app: ElectronApplication, editorPage: Page): Promise<void> {
await app.evaluate(async ({ Menu }) => {
const menu = Menu.getApplicationMenu();
@@ -248,4 +266,53 @@ test.describe('Docked terminal launch — composed argv', () => {
expect(ask).toContain(`mcp__${OK_SERVER_NAME}__delete`);
for (const rule of ask) expect(rule.startsWith(`mcp__${OK_SERVER_NAME}__`)).toBe(true);
});
+
+ test('a narrow file action selects Terminal and delivers its prompt to the real PTY', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed();
+ const app = await launchApp(s);
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await resizeEditorWindow(app, page, 900, 700);
+ await expect(
+ page.locator('header[data-app-header]').getByRole('button', { name: 'Editor' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ await expect
+ .poll(() => page.evaluate(() => window.okDesktop?.terminal.getDockState()))
+ .toMatchObject({
+ terminalVisible: false,
+ });
+
+ await resizeEditorWindow(app, page, 720, 480);
+ const filesTrigger = page.locator('[data-sidebar="trigger"]');
+ if ((await filesTrigger.getAttribute('aria-expanded')) !== 'true') await filesTrigger.click();
+ await expect(filesTrigger).toHaveAttribute('aria-expanded', 'true');
+ const file = page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: 'start.md', exact: true });
+ await file.click({ button: 'right' });
+ await page.getByRole('menuitem', { name: 'Open with AI' }).click();
+ await page.getByTestId('file-tree-open-in-terminal-claude').click();
+
+ await expect(terminalSection(page)).toBeVisible();
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
+ await expect(
+ page.locator('header[data-app-header]').getByRole('button', { name: 'Terminal' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ await expect.poll(() => readRecordedArgv(s.capturePath), { timeout: 45_000 }).not.toBeNull();
+ const recorded = readRecordedArgv(s.capturePath);
+ if (recorded === null) throw new Error('recorded argv vanished after the poll');
+ expect(recorded[0]).toBe(join(s.binDir, 'claude'));
+ expect(recorded.at(-1)).toContain('start.md');
+ expect(existsSync(s.injectedPath)).toBe(false);
+ await expect
+ .poll(() => page.evaluate(() => window.okDesktop?.terminal.getDockState()))
+ .toMatchObject({
+ terminalVisible: false,
+ });
+ await resizeEditorWindow(app, page, 900, 700);
+ await expect(terminalSection(page)).toBeHidden();
+ });
});
diff --git a/packages/desktop/tests/smoke/terminal-links.e2e.ts b/packages/desktop/tests/smoke/terminal-links.e2e.ts
index 74a97e228..1e8a2537d 100644
--- a/packages/desktop/tests/smoke/terminal-links.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-links.e2e.ts
@@ -86,6 +86,39 @@ async function findEditorWindow(app: ElectronApplication): Promise<Page> {
return waitForWindowByMode(app, 'editor');
}
+async function findEditorWindowWithin20s(app: ElectronApplication): Promise<Page> {
+ await expect
+ .poll(
+ async () => {
+ for (const page of app.windows()) {
+ const mode = await page
+ .evaluate(() => window.okDesktop?.config?.mode)
+ .catch(() => undefined);
+ if (mode === 'editor') return true;
+ }
+ return false;
+ },
+ { timeout: 20_000, message: 'editor window did not appear within timeout' },
+ )
+ .toBe(true);
+
+ for (const page of app.windows()) {
+ const mode = await page.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
+ if (mode === 'editor') return page;
+ }
+ throw new Error('editor window vanished between poll resolution and read');
+}
+
+async function resizeEditorWindow(app: ElectronApplication, page: Page): Promise<void> {
+ const nativeWindowHandle = await app.browserWindow(page);
+ await nativeWindowHandle.evaluate((nativeWindow: unknown) => {
+ (
+ nativeWindow as { setSize: (width: number, height: number, animate: boolean) => void }
+ ).setSize(720, 480, false);
+ });
+ await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(720);
+}
+
async function openRunningTerminal(app: ElectronApplication, page: Page): Promise<void> {
const label = await app.evaluate(async ({ Menu }) => {
const view = Menu.getApplicationMenu()?.items.find((i) => i.label === 'View');
@@ -187,23 +220,36 @@ test.describe('Terminal clickable links — live Electron', () => {
}).toPass({ timeout: 20_000 });
});
- test.fixme('clicking an in-project markdown path opens the doc in the editor', async ({
+ test.fixme('clicking a printed project document from narrow Terminal reveals it in Editor', async ({
captureStderrFor,
}) => {
const s = seed('doc');
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);
+ const page = await findEditorWindowWithin20s(app);
await configureDesktopGitRepositories(page, s.projectDir);
await openRunningTerminal(app, page);
+ await resizeEditorWindow(app, page);
+ await expect(page.getByTestId('header-pane-button-terminal')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(page.locator('[data-pane="editor"]')).toBeHidden();
await runInTerminal(page, SHELL_COMMANDS.output('notes.md'), 'notes.md');
-
await expect(async () => {
await clickTerminalLink(page, 'notes.md');
- const hash = await page.evaluate(() => window.location.hash);
- expect(hash).toBe('#/notes');
+ expect(await page.evaluate(() => window.location.hash)).toBe('#/notes');
}).toPass({ timeout: 20_000 });
+ await expect(page.getByTestId('header-pane-button-editor')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(page.locator('[data-pane="editor"]')).toBeVisible();
+ await expect(page.locator('[data-pane="terminal"]:visible')).toHaveCount(0);
+ await expect(
+ page.locator('[data-pane="editor"] .ProseMirror:not(.composer-prosemirror):visible').first(),
+ ).toContainText('Clickable link target.');
});
});
diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
index 89c373ee3..2c936c57a 100644
--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import type { ElectronApplication, ElementHandle, JSHandle, Page } from '@playwright/test';
+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 { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
@@ -584,6 +584,63 @@ 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 ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed();
+ const app = await launchApp(s);
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await widenEditorWindow(app, page, 1900, 900);
+ await page.evaluate(() => {
+ window.location.hash = '#/start';
+ });
+ await expect(
+ page.locator('.ProseMirror[contenteditable="true"]:not(.composer-prosemirror)').first(),
+ ).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true', {
+ timeout: 10_000,
+ });
+
+ 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]');
+ const editorCard = page.locator('[data-slot="pane-card"][data-pane="editor"]');
+ await expect(editorCard.locator('#doc-panel')).toHaveCount(1);
+ await expect
+ .poll(() => sidePanel.evaluate((element) => element.getBoundingClientRect().width), {
+ timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ })
+ .toBeGreaterThanOrEqual(300);
+ const sidePanelBefore = await sidePanel.evaluate(
+ (element) => element.getBoundingClientRect().width,
+ );
+ const columnBefore = await documentColumn.evaluate(
+ (element) => element.getBoundingClientRect().width,
+ );
+
+ const deltaPx = 150;
+ 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,
+ );
+ });
+
test('renderer restart restores the right layout and its live active terminal', async ({
captureStderrFor,
}) => {
@@ -676,7 +733,10 @@ test.describe('Terminal placement continuity — live Electron', () => {
);
await expectCollapsedRailColumn(page, '#agents-column', { budget: shrink });
await page.evaluate(() => {
- window.okDesktop?.editor.notifyViewMenuStateChanged({ agentPanelVisible: true });
+ window.okDesktop?.editor.notifyViewMenuStateChanged({
+ agentPanelVisible: true,
+ wideIntent: { agentPanelVisible: true },
+ });
});
await expect
.poll(
@@ -751,4 +811,118 @@ test.describe('Terminal placement continuity — live Electron', () => {
await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(output)}\r`);
await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(output);
});
+
+ test('the terminal is its own card: under the whole editor card at the bottom, a full-height card on the right', async ({
+ captureStderrFor,
+ }) => {
+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
+ const s = seed();
+ const app = await launchApp(s);
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await widenEditorWindow(app, page, 1900, 900);
+ await page.evaluate(() => {
+ window.location.hash = '#/start';
+ });
+ await expect(
+ page.locator('.ProseMirror[contenteditable="true"]:not(.composer-prosemirror)').first(),
+ ).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator('[data-doc-panel-toggle]')).toHaveAttribute('aria-expanded', 'true', {
+ timeout: 10_000,
+ });
+
+ const box = async (selector: string) => {
+ const rect = await page.locator(selector).first().boundingBox();
+ if (rect == null) throw new Error(`${selector} has no box`);
+ return {
+ x: rect.x,
+ y: rect.y,
+ right: rect.x + rect.width,
+ bottom: rect.y + rect.height,
+ height: rect.height,
+ };
+ };
+ const gapPx = 8;
+ const clippingAncestors = (card: Locator) =>
+ card.evaluate((element) => {
+ const clippers: string[] = [];
+ let cur: Element | null = element.parentElement;
+ while (cur != null && cur !== document.body) {
+ if (getComputedStyle(cur).overflow !== 'visible') clippers.push(cur.className.toString());
+ cur = cur.parentElement;
+ }
+ return clippers;
+ });
+
+ 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 });
+ expect(
+ await clippingAncestors(bottomCard),
+ '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 fileList = await box('[data-slot="sidebar-container"]');
+ const sidePanel = await box('#doc-panel');
+ expect(
+ Math.abs(bottom.x - editor.x),
+ 'the bottom terminal card starts under the file list',
+ ).toBeLessThanOrEqual(1);
+ expect(
+ Math.abs(bottom.right - editor.right),
+ 'the bottom terminal card ends under the side panel',
+ ).toBeLessThanOrEqual(1);
+ expect(
+ Math.abs(bottom.y - editor.bottom - gapPx),
+ 'one gap separates the editor card and the terminal card',
+ ).toBeLessThanOrEqual(1);
+ expect(fileList.bottom, 'the file list stops above the terminal card').toBeLessThanOrEqual(
+ bottom.y + 1,
+ );
+ 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]');
+ 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),
+ '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"]');
+ expect(
+ Math.abs(right.y - editorAfter.y),
+ 'the right terminal card top lines up with the editor card',
+ ).toBeLessThanOrEqual(1);
+ expect(
+ Math.abs(right.bottom - editorAfter.bottom),
+ 'the right terminal card runs the full height',
+ ).toBeLessThanOrEqual(1);
+ expect(
+ 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 tabRow = await box('header[data-editor-header]');
+ const rightBar = await box('#terminal-column [data-terminal-tab-row]');
+ expect(
+ Math.abs(rightBar.height - tabRow.height),
+ 'the right terminal top bar matches the tab row height',
+ ).toBeLessThanOrEqual(1);
+ expect(Math.abs(rightBar.y - tabRow.y)).toBeLessThanOrEqual(1);
+ });
});
diff --git a/packages/desktop/tests/smoke/window-chrome.e2e.ts b/packages/desktop/tests/smoke/window-chrome.e2e.ts
index 969aa933e..30f5193cb 100644
--- a/packages/desktop/tests/smoke/window-chrome.e2e.ts
+++ b/packages/desktop/tests/smoke/window-chrome.e2e.ts
@@ -1,9 +1,10 @@
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import type { ElectronApplication, JSHandle, Page } from '@playwright/test';
+import type { ElectronApplication, JSHandle, Locator, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { CHROME_BG } from '../../src/main/window-chrome.ts';
+import { WINDOW_MIN_SIZE } from '../../src/main/window-min-size.ts';
import { configureDesktopGitRepositories } from '../support/git-fixture.test-helper.ts';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import {
@@ -69,6 +70,12 @@ async function launchApp(tmpHome: string): Promise<ElectronApplication> {
);
}
+async function appRegionOfButton(scope: Locator, name: string): Promise<string> {
+ return scope
+ .getByRole('button', { name, exact: true })
+ .evaluate((element) => getComputedStyle(element).getPropertyValue('-webkit-app-region'));
+}
+
async function findEditorWindow(app: ElectronApplication, timeoutMs = 20_000): Promise<Page> {
await expect
.poll(
@@ -91,6 +98,98 @@ async function findEditorWindow(app: ElectronApplication, timeoutMs = 20_000): P
throw new Error('editor window vanished between poll resolution and read');
}
+interface HeaderFitReading {
+ headerHeight: number;
+ outsideRow: string[];
+ outsideWindow: string[];
+ overlapping: string[];
+ paneControls: string[];
+ underWindowControls: string[];
+}
+
+function readSettledHeaderFit(frames: number): Promise<HeaderFitReading | null> {
+ const read = (): HeaderFitReading | null => {
+ const header = document.querySelector<HTMLElement>('header[data-app-header]');
+ if (!header) return null;
+ const headerRect = header.getBoundingClientRect();
+ const isShown = (element: Element) => {
+ const rect = element.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0 && getComputedStyle(element).visibility !== 'hidden';
+ };
+ const labelOf = (element: Element) =>
+ element.getAttribute('aria-label') ??
+ element.getAttribute('data-testid') ??
+ (element.textContent ?? '').trim().slice(0, 32);
+ const controls = [
+ ...header.querySelectorAll(
+ 'button, a[href], [data-slot="badge"], [data-testid$="-badge"], [data-testid="header-pane-divider"]',
+ ),
+ ]
+ .filter(isShown)
+ .map((element) => ({
+ element,
+ label: labelOf(element),
+ rect: element.getBoundingClientRect(),
+ }));
+ const overlapping: string[] = [];
+ for (const [index, a] of controls.entries()) {
+ for (const b of controls.slice(index + 1)) {
+ if (a.element.contains(b.element) || b.element.contains(a.element)) continue;
+ const across = Math.min(a.rect.right, b.rect.right) - Math.max(a.rect.left, b.rect.left);
+ const down = Math.min(a.rect.bottom, b.rect.bottom) - Math.max(a.rect.top, b.rect.top);
+ if (across > 0.5 && down > 0.5) overlapping.push(`${a.label} x ${b.label}`);
+ }
+ }
+ const overlay = (
+ navigator as Navigator & {
+ windowControlsOverlay?: { visible: boolean; getTitlebarAreaRect(): DOMRect };
+ }
+ ).windowControlsOverlay;
+ const titlebar = overlay?.visible === true ? overlay.getTitlebarAreaRect() : null;
+ return {
+ headerHeight: Math.round(headerRect.height),
+ outsideRow: controls
+ .filter(
+ ({ rect }) => rect.top < headerRect.top - 0.5 || rect.bottom > headerRect.bottom + 0.5,
+ )
+ .map(({ label }) => label),
+ outsideWindow: controls
+ .filter(({ rect }) => rect.left < -0.5 || rect.right > window.innerWidth + 0.5)
+ .map(({ label }) => label),
+ overlapping,
+ paneControls: [
+ ...header.querySelectorAll(
+ '[data-testid="header-pane-divider"], [data-testid^="header-pane-button-"]',
+ ),
+ ]
+ .filter(isShown)
+ .map((element) => element.getAttribute('data-testid') ?? ''),
+ underWindowControls:
+ titlebar === null
+ ? []
+ : controls
+ .filter(
+ ({ rect }) =>
+ rect.left < titlebar.x - 0.5 || rect.right > titlebar.x + titlebar.width + 0.5,
+ )
+ .map(({ label }) => label),
+ };
+ };
+ return new Promise((resolve) => {
+ const readings = [JSON.stringify(read())];
+ const sample = () => {
+ readings.push(JSON.stringify(read()));
+ if (readings.length > frames) {
+ const settled = readings.every((reading) => reading === readings[0]);
+ resolve(settled ? read() : null);
+ return;
+ }
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ });
+}
+
test.describe('Windows/Linux window chrome smoke', () => {
test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
test.skip(!PLATFORM_SUPPORTED, PLATFORM_SKIP_REASON);
@@ -127,6 +226,18 @@ test.describe('Windows/Linux window chrome smoke', () => {
if (process.platform === 'win32') {
expect(overlay.visible).toBe(true);
+ await expect(editor.locator('header[data-app-header]')).toBeVisible();
+ const heights = await editor.evaluate(() => {
+ const wco = (
+ navigator as Navigator & { windowControlsOverlay?: { getTitlebarAreaRect(): DOMRect } }
+ ).windowControlsOverlay;
+ const header = document.querySelector('header[data-app-header]');
+ return {
+ titlebarArea: wco?.getTitlebarAreaRect().height ?? null,
+ appHeader: header?.getBoundingClientRect().height ?? null,
+ };
+ });
+ expect(heights.titlebarArea).toBe(heights.appHeader);
}
await configureDesktopGitRepositories(editor, projectDir);
});
@@ -147,7 +258,7 @@ test.describe('Editor header drag-region smoke', () => {
const editor = await findEditorWindow(app);
await configureDesktopGitRepositories(editor, projectDir);
const filesToggle = editor
- .locator('[data-editor-header-leading-actions]')
+ .locator('header[data-editor-header] [data-file-list-toggle]')
.locator('[data-sidebar="trigger"]');
await expect(filesToggle).toBeVisible();
await filesToggle.click();
@@ -159,13 +270,10 @@ test.describe('Editor header drag-region smoke', () => {
new Promise<string>((resolve) => {
const headerGeometrySignature = () => {
const sidebar = document.querySelector('[data-slot="sidebar"]');
- const leadingActions = document.querySelector(
- '[data-editor-header-leading-actions]',
- );
+ const toggleZone = document.querySelector('[data-file-list-toggle]');
const overflowRoot = document.querySelector('[data-editor-tab-overflow-root]');
- if (!sidebar || !leadingActions || !overflowRoot)
- return 'header chrome not mounted';
- const leading = leadingActions.getBoundingClientRect();
+ if (!sidebar || !toggleZone || !overflowRoot) return 'header chrome not mounted';
+ const leading = toggleZone.getBoundingClientRect();
const overflow = overflowRoot.getBoundingClientRect();
return `${sidebar.getAttribute('data-state')} leadingRight=${leading.right} overflowLeft=${overflow.left} overflowWidth=${overflow.width}`;
};
@@ -193,6 +301,11 @@ test.describe('Editor header drag-region smoke', () => {
},
)
.toMatch(/^collapsed /);
+ await expect(
+ editor
+ .locator('header[data-app-header]')
+ .getByRole('button', { name: 'Agents', exact: true }),
+ ).toBeVisible();
const appRegions = await editor.evaluate((probeInsetPx) => {
const requireElement = (selector: string): HTMLElement => {
@@ -213,62 +326,121 @@ test.describe('Editor header drag-region smoke', () => {
const scrollViewport = scrollStrip.parentElement;
if (!scrollViewport) throw new Error('Missing editor tab scroll viewport');
- const leadingActions = requireElement('[data-editor-header-leading-actions]');
- const shareButton = requireElement('[data-testid="share-button"]');
- const trailingActions = requireElement('[data-editor-header-actions]');
- const leadingActionsRect = leadingActions.getBoundingClientRect();
+ const toggleZone = requireElement('[data-file-list-toggle]');
+ const filesTrigger = requireElement('[data-file-list-toggle] [data-sidebar="trigger"]');
+ const appHeader = requireElement('header[data-app-header][data-electron-drag]');
+ const shareButton = requireElement(
+ 'header[data-app-header] [data-app-header-trailing] [data-testid="share-button"]',
+ );
+ const filesTriggerRect = filesTrigger.getBoundingClientRect();
const overflowRootRect = overflowRoot.getBoundingClientRect();
const shareButtonRect = shareButton.getBoundingClientRect();
- const trailingActionsRect = trailingActions.getBoundingClientRect();
- const leadingGapPx = overflowRootRect.left - leadingActionsRect.right;
+ const appHeaderRect = appHeader.getBoundingClientRect();
+ const leadingGapPx = overflowRootRect.left - filesTriggerRect.right;
+ const effectiveRegionAt = (x: number, y: number, what: string) => {
+ let probeElement = document.elementFromPoint(x, y);
+ if (!(probeElement instanceof HTMLElement)) return `${what} covered by no element`;
+ while (probeElement instanceof HTMLElement && appRegion(probeElement) === 'none') {
+ probeElement = probeElement.parentElement;
+ }
+ return probeElement instanceof HTMLElement ? appRegion(probeElement) : 'none';
+ };
const probeLeadingGapRegion = () => {
const measured = `${leadingGapPx.toFixed(2)}px`;
- if (leadingGapPx <= 0) return `tab strip reaches the leading actions (${measured})`;
+ if (leadingGapPx <= 0) return `tab strip reaches the files toggle (${measured})`;
if (leadingGapPx <= probeInsetPx) return `leading gap too narrow to probe (${measured})`;
- const probeX = leadingActionsRect.right + Math.min(probeInsetPx, leadingGapPx / 2);
- const probeY = (leadingActionsRect.top + leadingActionsRect.bottom) / 2;
- const probeElement = document.elementFromPoint(probeX, probeY);
- if (!(probeElement instanceof HTMLElement)) return 'leading gap covered by no element';
- return appRegion(probeElement);
+ const probeX = filesTriggerRect.right + Math.min(probeInsetPx, leadingGapPx / 2);
+ const probeY = (filesTriggerRect.top + filesTriggerRect.bottom) / 2;
+ return effectiveRegionAt(probeX, probeY, 'leading gap');
+ };
+ const paneDivider = requireElement(
+ 'header[data-app-header] [data-testid="header-pane-divider"]',
+ );
+ const paneDividerRect = paneDivider.getBoundingClientRect();
+ const probePaneDividerGap = (side: 'before' | 'after') => {
+ const neighbour =
+ side === 'before'
+ ? paneDivider.parentElement?.previousElementSibling
+ : paneDivider.nextElementSibling;
+ if (!(neighbour instanceof HTMLElement)) return `nothing ${side} the pane divider`;
+ const neighbourRect = neighbour.getBoundingClientRect();
+ const [left, right] =
+ side === 'before' ? [neighbourRect, paneDividerRect] : [paneDividerRect, neighbourRect];
+ const gapPx = right.left - left.right;
+ if (gapPx <= 0) return `no gap ${side} the pane divider (${gapPx.toFixed(2)}px)`;
+ return effectiveRegionAt(
+ left.right + gapPx / 2,
+ (appHeaderRect.top + appHeaderRect.bottom) / 2,
+ `gap ${side} the pane divider`,
+ );
};
return {
- filesButton: appRegionFor('[data-editor-header-leading-actions] [data-sidebar="trigger"]'),
- headerCanvas: appRegionFor('header[data-electron-drag]'),
+ filesButton: appRegion(filesTrigger),
+ headerCanvas: appRegionFor('header[data-editor-header][data-electron-drag]'),
leadingGapRegion: probeLeadingGapRegion(),
- leadingActions: appRegion(leadingActions),
+ filesToggleZone: appRegion(toggleZone),
newTabButton: appRegionFor('[data-testid="editor-new-tab-button"]'),
overflowRoot: appRegion(overflowRoot),
+ paneDivider: effectiveRegionAt(
+ (paneDividerRect.left + paneDividerRect.right) / 2,
+ (paneDividerRect.top + paneDividerRect.bottom) / 2,
+ 'pane divider',
+ ),
+ paneDividerGapAfter: probePaneDividerGap('after'),
+ paneDividerGapBefore: probePaneDividerGap('before'),
paneTabs: appRegion(paneTabs),
- resourcesButton: appRegionFor('[data-editor-header-actions] button:last-of-type'),
scrollViewport: appRegion(scrollViewport),
shareButton: appRegion(shareButton),
shareHasDraggableVerticalGutter:
- shareButtonRect.top > trailingActionsRect.top &&
- shareButtonRect.bottom < trailingActionsRect.bottom &&
- appRegion(trailingActions) === 'drag',
+ shareButtonRect.top > appHeaderRect.top &&
+ shareButtonRect.bottom < appHeaderRect.bottom &&
+ appRegion(appHeader) === 'drag',
+ tabRowHoldsNoShare:
+ document.querySelector('header[data-editor-header] [data-testid="share-button"]') ===
+ null,
tabsHost: appRegion(tabsHost),
- tabsPaintBeforeControls:
- precedes(tabsHost, leadingActions) && precedes(tabsHost, trailingActions),
- trailingActions: appRegion(trailingActions),
+ toggleLeadsFirstPaneRow:
+ paneTabs.contains(toggleZone) && precedes(toggleZone, overflowRoot),
+ appHeaderCanvas: appRegion(appHeader),
};
}, PROBE_INSET_PX);
- expect(appRegions).toEqual({
+ const appHeader = editor.locator('header[data-app-header]');
+ const ptyAvailable = await editor.evaluate(
+ () => window.okDesktop?.config.ptyAvailable === true,
+ );
+ const namedButtonRegions = {
+ agentsButton: await appRegionOfButton(appHeader, 'Agents'),
+ editorButton: await appRegionOfButton(appHeader, 'Editor'),
+ resourcesButton: await appRegionOfButton(appHeader, 'Resources'),
+ terminalButton: ptyAvailable
+ ? await appRegionOfButton(appHeader, 'Terminal')
+ : 'no terminal on this host',
+ };
+
+ expect({ ...appRegions, ...namedButtonRegions }).toEqual({
+ agentsButton: 'no-drag',
+ editorButton: 'no-drag',
filesButton: 'no-drag',
headerCanvas: 'drag',
leadingGapRegion: 'drag',
- leadingActions: 'drag',
+ filesToggleZone: 'drag',
newTabButton: 'no-drag',
overflowRoot: 'drag',
+ paneDivider: 'drag',
+ paneDividerGapAfter: 'drag',
+ paneDividerGapBefore: 'drag',
paneTabs: 'drag',
resourcesButton: 'no-drag',
+ terminalButton: ptyAvailable ? 'no-drag' : 'no terminal on this host',
scrollViewport: 'no-drag',
shareButton: 'no-drag',
shareHasDraggableVerticalGutter: true,
+ tabRowHoldsNoShare: true,
tabsHost: 'drag',
- tabsPaintBeforeControls: true,
- trailingActions: 'drag',
+ toggleLeadsFirstPaneRow: true,
+ appHeaderCanvas: 'drag',
});
const newTabButton = editor.getByTestId('editor-new-tab-button');
@@ -277,8 +449,78 @@ test.describe('Editor header drag-region smoke', () => {
await newTabButton.click();
await expect(newTabPlaceholders).toHaveCount(placeholderCountBefore + 1);
+ const agentsButton = appHeader.getByRole('button', { name: 'Agents', exact: true });
+ await expect(agentsButton).toHaveAttribute('aria-pressed', 'false');
+ await agentsButton.click();
+ await expect(agentsButton).toHaveAttribute('aria-pressed', 'true');
+
const resourcesButton = editor.getByRole('button', { name: 'Resources' });
await resourcesButton.click();
await expect(editor.getByRole('link', { name: 'Docs' })).toBeVisible();
});
+
+ test('keeps one 44px row with the divider and pane buttons in view', async ({
+ captureStderrFor,
+ }) => {
+ const { tmpHome, projectDir } = seedHomeWithLastOpenedProject();
+ const app = await launchApp(tmpHome);
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
+
+ const editor = await findEditorWindow(app);
+ const appHeader = editor.locator('header[data-app-header]');
+ await expect(appHeader.getByRole('button', { name: 'Agents', exact: true })).toBeVisible({
+ timeout: 20_000,
+ });
+ const ptyAvailable = await editor.evaluate(
+ () => window.okDesktop?.config.ptyAvailable === true,
+ );
+
+ const winHandle: JSHandle = await app.browserWindow(editor);
+ await winHandle.evaluate((win: unknown, size) => {
+ (win as { setSize: (width: number, height: number, animate: boolean) => void }).setSize(
+ size.width,
+ size.height,
+ false,
+ );
+ }, WINDOW_MIN_SIZE.EDITOR);
+ await expect
+ .poll(() => editor.evaluate(() => window.innerWidth), {
+ timeout: 10_000,
+ message: 'the editor window never narrowed to its minimum width',
+ })
+ .toBeLessThanOrEqual(WINDOW_MIN_SIZE.EDITOR.width);
+
+ await expect
+ .poll(() => editor.evaluate(readSettledHeaderFit, HEADER_SETTLE_FRAMES), {
+ timeout: 10_000,
+ message: 'the app header did not settle into one clean row at the minimum width',
+ })
+ .toEqual({
+ headerHeight: 44,
+ outsideRow: [],
+ outsideWindow: [],
+ overlapping: [],
+ paneControls: [
+ 'header-pane-divider',
+ 'header-pane-button-editor',
+ 'header-pane-button-agents',
+ ...(ptyAvailable ? ['header-pane-button-terminal'] : []),
+ ],
+ underWindowControls: [],
+ });
+
+ const widths = await editor.evaluate(() => {
+ const overlay = (
+ navigator as Navigator & {
+ windowControlsOverlay?: { visible: boolean; getTitlebarAreaRect(): DOMRect };
+ }
+ ).windowControlsOverlay;
+ const titlebar = overlay?.visible === true ? overlay.getTitlebarAreaRect() : null;
+ return {
+ innerWidth: window.innerWidth,
+ captionWidth: titlebar === null ? null : window.innerWidth - (titlebar.x + titlebar.width),
+ };
+ });
+ console.log(`[window-chrome] minimum-width header: ${JSON.stringify(widths)}`);
+ });
});
diff --git a/turbo.json b/turbo.json
index a702f62c7..926621eba 100644
--- a/turbo.json
+++ b/turbo.json
@@ -301,6 +301,11 @@
"cache": false,
"passThroughEnv": ["OK_TEST_E2E_SERVING"]
},
+ "@inkeep/open-knowledge-app#test:e2e": {
+ "dependsOn": ["^build", "build", "@inkeep/open-knowledge#build"],
+ "cache": false,
+ "passThroughEnv": ["OK_TEST_E2E_SERVING"]
+ },
"test:perf": {
"dependsOn": [],
"cache": false,