From d0b4444f0a5312ff2a6941183c48fac0c8dfa571 Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 10:46:46 +0100 Subject: [PATCH 1/7] Plan: typed keys reach the current terminal; repo tabs on Alt+Left/Right, terminal tabs on Ctrl+Shift+Left/Right --- .../.openspec.yaml | 2 + .../design.md | 60 ++++++++ .../proposal.md | 29 ++++ .../specs/web/spec.md | 128 ++++++++++++++++++ .../tasks.md | 34 +++++ 5 files changed, 253 insertions(+) create mode 100644 openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml create mode 100644 openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md create mode 100644 openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md create mode 100644 openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md create mode 100644 openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml new file mode 100644 index 0000000..41484f3 --- /dev/null +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-18 diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md new file mode 100644 index 0000000..75fbcae --- /dev/null +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md @@ -0,0 +1,60 @@ +## Context + +See proposal.md (Why). Current focus plumbing: + +- `View.sync()` (`src/web/ui/view.ts`) calls `manager.focus(host, focused)` only when `focusKey` (host, shown panes, focused pane, modal) changes — edge-triggered, while the `Pane focus` requirement is level-triggered. This is the structural cause: every other way of losing the focus (a clicked button, the page body, a re-rendered element, a window switch) would need its own patch. +- `src/web/main/index.ts` has a document `keydown` listener routing keys outside terminals to `view.handleKey(event, false)`. +- `focusSpot` / `choicesTakeFocus` live in `src/web/ui/picker.ts`, the DOM reader `activeSpot(manager)` in `src/web/ui/app.tsx`. +- xterm 6 turns Enter, arrows, Backspace, Ctrl keys and most printable keys into input in its own `keydown` handler on its textarea (reading `keyCode`); upper-case A–Z and dead keys wait for `keypress`. A `keydown` dispatched on the page body never reaches that handler, so moving the focus during `keydown` alone loses the first key. + +Architecture: touches `typescript.web.ui`, `typescript.web.terminals` (one public method) and `typescript.web.main` (wiring). The existing arrows `ui → terminals`, `main → ui`, `main → terminals` cover every call; no model or arc42 change. Principles that apply: web 1 (no Node APIs), web 3 (`terminals` never depends on `ui` — the policy stays in `ui`, `terminals` only delivers), web 4 (no terminal re-created); system 1–2 (imports only through each element's `index.ts`), system 4 (strict tsc/lint), system 6 (no swallowed errors), system 8 (unit tests beside the code, e2e in `test/e2e`). + +## Goals / Non-Goals + +**Goals:** +- One rule, applied by three triggers, decides whether the current terminal takes the keyboard focus (see the `Pane focus` delta). +- The first key typed while nothing holds the keyboard reaches the terminal exactly once. +- Repo-tab and terminal-tab keyboard navigation as in the `Keyboard shortcuts` delta. + +**Non-Goals:** +- No change to how the preset choices (worktree without terminals) take or keep the focus: without a current terminal the rule never fires. +- Pickers, dialogs and the worktree menu keep their modal key handling unchanged. + +## Decisions + +**D1. One level-triggered rule at three triggers (default — structural fix).** A pure `terminalTakesFocus` in a new `src/web/ui/focus.ts` decides; the triggers are a pointer click, a key pressed outside the terminals, and the window `focus` event. Alternative — patch each focus-losing path (row click, tab click, refocus…) — rejected: N code paths that must agree by hand, and the next path is missed again. `View.sync()` keeps focusing on `focusKey` changes. + +**D2. Which controls hold the keyboard: by how they got the focus (user).** Options: split by key (Enter/Space/Tab/Escape/arrows/Home/End/PgUp/PgDn stay with a focused control, others go to the terminal); split by focus origin; every key to the terminal. Taken: by focus origin — a control the user clicked does not hold the keyboard (treated like the page body), a control focused from the keyboard or by the page holds every key. Why: any first key after a click reaches the terminal (Enter, arrows, Escape included) while keyboard navigation of tabs, labels and the separator keeps working. + +**D3. Selected page text (user).** Options: hold every key while text outside the terminals is selected; hold only Ctrl/Meta keys; no exception. Taken: a click or window refocus leaving such a selection does not move the focus, and a key pressed with Ctrl or Meta while it exists stays with the page; other keys go to the terminal. Why: Ctrl+C copies the selection instead of interrupting the terminal's program. + +**D4. Focus origin is tracked explicitly (codex).** The DOM does not record how an element got the focus, and no `click` fires after some pointer interactions (drags ending elsewhere, context menus). A tracker in `ui` marks the element that gains the focus during a pointer interaction (from a capture-phase `pointerdown` until that interaction's click task has run) as clicked; a focus gained otherwise — Tab, script, Playwright's `locator.focus()` — is not. The rule therefore sees spot `other` together with a `clicked` flag, and a stale clicked control is repaired by the next key or window refocus even when no `click` fired. Alternative `:focus-visible` rejected: a browser heuristic, where a script focus after a click inherits pointer modality, which would break the existing scripted-focus tests (`keyboard.spec.ts` focuses the checked filter, `sidebar.spec.ts` the worktree label). + +**D5. Key delivery is a designed forward, not a focus move (codex).** New public `TerminalManager.forwardKey(host, termId, event)`: focuses the terminal and replays the `keydown` on xterm's textarea (a copy carrying `key`, `code`, `keyCode`, modifiers, `repeat`, `location`), so xterm's own key handling and the installed key filter apply. If xterm handled the replay (it cancelled it), the original event is cancelled, so nothing is delivered twice; otherwise the original's default proceeds and the following `keypress` reaches the now-focused textarea (upper-case letters, dead keys). A key whose default the page already prevented (a control's own handler, e.g. Enter on a worktree label) is never forwarded. + +**D6. Keys being composed are never claimed (codex).** `isComposing`, `key === 'Process'` and `key === 'Dead'` keys stay where they are. + +**D7. Page selection classification (codex).** "Text outside the terminals is selected" = the document selection is non-collapsed and not wholly inside the terminal layer (page-owned or mixed counts); a range with an endpoint no longer in the document is ignored. A pure classifier over (collapsed, anchor in terminals, focus in terminals, endpoints connected) is unit-tested; selections inside inputs are covered by the text-field rule. + +**D8. Any open menu blocks the claim (codex).** Not only when it holds the focus: any element with `aria-expanded="true"` or `role="menu"` present on the page blocks it, as do `view.modal` (pickers, dialogs, worktree menu, editor failure dialog) and a text field or terminal holding the focus. + +**D9. Click claim timing (codex).** The click trigger runs after the click's own handlers and the render they cause (a task later), re-reads the focus when it runs, and is cancelled by a `dblclick`, so the rename field, menus and dialogs take their focus first. Clicks generated by the keyboard (`detail === 0`) are not pointer clicks. + +**D10. Clicking a new worktree or repo tab focuses its terminal at once (user).** In scope. Covered by the click trigger; in addition pr-implement finds why `sync()`'s own focus call does not win today and removes that cause rather than relying on the second trigger alone. + +**D11. Shortcuts first (default).** `view.handleKey` runs before the rule; a shortcut never moves the focus beyond what its action does. + +**D12. Window refocus reclaims from nothing-holds only (default).** A control focused from the keyboard keeps the focus across a window switch (D2). + +**D13. Module placement (default).** `focus.ts` in `ui` holds the rule, the moved `focusSpot` / `FocusSpot` / `FocusedElement` / `choicesTakeFocus` / `ChoicesTrigger` (from `picker.ts`), the moved `activeSpot` DOM reader (from `app.tsx`), the origin tracker and the selection classifier — one focus classifier for `View` and `app.tsx`. Their tests move from `picker.test.ts` to `focus.test.ts`. + +**D14. Repo tabs on Alt+Left/Right; terminal tabs on Ctrl+Shift+Left/Right (user).** Options considered for repo tabs: Ctrl+arrows (rejected: word jumps in shells and editors), Shift+arrows (rejected: text selection in TUIs/editors), Ctrl+Shift+Left/Right with terminal tabs kept on Alt+Left/Right (recommended first), Alt+Left/Right. Taken: Alt+Left/Right for repo tabs, because switching repos is far more frequent than switching terminal tabs. Terminal tabs then: Ctrl+Shift+Left/Right (kitty's convention, fits the Ctrl+Shift family; costs word-selection in some editors) over Alt+PageUp/PageDown (Fn on laptops) — Ctrl+PageUp/PageDown is reserved by Chrome. Both are navigation shortcuts (repeat when held); repo navigation follows the shown repo-tab order and stops at either end. Worktrees stay on Alt+Up/Down, which already keeps the focus in the terminal. Aligning `src/web/ui/keymap.test.ts`, `test/e2e/keyboard.spec.ts` and `test/e2e/splits.spec.ts` (which pin Alt+Left/Right as terminal-tab keys) and the README shortcut table follows from this decision. + +**D15. Codex finding rejected (codex, rejected).** "The global claim competes with the preset choices' own focus restoration (DEV-2278)": rejected — the choices appear only for a worktree without terminals, where there is no current terminal and the rule never fires; a unit row pins it. + +## Risks / Trade-offs + +- [Replayed `keydown` behaves differently from a trusted one in xterm (e.g. `keyCode` not settable from the event init)] → e2e first-key scenario with every key class against `cat -v` / a shell; define `keyCode` on the copy if the init ignores it. +- [Delayed click claim races focus set by effects] → the claim re-reads the focus at run time and a `dblclick` cancels it; double-click rename e2e. +- [Pointer-origin window too wide or narrow] → unit tests of the tracker's transitions (pointerdown → focusin → click task end; keyboard focus; script focus). +- [Ctrl+Shift+Left/Right no longer reach editors inside the terminal] → accepted (D14). diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md new file mode 100644 index 0000000..d62bbbf --- /dev/null +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md @@ -0,0 +1,29 @@ +## Why + +Keys typed in the focused wtd window often go nowhere until the user clicks into the terminal: after clicking a sidebar row (even a newly selected worktree's), a repo or terminal tab, a pane header button or the page background, or after the window regains the focus. The `Pane focus` requirement already promises the focused pane holds the keyboard, but the page only moves the focus when the shown tab, focused pane or modal state changes, so every other way of losing it is never repaired. Switching repos also has no keyboard shortcut, although it is far more frequent than switching terminal tabs. + +## What Changes + +- One rule decides whether the current terminal may take the keyboard focus. Three triggers apply it: a pointer click, a key pressed while nothing holds the keyboard, and the window regaining the focus. +- A control the user clicked no longer holds the keyboard; a control focused from the keyboard or by the page still does. Text fields, open menus, pickers and dialogs keep the keyboard as now. +- A key pressed while nothing holds the keyboard reaches the current terminal, the first key included (Enter, arrows, Backspace and Ctrl keys too), except shortcuts, keys being composed with an input method, and Ctrl/Meta keys while text outside the terminals is selected. +- Clicking an unselected worktree's row or a repo tab gives the new current terminal the keyboard focus without a second click. +- **BREAKING** (keyboard): Alt+Left / Alt+Right select the previous / next repo tab; choosing the previous / next terminal tab moves to Ctrl+Shift+Left / Ctrl+Shift+Right. + +## Capabilities + +### New Capabilities + +(none) + +### Modified Capabilities + +- `web`: `Pane focus` (when the current terminal takes the keyboard focus) and `Keyboard shortcuts` (repo-tab navigation on Alt+Left/Right, terminal-tab navigation on Ctrl+Shift+Left/Right). + +## Impact + +- `src/web/ui`: new `focus.ts` (the rule, the focus classifier moved from `picker.ts` and `app.tsx`, focus-origin tracking, page-selection classification); `view.ts` (claiming the focus, repo-tab stepping); `keymap.ts` (new bindings); `app.tsx` (uses the moved classifier). +- `src/web/terminals/manager.ts`: a public method forwarding a key event to a terminal. +- `src/web/main/index.ts`: wiring of the click, key and window-focus triggers. +- `README.md` shortcut table. +- No architecture model change: the existing `ui → terminals` and `main → terminals` arrows cover the new calls. diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md new file mode 100644 index 0000000..76a3451 --- /dev/null +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md @@ -0,0 +1,128 @@ +## MODIFIED Requirements + +### Requirement: Pane focus +Each tab SHALL have one focused pane, kept per page and not stored: the first pane until the user chooses another, the pane the user clicks, a new pane once created, and, when the focused pane's terminal closes, the first pane of the subtree that took its place. In a split, the focused pane's header SHALL be shown in the accent colour. While its tab is shown and no picker or dialog is open, the focused pane's terminal is the current terminal: it SHALL take the keyboard focus when its tab is shown, when it becomes the focused pane and when a picker or dialog closes. Nothing holds the keyboard while the keyboard focus is on the page body or on a control the user clicked, and no text field, open menu, picker or dialog is present to hold it; a control focused from the keyboard or by the page holds it. While nothing holds the keyboard, a pointer click and the window regaining the focus SHALL give the keyboard focus to the current terminal unless text outside the terminals is selected, and a key SHALL reach the current terminal, the first key included, unless it is a keyboard shortcut, is being composed with an input method, or is pressed with Ctrl or Meta while text outside the terminals is selected. Without a current terminal, none of this SHALL move the keyboard focus. + +#### Scenario: Focus follows a closed pane's sibling +- **WHEN** the focused pane of a two-pane split is closed +- **THEN** the remaining pane is focused and receives typed input + +#### Scenario: Focus follows a cleanly exited pane's sibling +- **WHEN** the user types `exit` in the focused pane of a two-pane split +- **THEN** the remaining pane is focused and receives typed input + +#### Scenario: Clicking another worktree focuses its terminal +- **WHEN** a terminal of the selected worktree has the keyboard focus, the user clicks the row of another worktree that has a terminal, and types `echo b` and Enter +- **THEN** the other worktree's current terminal has the keyboard focus and runs `echo b`, without a further click + +#### Scenario: Clicking another repo tab focuses its terminal +- **WHEN** the user clicks another repo tab whose selected worktree has a terminal and types text +- **THEN** the text reaches that repo's current terminal + +#### Scenario: Typing after clicking the selected worktree's row +- **WHEN** the user clicks the selected worktree's row and types `echo row` +- **THEN** `echo row` reaches the current terminal + +#### Scenario: Typing after clicking the active terminal tab +- **WHEN** the user clicks the active terminal tab and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after clicking the page background +- **WHEN** the user clicks an empty part of the tab bar and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after clicking a disabled control +- **WHEN** the split controls are disabled, the user clicks one and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after dragging the sidebar edge +- **WHEN** the user drags the sidebar's right edge to a new width and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after the clicked control disappears +- **WHEN** the user closes a tab whose terminal exited with its close control, no dialog is shown, and the user types text +- **THEN** the text reaches the current terminal + +#### Scenario: First key not lost +- **WHEN** the keyboard focus is on the page body and the user presses, one at a time, a lower-case letter, an upper-case letter, an arrow key, Backspace, Enter and Ctrl+C +- **THEN** the current terminal's program receives each of those keys exactly once, the first included + +#### Scenario: Window refocus +- **WHEN** the keyboard focus is on the page body or on a control the user clicked, the window loses the focus and regains it, and the user types text +- **THEN** the current terminal has the keyboard focus and the text reaches it + +#### Scenario: Search keeps its keys +- **WHEN** the worktree search has the keyboard focus and the user types text +- **THEN** the text appears in the search and nothing reaches the current terminal + +#### Scenario: Add form keeps its keys +- **WHEN** the add form in the preset picker has the keyboard focus and the user types text +- **THEN** the text appears in the form and nothing reaches the current terminal + +#### Scenario: Rename field keeps its keys +- **WHEN** the user double-clicks a terminal tab and types text +- **THEN** the rename field has the keyboard focus with its text selected before typing, the typed text replaces it, and nothing reaches the current terminal + +#### Scenario: Open menu keeps its keys +- **WHEN** the Hubs menu is open and the user types a letter +- **THEN** the menu stays open and nothing reaches the current terminal + +#### Scenario: A control focused from the keyboard keeps its keys +- **WHEN** the user focuses an inactive terminal tab from the keyboard and presses Enter +- **THEN** that tab is shown with its terminal focused, and no Enter reached the previously focused terminal's program + +#### Scenario: Copying selected page text +- **WHEN** the user selects a worktree's name in the sidebar with the pointer and presses Ctrl+C, then types `x` +- **THEN** the name is copied to the clipboard, the current terminal's program receives no Ctrl+C, and `x` reaches the current terminal + +#### Scenario: Shortcut while nothing holds the keyboard +- **WHEN** the keyboard focus is on the page body and the user presses Alt+Down +- **THEN** the next worktree is selected, its current terminal has the keyboard focus, and nothing reached any terminal's program + +#### Scenario: No current terminal +- **WHEN** the selected worktree has no terminals and the user clicks an empty part of the terminal area +- **THEN** no terminal takes the keyboard focus + +### Requirement: Keyboard shortcuts +The page SHALL handle these shortcuts whether the keyboard focus is in a terminal or elsewhere on the page, except while a picker or dialog is open or text is being composed with an input method; a handled shortcut SHALL act once per key press, SHALL NOT reach the terminal's program, and SHALL suppress the browser's own action: +- Alt+Up / Alt+Down: select the previous / next worktree as listed in the sidebar under the current filter, doing nothing at either end. +- Alt+Left / Alt+Right: select the previous / next repo tab in the order the tabs are shown, doing nothing at either end. +- Ctrl+Shift+Left / Ctrl+Shift+Right: choose the previous / next terminal tab, doing nothing at either end. +- Alt+Shift+Left/Right/Up/Down: focus the pane in that direction — among panes lying wholly beyond the focused pane's edge on that side, the one overlapping it most along the other axis, then the nearest, then the first in the tab's order; nothing when there is none. +- Ctrl+Shift+T: new tab; Ctrl+Shift+D: split right; Ctrl+Shift+E: split down; each through the preset picker and only when the corresponding control is enabled. +- Ctrl+Shift+W: close the focused pane, as specified for closing terminals. +- Ctrl+Shift+C: copy the focused terminal's selection to the clipboard; nothing without a selection; a failed copy SHALL be reported on the page. +- Ctrl+Shift+V: paste the clipboard into the focused terminal as pasted text; the browser's paste SHALL be let through to the terminal. +Holding a navigation shortcut (worktree, repo tab, terminal tab or pane) SHALL repeat it; holding any other shortcut SHALL act once. + +#### Scenario: Worktree navigation respects the filter +- **WHEN** the filter is "checked only" and the user presses Alt+Down +- **THEN** the next checked worktree is selected, skipping unchecked ones + +#### Scenario: Navigation stops at the end +- **WHEN** the last listed worktree is selected and the user presses Alt+Down +- **THEN** the selection does not change + +#### Scenario: Navigation keeps the keyboard in the terminal +- **WHEN** a terminal has the keyboard focus and the user presses Alt+Down onto a worktree that has a terminal, then types text +- **THEN** that worktree's current terminal has the keyboard focus and the text reaches it + +#### Scenario: Repo navigation +- **WHEN** the first of three repo tabs is selected and the user presses Alt+Right twice, then once more +- **THEN** the third repo tab is selected, its current terminal has the keyboard focus, and the last press changes nothing + +#### Scenario: Tab navigation +- **WHEN** the first of three terminal tabs is active and the user presses Ctrl+Shift+Right twice +- **THEN** the third tab is active + +#### Scenario: Pane navigation +- **WHEN** a tab is split right and its right pane split down with ratio 0.3, the top-right pane is focused, and the user presses Alt+Shift+Left and then Alt+Shift+Right +- **THEN** the left pane is focused and then the bottom-right pane, the one overlapping the left pane most + +#### Scenario: Shortcut does not reach the program +- **WHEN** a terminal running `cat -v` is focused and the user presses Alt+Up, Alt+Left or Ctrl+Shift+Left +- **THEN** nothing is echoed by `cat` + +#### Scenario: Copy and paste +- **WHEN** the user selects text in a terminal, presses Ctrl+Shift+C, focuses another terminal and presses Ctrl+Shift+V +- **THEN** the selected text is typed into the second terminal diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md new file mode 100644 index 0000000..abbcf68 --- /dev/null +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md @@ -0,0 +1,34 @@ +## 1. Tests first (pr-tests) + +- [ ] 1.1 `src/web/ui/focus.test.ts`: full truth table of `terminalTakesFocus` (trigger click / key / windowFocus × spot none / terminal / menu / textField / other-clicked / other-not-clicked × modal × open menu present × current terminal × page selection × Ctrl/Meta × composing incl. `Process`/`Dead`), including the no-current-terminal row standing for the preset choices (design D15); move the `focusSpot` / `choicesTakeFocus` cases from `picker.test.ts`; verify they fail for the missing module +- [ ] 1.2 `focus.test.ts`: focus-origin tracker transitions (pointerdown → focusin → after the click task = clicked; Tab/script focus = not clicked; a later script focus after a click = not clicked) and the page-selection classifier (collapsed, terminal-only, page-only, mixed, disconnected endpoint); verify they fail +- [ ] 1.3 `view` unit test for the claim (typed fake `TerminalManager`): claims `forwardKey`/`focus` on the focused pane only when the rule allows, never for a key whose default was prevented; repo-tab stepping in shown order, stopping at both ends; verify they fail +- [ ] 1.4 Align `src/web/ui/keymap.test.ts` to design D14 (Alt+Left/Right → repo tab, Ctrl+Shift+Left/Right → terminal tab, both navigation/repeating); verify the new rows fail +- [ ] 1.5 New `test/e2e/focus.spec.ts` covering every new `Pane focus` scenario of the delta; assert terminal screen contents (via `__wtdInspect` / `cat -v`) and `document.activeElement`; first-key scenario covers lower-case, upper-case, an arrow, Backspace, Enter, Ctrl+C with no duplicates; verify they fail +- [ ] 1.6 Align `test/e2e/keyboard.spec.ts` and `test/e2e/splits.spec.ts` (Alt+Left/Right as terminal-tab keys) to Ctrl+Shift+Left/Right; add the `Repo navigation`, `Navigation keeps the keyboard in the terminal` and extended `Shortcut does not reach the program` scenarios; verify they fail +- [ ] 1.7 Codex review of the tests against the spec delta and design + +## 2. Focus rule and tracking (`src/web/ui/focus.ts`) + +- [ ] 2.1 Create `focus.ts`; move `focusSpot`, `FocusSpot`, `FocusedElement`, `choicesTakeFocus`, `ChoicesTrigger` from `picker.ts` and `activeSpot` from `app.tsx`; update imports; verify `pnpm test` unit tier for picker/focus passes +- [ ] 2.2 Implement `terminalTakesFocus`, the page-selection classifier and the focus-origin tracker (design D2–D4, D6–D8); verify 1.1–1.2 pass + +## 3. Terminal key delivery (`src/web/terminals/manager.ts`) + +- [ ] 3.1 Add public `forwardKey(host, termId, event)` per design D5 (replay keydown on xterm's textarea with `keyCode` defined, cancel the original only when xterm handled the replay); verify the first-key e2e scenario passes with no duplicate input + +## 4. Wiring (`view.ts`, `main/index.ts`) + +- [ ] 4.1 `View`: claim method applying the rule for the three triggers; key trigger runs after `handleKey` and skips default-prevented keys; verify 1.3 passes +- [ ] 4.2 `main/index.ts`: document `keydown` → claim; document `click` (pointer clicks only, `detail !== 0`) → claim a task later, re-reading the focus, cancelled by `dblclick`; `window` `focus` → claim; install the origin tracker (design D9) +- [ ] 4.3 Find why `sync()`'s own focus call loses after clicking a new worktree row or repo tab and remove that cause (design D10); verify the `Clicking another worktree/repo tab` scenarios pass + +## 5. Shortcuts + +- [ ] 5.1 `keymap.ts`: new `repo` action on Alt+Left/Right, `tab` on Ctrl+Shift+Left/Right (navigation); `View.stepRepo` over the shown repo tabs; verify 1.4 and 1.6 pass +- [ ] 5.2 README shortcut table updated to the new bindings + +## 6. Gates + +- [ ] 6.1 Run the local test scope (`la-affected-tests --base main` plus the e2e specs above, `keyboard.spec.ts`, `splits.spec.ts`, `picker.spec.ts`, `sidebar.spec.ts`, `tab-names.spec.ts`, `terminals.spec.ts`); all green +- [ ] 6.2 Enforcement bundle: `la-arch-check`, LikeC4 validation, `tsc -b`, `pnpm lint`; all green From 69e742501e59bbc6ffc36ca29d341c2c7ec15a99 Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 11:57:58 +0100 Subject: [PATCH 2/7] Failing tests: typed keys and clicks give the current terminal the focus; repo tabs on Alt+Left/Right, terminal tabs on Ctrl+Shift+Left/Right --- .../tasks.md | 14 +- src/web/ui/focus.test.ts | 360 +++++++++++++++++ src/web/ui/keymap.test.ts | 12 +- src/web/ui/picker.test.ts | 90 +---- src/web/ui/view.test.ts | 323 +++++++++++++++ test/e2e/fixture.ts | 15 + test/e2e/focus.spec.ts | 373 ++++++++++++++++++ test/e2e/keyboard.spec.ts | 81 +++- test/e2e/splits.spec.ts | 4 +- 9 files changed, 1161 insertions(+), 111 deletions(-) create mode 100644 src/web/ui/focus.test.ts create mode 100644 src/web/ui/view.test.ts create mode 100644 test/e2e/focus.spec.ts diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md index abbcf68..bce0ea3 100644 --- a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md @@ -1,12 +1,12 @@ ## 1. Tests first (pr-tests) -- [ ] 1.1 `src/web/ui/focus.test.ts`: full truth table of `terminalTakesFocus` (trigger click / key / windowFocus × spot none / terminal / menu / textField / other-clicked / other-not-clicked × modal × open menu present × current terminal × page selection × Ctrl/Meta × composing incl. `Process`/`Dead`), including the no-current-terminal row standing for the preset choices (design D15); move the `focusSpot` / `choicesTakeFocus` cases from `picker.test.ts`; verify they fail for the missing module -- [ ] 1.2 `focus.test.ts`: focus-origin tracker transitions (pointerdown → focusin → after the click task = clicked; Tab/script focus = not clicked; a later script focus after a click = not clicked) and the page-selection classifier (collapsed, terminal-only, page-only, mixed, disconnected endpoint); verify they fail -- [ ] 1.3 `view` unit test for the claim (typed fake `TerminalManager`): claims `forwardKey`/`focus` on the focused pane only when the rule allows, never for a key whose default was prevented; repo-tab stepping in shown order, stopping at both ends; verify they fail -- [ ] 1.4 Align `src/web/ui/keymap.test.ts` to design D14 (Alt+Left/Right → repo tab, Ctrl+Shift+Left/Right → terminal tab, both navigation/repeating); verify the new rows fail -- [ ] 1.5 New `test/e2e/focus.spec.ts` covering every new `Pane focus` scenario of the delta; assert terminal screen contents (via `__wtdInspect` / `cat -v`) and `document.activeElement`; first-key scenario covers lower-case, upper-case, an arrow, Backspace, Enter, Ctrl+C with no duplicates; verify they fail -- [ ] 1.6 Align `test/e2e/keyboard.spec.ts` and `test/e2e/splits.spec.ts` (Alt+Left/Right as terminal-tab keys) to Ctrl+Shift+Left/Right; add the `Repo navigation`, `Navigation keeps the keyboard in the terminal` and extended `Shortcut does not reach the program` scenarios; verify they fail -- [ ] 1.7 Codex review of the tests against the spec delta and design +- [x] 1.1 `src/web/ui/focus.test.ts`: full truth table of `terminalTakesFocus` (trigger click / key / windowFocus × spot none / terminal / menu / textField / other-clicked / other-not-clicked × modal × open menu present × current terminal × page selection × Ctrl/Meta × composing incl. `Process`/`Dead`), including the no-current-terminal row standing for the preset choices (design D15); move the `focusSpot` / `choicesTakeFocus` cases from `picker.test.ts`; verify they fail for the missing module +- [x] 1.2 `focus.test.ts`: focus-origin tracker transitions (pointerdown → focusin → after the click task = clicked; Tab/script focus = not clicked; a later script focus after a click = not clicked) and the page-selection classifier (collapsed, terminal-only, page-only, mixed, disconnected endpoint); verify they fail +- [x] 1.3 `view` unit test for the claim (typed fake `TerminalManager`): claims `forwardKey`/`focus` on the focused pane only when the rule allows, never for a key whose default was prevented; repo-tab stepping in shown order, stopping at both ends; verify they fail +- [x] 1.4 Align `src/web/ui/keymap.test.ts` to design D14 (Alt+Left/Right → repo tab, Ctrl+Shift+Left/Right → terminal tab, both navigation/repeating); verify the new rows fail +- [x] 1.5 New `test/e2e/focus.spec.ts` covering every new `Pane focus` scenario of the delta; assert terminal screen contents (via `__wtdInspect` / `cat -v`) and `document.activeElement`; first-key scenario covers lower-case, upper-case, an arrow, Backspace, Enter, Ctrl+C with no duplicates; verify they fail +- [x] 1.6 Align `test/e2e/keyboard.spec.ts` and `test/e2e/splits.spec.ts` (Alt+Left/Right as terminal-tab keys) to Ctrl+Shift+Left/Right; add the `Repo navigation`, `Navigation keeps the keyboard in the terminal` and extended `Shortcut does not reach the program` scenarios; verify they fail +- [x] 1.7 Codex review of the tests against the spec delta and design ## 2. Focus rule and tracking (`src/web/ui/focus.ts`) diff --git a/src/web/ui/focus.test.ts b/src/web/ui/focus.test.ts new file mode 100644 index 0000000..63a1bce --- /dev/null +++ b/src/web/ui/focus.test.ts @@ -0,0 +1,360 @@ +import { describe, expect, it } from 'vitest'; +import { + choicesTakeFocus, + FocusOrigin, + focusSpot, + pageTextSelected, + terminalTakesFocus, + type ChoicesTrigger, + type ClaimKey, + type ClaimTrigger, + type FocusedElement, + type FocusSpot, + type FocusWorld, + type SelectionFacts, +} from './focus.js'; + +describe('focusSpot', () => { + const element = (fields: Partial = {}): FocusedElement => ({ + tag: 'div', + type: '', + editable: false, + terminal: false, + menu: false, + ...fields, + }); + + it('is none without a focused element or on the page body', () => { + expect(focusSpot(null)).toBe('none'); + expect(focusSpot(element({ tag: 'body' }))).toBe('none'); + }); + + it.each(['text', 'search', 'email', 'url', 'tel', 'password', 'number'])('is a text field for an input of type %j', (type) => { + expect(focusSpot(element({ tag: 'input', type }))).toBe('textField'); + }); + + it('is a text field for a textarea and inside an editable element', () => { + expect(focusSpot(element({ tag: 'textarea' }))).toBe('textField'); + expect(focusSpot(element({ tag: 'div', editable: true }))).toBe('textField'); + expect(focusSpot(element({ tag: 'span', editable: true }))).toBe('textField'); + }); + + it.each(['checkbox', 'radio', 'button', 'submit', 'range', 'color', 'file'])('is other for an input of type %j', (type) => { + expect(focusSpot(element({ tag: 'input', type }))).toBe('other'); + }); + + it('is other for buttons, options and plain elements', () => { + expect(focusSpot(element({ tag: 'button' }))).toBe('other'); + expect(focusSpot(element({ tag: 'div' }))).toBe('other'); + expect(focusSpot(element({ tag: 'dialog' }))).toBe('other'); + }); + + it('is a menu on a control whose menu is open or inside an open menu, even a text field', () => { + expect(focusSpot(element({ tag: 'button', menu: true }))).toBe('menu'); + expect(focusSpot(element({ tag: 'input', type: 'text', menu: true }))).toBe('menu'); + }); + + it('is a terminal for an element the terminal manager owns, even a textarea', () => { + expect(focusSpot(element({ tag: 'textarea', terminal: true }))).toBe('terminal'); + expect(focusSpot(element({ tag: 'div', terminal: true }))).toBe('terminal'); + expect(focusSpot(element({ tag: 'div', editable: true, terminal: true }))).toBe('terminal'); + expect(focusSpot(element({ tag: 'div', terminal: true, menu: true }))).toBe('terminal'); + }); +}); + +describe('choicesTakeFocus', () => { + const spots: readonly FocusSpot[] = ['none', 'terminal', 'other', 'textField', 'menu']; + + it.each<[FocusSpot, boolean]>([ + ['none', true], + ['terminal', true], + ['other', true], + ['textField', false], + ['menu', false], + ])('when shown, takes the focus from %s: %s', (spot, takes) => { + expect(choicesTakeFocus('shown', spot, false)).toBe(takes); + }); + + it.each<[FocusSpot, boolean]>([ + ['none', true], + ['terminal', false], + ['other', false], + ['textField', false], + ['menu', false], + ])('after a picker or dialog closed, takes the focus from %s: %s', (spot, takes) => { + expect(choicesTakeFocus('modalClosed', spot, false)).toBe(takes); + }); + + it.each(['shown', 'modalClosed'])('never takes the focus while a picker or dialog is open (%s)', (trigger) => { + for (const spot of spots) expect(choicesTakeFocus(trigger, spot, true)).toBe(false); + }); +}); + +describe('terminalTakesFocus', () => { + const key = (fields: Partial = {}): ClaimKey => ({ key: 'x', ctrlKey: false, metaKey: false, isComposing: false, ...fields }); + + const CLICK: ClaimTrigger = { t: 'click' }; + const WINDOW: ClaimTrigger = { t: 'windowFocus' }; + const KEY: ClaimTrigger = { t: 'key', key: key() }; + const TRIGGERS: [string, ClaimTrigger][] = [ + ['click', CLICK], + ['windowFocus', WINDOW], + ['key', KEY], + ]; + + /** Nothing holds the keyboard, a current terminal exists, no page text is selected. */ + const world = (fields: Partial = {}): FocusWorld => ({ + spot: 'none', + clicked: false, + modal: false, + menuOpen: false, + currentTerminal: true, + pageSelection: false, + ...fields, + }); + + it.each(TRIGGERS)('claims from the page body (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world())).toBe(true); + }); + + it.each(TRIGGERS)('claims from a control the user clicked (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ spot: 'other', clicked: true }))).toBe(true); + }); + + it.each(TRIGGERS)('leaves a control focused from the keyboard or by the page (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ spot: 'other', clicked: false }))).toBe(false); + }); + + it.each(TRIGGERS)('does nothing while a terminal holds the focus (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ spot: 'terminal' }))).toBe(false); + expect(terminalTakesFocus(trigger, world({ spot: 'terminal', clicked: true }))).toBe(false); + }); + + it.each(TRIGGERS)('leaves a text field, even a clicked one (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ spot: 'textField' }))).toBe(false); + expect(terminalTakesFocus(trigger, world({ spot: 'textField', clicked: true }))).toBe(false); + }); + + it.each(TRIGGERS)('leaves an open menu holding the focus, even a clicked one (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ spot: 'menu' }))).toBe(false); + expect(terminalTakesFocus(trigger, world({ spot: 'menu', clicked: true }))).toBe(false); + }); + + it.each(TRIGGERS)('does nothing while any menu is open on the page, focused or not (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ menuOpen: true }))).toBe(false); + expect(terminalTakesFocus(trigger, world({ spot: 'other', clicked: true, menuOpen: true }))).toBe(false); + }); + + it.each(TRIGGERS)('does nothing while a picker or dialog is open (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ modal: true }))).toBe(false); + expect(terminalTakesFocus(trigger, world({ spot: 'other', clicked: true, modal: true }))).toBe(false); + }); + + it.each(TRIGGERS)('does nothing without a current terminal (%s)', (_name, trigger) => { + expect(terminalTakesFocus(trigger, world({ currentTerminal: false }))).toBe(false); + expect(terminalTakesFocus(trigger, world({ spot: 'other', clicked: true, currentTerminal: false }))).toBe(false); + }); + + it.each(TRIGGERS)('never takes the focus from the preset choices of a worktree without terminals (%s)', (_name, trigger) => { + // The choices exist only without a current terminal; a clicked or keyboard-focused option keeps the focus. + for (const clicked of [false, true]) { + expect(terminalTakesFocus(trigger, world({ spot: 'other', clicked, currentTerminal: false }))).toBe(false); + } + }); + + describe('with text outside the terminals selected', () => { + const selected = world({ pageSelection: true }); + + it('keeps the selection on a click or window refocus', () => { + expect(terminalTakesFocus(CLICK, selected)).toBe(false); + expect(terminalTakesFocus(WINDOW, selected)).toBe(false); + expect(terminalTakesFocus(CLICK, world({ pageSelection: true, spot: 'other', clicked: true }))).toBe(false); + }); + + it.each<[string, Partial]>([ + ['Ctrl+C', { key: 'c', ctrlKey: true }], + ['Meta+C', { key: 'c', metaKey: true }], + ['Ctrl alone', { key: 'Control', ctrlKey: true }], + ['Meta alone', { key: 'Meta', metaKey: true }], + ['Ctrl+Shift+X', { key: 'X', ctrlKey: true }], + ])('keeps %s with the page', (_name, fields) => { + expect(terminalTakesFocus({ t: 'key', key: key(fields) }, selected)).toBe(false); + }); + + it.each(['x', 'A', 'Enter', 'ArrowUp', 'Backspace', 'Shift', 'Alt'])('gives %j to the terminal', (name) => { + expect(terminalTakesFocus({ t: 'key', key: key({ key: name }) }, selected)).toBe(true); + }); + }); + + it.each<[string, Partial]>([ + ['a lower-case letter', { key: 'a' }], + ['an upper-case letter', { key: 'A' }], + ['Enter', { key: 'Enter' }], + ['an arrow', { key: 'ArrowUp' }], + ['Backspace', { key: 'Backspace' }], + ['Escape', { key: 'Escape' }], + ['Tab', { key: 'Tab' }], + ['Space', { key: ' ' }], + ['Ctrl+C', { key: 'c', ctrlKey: true }], + ['Meta+K', { key: 'k', metaKey: true }], + ])('gives %s to the terminal without a page selection', (_name, fields) => { + expect(terminalTakesFocus({ t: 'key', key: key(fields) }, world())).toBe(true); + expect(terminalTakesFocus({ t: 'key', key: key(fields) }, world({ spot: 'other', clicked: true }))).toBe(true); + }); + + it.each<[string, Partial]>([ + ['a key being composed', { key: 'a', isComposing: true }], + ['a Process key', { key: 'Process' }], + ['a dead key', { key: 'Dead' }], + ])('never claims for %s', (_name, fields) => { + expect(terminalTakesFocus({ t: 'key', key: key(fields) }, world())).toBe(false); + expect(terminalTakesFocus({ t: 'key', key: key(fields) }, world({ spot: 'other', clicked: true }))).toBe(false); + }); + + it('follows the rule over every combination', () => { + const spots: readonly FocusSpot[] = ['none', 'terminal', 'menu', 'textField', 'other']; + const bools = [false, true] as const; + const keys: ClaimKey[] = [ + key(), + key({ key: 'c', ctrlKey: true }), + key({ key: 'c', metaKey: true }), + key({ isComposing: true }), + key({ key: 'Process' }), + key({ key: 'Dead' }), + ]; + const triggers: ClaimTrigger[] = [CLICK, WINDOW, ...keys.map((k): ClaimTrigger => ({ t: 'key', key: k }))]; + for (const trigger of triggers) { + for (const spot of spots) { + for (const clicked of bools) { + for (const modal of bools) { + for (const menuOpen of bools) { + for (const currentTerminal of bools) { + for (const pageSelection of bools) { + const w: FocusWorld = { spot, clicked, modal, menuOpen, currentTerminal, pageSelection }; + const nothingHolds = !modal && !menuOpen && (spot === 'none' || (spot === 'other' && clicked)); + let expected = nothingHolds && currentTerminal; + if (trigger.t === 'key') { + const k = trigger.key; + const composing = k.isComposing || k.key === 'Process' || k.key === 'Dead'; + expected &&= !composing && !(pageSelection && (k.ctrlKey || k.metaKey)); + } else expected &&= !pageSelection; + expect(terminalTakesFocus(trigger, w), JSON.stringify({ trigger, w })).toBe(expected); + } + } + } + } + } + } + } + }); +}); + +describe('FocusOrigin', () => { + const a = { id: 'a' }; + const b = { id: 'b' }; + + it('marks the element focused during a pointer interaction as clicked', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.focused(a); + expect(origin.clicked(a)).toBe(true); + origin.pointerSettled(); + expect(origin.clicked(a)).toBe(true); + }); + + it('marks the last element focused during the interaction, as when a click handler moves the focus', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.focused(a); + origin.focused(b); + origin.pointerSettled(); + expect(origin.clicked(b)).toBe(true); + expect(origin.clicked(a)).toBe(false); + }); + + it('does not mark an element focused from the keyboard or by a script', () => { + const origin = new FocusOrigin(); + origin.focused(a); + expect(origin.clicked(a)).toBe(false); + }); + + it('does not mark an element focused after the interaction settled', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.pointerSettled(); + origin.focused(a); + expect(origin.clicked(a)).toBe(false); + }); + + it('forgets a click once a later focus from the keyboard or a script lands, even on the clicked element', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.focused(a); + origin.pointerSettled(); + origin.focused(b); + expect(origin.clicked(b)).toBe(false); + expect(origin.clicked(a)).toBe(false); + origin.focused(a); + expect(origin.clicked(a)).toBe(false); + }); + + it('keeps a click until the focus moves', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.focused(a); + origin.pointerSettled(); + origin.pointerDown(); + origin.pointerSettled(); + expect(origin.clicked(a)).toBe(true); + }); + + it('marks again on a later pointer interaction', () => { + const origin = new FocusOrigin(); + origin.focused(a); + origin.pointerDown(); + origin.focused(b); + origin.pointerSettled(); + expect(origin.clicked(b)).toBe(true); + }); + + it('reports nothing focused as not clicked', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.focused(a); + expect(origin.clicked(null)).toBe(false); + }); +}); + +describe('pageTextSelected', () => { + const facts = (fields: Partial = {}): SelectionFacts => ({ + collapsed: false, + anchorInTerminals: false, + focusInTerminals: false, + connected: true, + ...fields, + }); + + it('is false without a selection or with a collapsed one', () => { + expect(pageTextSelected(null)).toBe(false); + expect(pageTextSelected(facts({ collapsed: true }))).toBe(false); + expect(pageTextSelected(facts({ collapsed: true, anchorInTerminals: true, focusInTerminals: true }))).toBe(false); + }); + + it('is false for a selection wholly inside the terminals', () => { + expect(pageTextSelected(facts({ anchorInTerminals: true, focusInTerminals: true }))).toBe(false); + }); + + it('is true for a selection of page text', () => { + expect(pageTextSelected(facts())).toBe(true); + }); + + it('is true for a selection reaching from the page into the terminals, either way', () => { + expect(pageTextSelected(facts({ anchorInTerminals: true }))).toBe(true); + expect(pageTextSelected(facts({ focusInTerminals: true }))).toBe(true); + }); + + it('ignores a selection with an endpoint no longer in the document', () => { + expect(pageTextSelected(facts({ connected: false }))).toBe(false); + expect(pageTextSelected(facts({ connected: false, anchorInTerminals: true }))).toBe(false); + }); +}); diff --git a/src/web/ui/keymap.test.ts b/src/web/ui/keymap.test.ts index 71063fc..b1f2d39 100644 --- a/src/web/ui/keymap.test.ts +++ b/src/web/ui/keymap.test.ts @@ -22,8 +22,10 @@ const press = (code: string, modifiers: Modifiers = {}, key = code.startsWith('K const navigation: [string, Modifiers, string, Action][] = [ ['Alt+Up', ALT, 'ArrowUp', { t: 'worktree', dir: -1 }], ['Alt+Down', ALT, 'ArrowDown', { t: 'worktree', dir: 1 }], - ['Alt+Left', ALT, 'ArrowLeft', { t: 'tab', dir: -1 }], - ['Alt+Right', ALT, 'ArrowRight', { t: 'tab', dir: 1 }], + ['Alt+Left', ALT, 'ArrowLeft', { t: 'repo', dir: -1 }], + ['Alt+Right', ALT, 'ArrowRight', { t: 'repo', dir: 1 }], + ['Ctrl+Shift+Left', CTRL_SHIFT, 'ArrowLeft', { t: 'tab', dir: -1 }], + ['Ctrl+Shift+Right', CTRL_SHIFT, 'ArrowRight', { t: 'tab', dir: 1 }], ['Alt+Shift+Left', ALT_SHIFT, 'ArrowLeft', { t: 'pane', dir: 'left' }], ['Alt+Shift+Right', ALT_SHIFT, 'ArrowRight', { t: 'pane', dir: 'right' }], ['Alt+Shift+Up', ALT_SHIFT, 'ArrowUp', { t: 'pane', dir: 'up' }], @@ -72,7 +74,11 @@ describe('keymap', () => { ['Alt+Shift+Ctrl+Left', { ...ALT_SHIFT, ctrlKey: true }, 'ArrowLeft'], ['Ctrl+Up', { ctrlKey: true }, 'ArrowUp'], ['Shift+Up', { shiftKey: true }, 'ArrowUp'], - ['Ctrl+Shift+Left', CTRL_SHIFT, 'ArrowLeft'], + ['Ctrl+Shift+Up', CTRL_SHIFT, 'ArrowUp'], + ['Ctrl+Shift+Down', CTRL_SHIFT, 'ArrowDown'], + ['Ctrl+Left', { ctrlKey: true }, 'ArrowLeft'], + ['Shift+Left', { shiftKey: true }, 'ArrowLeft'], + ['Ctrl+Shift+Meta+Left', { ...CTRL_SHIFT, metaKey: true }, 'ArrowLeft'], ['Meta+Up', { metaKey: true }, 'ArrowUp'], ['Alt+Enter', ALT, 'Enter'], ])('ignores %s', (_name, modifiers, code) => { diff --git a/src/web/ui/picker.test.ts b/src/web/ui/picker.test.ts index 47f3421..2d5a400 100644 --- a/src/web/ui/picker.test.ts +++ b/src/web/ui/picker.test.ts @@ -1,18 +1,6 @@ import { describe, expect, it } from 'vitest'; import type { Layout } from '../../protocol/index.js'; -import { - choicesTakeFocus, - dropPosition, - focusSpot, - pickerKey, - pickerValid, - presetFromForm, - type ChoicesTrigger, - type FocusedElement, - type FocusSpot, - type PickerContext, - type PickerWorld, -} from './picker.js'; +import { dropPosition, pickerKey, pickerValid, presetFromForm, type PickerContext, type PickerWorld } from './picker.js'; type Pane = Layout['tabs'][number]['root']; @@ -132,82 +120,6 @@ describe('pickerKey', () => { }); }); -describe('focusSpot', () => { - const element = (fields: Partial = {}): FocusedElement => ({ - tag: 'div', - type: '', - editable: false, - terminal: false, - menu: false, - ...fields, - }); - - it('is none without a focused element or on the page body', () => { - expect(focusSpot(null)).toBe('none'); - expect(focusSpot(element({ tag: 'body' }))).toBe('none'); - }); - - it.each(['text', 'search', 'email', 'url', 'tel', 'password', 'number'])('is a text field for an input of type %j', (type) => { - expect(focusSpot(element({ tag: 'input', type }))).toBe('textField'); - }); - - it('is a text field for a textarea and inside an editable element', () => { - expect(focusSpot(element({ tag: 'textarea' }))).toBe('textField'); - expect(focusSpot(element({ tag: 'div', editable: true }))).toBe('textField'); - expect(focusSpot(element({ tag: 'span', editable: true }))).toBe('textField'); - }); - - it.each(['checkbox', 'radio', 'button', 'submit', 'range', 'color', 'file'])('is other for an input of type %j', (type) => { - expect(focusSpot(element({ tag: 'input', type }))).toBe('other'); - }); - - it('is other for buttons, options and plain elements', () => { - expect(focusSpot(element({ tag: 'button' }))).toBe('other'); - expect(focusSpot(element({ tag: 'div' }))).toBe('other'); - expect(focusSpot(element({ tag: 'dialog' }))).toBe('other'); - }); - - it('is a menu on a control whose menu is open or inside an open menu, even a text field', () => { - expect(focusSpot(element({ tag: 'button', menu: true }))).toBe('menu'); - expect(focusSpot(element({ tag: 'input', type: 'text', menu: true }))).toBe('menu'); - }); - - it('is a terminal for an element the terminal manager owns, even a textarea', () => { - expect(focusSpot(element({ tag: 'textarea', terminal: true }))).toBe('terminal'); - expect(focusSpot(element({ tag: 'div', terminal: true }))).toBe('terminal'); - expect(focusSpot(element({ tag: 'div', editable: true, terminal: true }))).toBe('terminal'); - expect(focusSpot(element({ tag: 'div', terminal: true, menu: true }))).toBe('terminal'); - }); -}); - -describe('choicesTakeFocus', () => { - const spots: readonly FocusSpot[] = ['none', 'terminal', 'other', 'textField', 'menu']; - - it.each<[FocusSpot, boolean]>([ - ['none', true], - ['terminal', true], - ['other', true], - ['textField', false], - ['menu', false], - ])('when shown, takes the focus from %s: %s', (spot, takes) => { - expect(choicesTakeFocus('shown', spot, false)).toBe(takes); - }); - - it.each<[FocusSpot, boolean]>([ - ['none', true], - ['terminal', false], - ['other', false], - ['textField', false], - ['menu', false], - ])('after a picker or dialog closed, takes the focus from %s: %s', (spot, takes) => { - expect(choicesTakeFocus('modalClosed', spot, false)).toBe(takes); - }); - - it.each(['shown', 'modalClosed'])('never takes the focus while a picker or dialog is open (%s)', (trigger) => { - for (const spot of spots) expect(choicesTakeFocus(trigger, spot, true)).toBe(false); - }); -}); - describe('presetFromForm', () => { const presets = [ { name: 'shell', command: null }, diff --git a/src/web/ui/view.test.ts b/src/web/ui/view.test.ts new file mode 100644 index 0000000..38e24c2 --- /dev/null +++ b/src/web/ui/view.test.ts @@ -0,0 +1,323 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { HostEntry, Layout, Terminal, Worktree } from '../../protocol/index.js'; +import { HubClient } from '../client/index.js'; +import type { TerminalManager } from '../terminals/index.js'; +import type { PageFocus } from './focus.js'; +import { View } from './view.js'; + +/** A `KeyboardEvent` built without a DOM; `preventDefault` sets `defaultPrevented`. */ +class TestKey extends Event implements KeyboardEvent { + readonly DOM_KEY_LOCATION_STANDARD = 0; + readonly DOM_KEY_LOCATION_LEFT = 1; + readonly DOM_KEY_LOCATION_RIGHT = 2; + readonly DOM_KEY_LOCATION_NUMPAD = 3; + readonly charCode = 0; + readonly keyCode = 0; + readonly location = 0; + readonly detail = 0; + readonly view = null; + readonly which = 0; + readonly key: string; + readonly code: string; + readonly ctrlKey: boolean; + readonly shiftKey: boolean; + readonly altKey: boolean; + readonly metaKey: boolean; + readonly repeat = false; + readonly isComposing = false; + + constructor(key: string, code: string, modifiers: { ctrlKey?: boolean; shiftKey?: boolean; altKey?: boolean; metaKey?: boolean } = {}) { + super('keydown', { bubbles: true, cancelable: true }); + this.key = key; + this.code = code; + this.ctrlKey = modifiers.ctrlKey ?? false; + this.shiftKey = modifiers.shiftKey ?? false; + this.altKey = modifiers.altKey ?? false; + this.metaKey = modifiers.metaKey ?? false; + } + + getModifierState(): boolean { + throw new Error('not used'); + } + + initKeyboardEvent(): void { + throw new Error('not used'); + } + + initUIEvent(): void { + throw new Error('not used'); + } +} + +type Manager = Pick; + +/** Records what the view asks of the terminals; View takes any object with the manager methods it calls. */ +class FakeTerminals implements Manager { + readonly opened = new Set(); + focused: [number, number][] = []; + forwarded: [number, number, KeyboardEvent][] = []; + + has(host: number, termId: number): boolean { + return this.opened.has(`${String(host)}:${String(termId)}`); + } + + open(host: number, termId: number): void { + this.opened.add(`${String(host)}:${String(termId)}`); + } + + focus(host: number, termId: number): void { + this.focused.push([host, termId]); + } + + forwardKey(host: number, termId: number, event: KeyboardEvent): void { + this.forwarded.push([host, termId, event]); + } + + show(): void { + // Nothing to show without a DOM. + } + + sizeFor(): { cols: number; rows: number } { + return { cols: 80, rows: 24 }; + } + + selection(): string { + return ''; + } + + paste(): void { + throw new Error('not used'); + } + + onFocus(): void { + // The view's focus listener is not exercised here. + } + + clear(): void { + this.focused = []; + this.forwarded = []; + } +} + +class MemoryStorage implements Pick { + private readonly items = new Map(); + + getItem(key: string): string | null { + return this.items.get(key) ?? null; + } + + setItem(key: string, value: string): void { + this.items.set(key, value); + } + + removeItem(key: string): void { + this.items.delete(key); + } +} + +const worktree = (path: string, main: boolean): Worktree => ({ + path, + head: null, + branch: 'b', + detached: false, + locked: false, + prunable: false, + bare: false, + main, +}); + +const terminal = (termId: number, path: string): Terminal => ({ + termId, + worktree: path, + preset: 'shell', + cols: 80, + rows: 24, + exit: null, + unseen: false, + state: 'idle', +}); + +const host = (idx: number, repos: readonly string[]): HostEntry => ({ + idx, + name: idx === 0 ? 'local' : `h${String(idx)}`, + remote: idx !== 0, + status: 'connected', + reason: null, + daemonVersion: null, + instance: null, + login: null, + repos: [...repos], +}); + +/** Reports `repo` with only its main worktree, holding `terms` as one tab split right (none for no terminals). */ +const report = (client: HubClient, hostIdx: number, repo: string, terms: readonly number[]): void => { + const [first, second] = terms; + const root = + second === undefined ? { term: first ?? 0 } : { split: 'right' as const, ratio: 0.5, a: { term: first ?? 0 }, b: { term: second } }; + const layout: Layout = { tabs: [{ id: 't1', root }], active: 0 }; + client.store.apply(hostIdx, { + t: 'repoState', + repo, + worktrees: [worktree(repo, true)], + terminals: terms.map((id) => terminal(id, repo)), + checked: [], + layouts: terms.length === 0 ? [] : [{ worktree: repo, layout }], + }); +}; + +const NOTHING_HOLDS: PageFocus = { spot: 'none', clicked: false, menuOpen: false, pageSelection: false }; + +describe('View', () => { + let client: HubClient; + let manager: FakeTerminals; + let view: View; + + beforeEach(() => { + vi.stubGlobal('localStorage', new MemoryStorage()); + client = new HubClient('test'); + manager = new FakeTerminals(); + view = new View(client, manager); + client.store.status.value = 'open'; + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + describe('claiming the keyboard focus', () => { + beforeEach(() => { + client.store.hosts.value = [host(0, ['/r/app', '/r/empty'])]; + report(client, 0, '/r/app', [1, 2]); + report(client, 0, '/r/empty', []); + view.focusPane(2); + manager.clear(); + }); + + it.each(['click', 'windowFocus'] as const)('focuses the focused pane on a %s while nothing holds the keyboard', (trigger) => { + view.claimFocus(trigger, NOTHING_HOLDS); + expect(manager.focused).toEqual([[0, 2]]); + expect(manager.forwarded).toEqual([]); + }); + + it.each(['click', 'windowFocus'] as const)('focuses it on a %s from a control the user clicked', (trigger) => { + view.claimFocus(trigger, { ...NOTHING_HOLDS, spot: 'other', clicked: true }); + expect(manager.focused).toEqual([[0, 2]]); + }); + + it.each<[string, PageFocus]>([ + ['a control focused from the keyboard', { ...NOTHING_HOLDS, spot: 'other' }], + ['a text field', { ...NOTHING_HOLDS, spot: 'textField', clicked: true }], + ['a terminal', { ...NOTHING_HOLDS, spot: 'terminal' }], + ['an open menu', { ...NOTHING_HOLDS, menuOpen: true }], + ['selected page text', { ...NOTHING_HOLDS, pageSelection: true }], + ])('leaves the focus with %s', (_name, page) => { + view.claimFocus('click', page); + view.claimFocus('windowFocus', page); + view.claimKey(new TestKey('c', 'KeyC', { ctrlKey: true }), page); + expect(manager.focused).toEqual([]); + expect(manager.forwarded).toEqual([]); + }); + + it('leaves the focus while a picker or dialog is open', () => { + view.openWorktreeMenu('/r/app', 10, 10); + manager.clear(); + view.claimFocus('click', NOTHING_HOLDS); + view.claimFocus('windowFocus', NOTHING_HOLDS); + view.claimKey(new TestKey('a', 'KeyA'), NOTHING_HOLDS); + expect(manager.focused).toEqual([]); + expect(manager.forwarded).toEqual([]); + }); + + it('does nothing without a current terminal', () => { + view.selectRepo({ host: 0, repo: '/r/empty', label: 'empty' }); + manager.clear(); + view.claimFocus('click', NOTHING_HOLDS); + view.claimFocus('windowFocus', NOTHING_HOLDS); + view.claimKey(new TestKey('a', 'KeyA'), NOTHING_HOLDS); + expect(manager.focused).toEqual([]); + expect(manager.forwarded).toEqual([]); + }); + + it('forwards a key pressed while nothing holds the keyboard to the focused pane only', () => { + const event = new TestKey('a', 'KeyA'); + view.claimKey(event, NOTHING_HOLDS); + expect(manager.forwarded).toEqual([[0, 2, event]]); + }); + + it('forwards a key pressed on a control the user clicked', () => { + const event = new TestKey('Enter', 'Enter'); + view.claimKey(event, { ...NOTHING_HOLDS, spot: 'other', clicked: true }); + expect(manager.forwarded).toEqual([[0, 2, event]]); + }); + + it('forwards a plain key while page text is selected, but not a Ctrl key', () => { + const selected = { ...NOTHING_HOLDS, pageSelection: true }; + view.claimKey(new TestKey('c', 'KeyC', { ctrlKey: true }), selected); + expect(manager.forwarded).toEqual([]); + const event = new TestKey('x', 'KeyX'); + view.claimKey(event, selected); + expect(manager.forwarded).toEqual([[0, 2, event]]); + }); + + it('never forwards a key whose default was prevented', () => { + const event = new TestKey('Enter', 'Enter'); + event.preventDefault(); + view.claimKey(event, NOTHING_HOLDS); + expect(manager.forwarded).toEqual([]); + expect(manager.focused).toEqual([]); + }); + + it('never forwards a shortcut the view handled', () => { + const event = new TestKey('ArrowDown', 'ArrowDown', { altKey: true }); + expect(view.handleKey(event, false)).toBe(true); + view.claimKey(event, NOTHING_HOLDS); + expect(manager.forwarded).toEqual([]); + }); + }); + + describe('repo tab navigation', () => { + beforeEach(() => { + client.store.hosts.value = [host(0, ['/r/a', '/r/b']), host(1, ['/r/c'])]; + report(client, 0, '/r/a', [1]); + report(client, 0, '/r/b', [2]); + report(client, 1, '/r/c', [3]); + manager.clear(); + }); + + const shown = (): string | undefined => view.tab.value?.repo; + const press = (code: 'ArrowLeft' | 'ArrowRight'): boolean => view.handleKey(new TestKey(code, code, { altKey: true }), false); + + it('steps through the repo tabs in their shown order across hosts, stopping at either end', () => { + expect(shown()).toBe('/r/a'); + expect(press('ArrowRight')).toBe(true); + expect(shown()).toBe('/r/b'); + press('ArrowRight'); + expect(shown()).toBe('/r/c'); + press('ArrowRight'); + expect(shown()).toBe('/r/c'); + press('ArrowLeft'); + expect(shown()).toBe('/r/b'); + press('ArrowLeft'); + press('ArrowLeft'); + expect(shown()).toBe('/r/a'); + }); + + it('focuses the current terminal of the repo it steps to', () => { + press('ArrowRight'); + expect(manager.focused.at(-1)).toEqual([0, 2]); + press('ArrowRight'); + expect(manager.focused.at(-1)).toEqual([1, 3]); + }); + + it('does nothing while a picker or dialog is open', () => { + view.openWorktreeMenu('/r/a', 10, 10); + press('ArrowRight'); + expect(shown()).toBe('/r/a'); + }); + + it('chooses terminal tabs with Ctrl+Shift+arrows instead', () => { + expect(view.handleKey(new TestKey('ArrowRight', 'ArrowRight', { ctrlKey: true, shiftKey: true }), false)).toBe(true); + expect(shown()).toBe('/r/a'); + }); + }); +}); diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index 0c3033b..ff20953 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -326,6 +326,21 @@ export const ready = async (page: Page, termId: number, host = LOCAL): Promise => + page.evaluate((selector) => { + const box = document.activeElement?.closest(selector); + return box instanceof HTMLElement ? Number(box.dataset['term']) : null; + }, byTestId(TID.terminal)); + +/** Moves the keyboard focus to the page body. */ +export const focusBody = async (page: Page): Promise => { + await page.evaluate(() => { + if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); + }); + expect(await page.evaluate(() => document.activeElement === document.body)).toBe(true); +}; + /** The terminal's `.xterm` element. */ export const xtermOf = (page: Page, termId: number, host = LOCAL): Promise> => { return page.locator(terminalBox(host, termId)).locator('.xterm').elementHandle(); diff --git a/test/e2e/focus.spec.ts b/test/e2e/focus.spec.ts new file mode 100644 index 0000000..5879a0c --- /dev/null +++ b/test/e2e/focus.spec.ts @@ -0,0 +1,373 @@ +import type { Page } from '@playwright/test'; +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { HubHost } from '../support/hub-host.js'; +import { byTestId, repoTab, terminalBox, termTab, TID, worktreeEntry } from './contract.js'; +import { + createShells, + expect, + focusBody, + focusedTerminal, + LOCAL, + makeRepoWith, + newTerminal, + openUi, + ready, + screenOf, + selectRepo, + selectWorktree, + test, + typeLine, + waitScreen, + watcher, + writeHubConfig, +} from './fixture.js'; +import { balanced, createTerms, storeTabs } from './panes.js'; + +const KEYS_READY = 'KEYS-READY'; + +/** Puts the terminal in raw mode and prints each input chunk it receives as `[]`. */ +const KEY_ECHO = `process.stdin.setRawMode(true); +process.stdout.write('KEYS' + '-READY\\n'); +process.stdin.on('data', (d) => process.stdout.write('[' + d.toString('hex') + ']')); +`; + +/** Starts the key echo in the terminal, clicking it first. */ +const startKeyEcho = async (hub: HubHost, page: Page, termId: number): Promise => { + const script = join(hub.dir, 'key-echo.cjs'); + writeFileSync(script, KEY_ECHO); + await typeLine(page, termId, `'${process.execPath}' '${script}'`); + await waitScreen(page, termId, KEYS_READY); +}; + +/** The input the key echo of the terminal received, as `[]` chunks. */ +const received = async (page: Page, termId: number): Promise => { + const screen = (await screenOf(page, termId)) ?? ''; + return screen.slice(screen.lastIndexOf(KEYS_READY) + KEYS_READY.length).replaceAll(/\s/g, ''); +}; + +/** Checks that the key echo of the terminal received nothing, after a pause for stray input. */ +const receivedNothing = async (page: Page, termId: number): Promise => { + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + expect(await received(page, termId)).toBe(''); +}; + +/** Types `echo ` and Enter where the keyboard focus is, and waits for the terminal to print the marker. */ +const echoReaches = async (page: Page, termId: number, marker: string): Promise => { + const [head = '', tail = ''] = marker.split('-'); + await page.keyboard.type(`echo ${head}''-${tail}`); + await page.keyboard.press('Enter'); + await waitScreen(page, termId, marker); + expect(await focusedTerminal(page)).toBe(termId); +}; + +/** One repo with one shell tab, ready for input. */ +const oneShell = async (hub: HubHost, page: Page): Promise<{ repo: string; term: number }> => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const term = await newTerminal(page); + await ready(page, term); + return { repo, term }; +}; + +/** Lets the page see the window lose the focus and regain it. */ +const switchWindowAway = (page: Page): Promise => + page.evaluate(() => { + window.dispatchEvent(new Event('blur')); + window.dispatchEvent(new Event('focus')); + }); + +test.describe('typing after a click reaches the current terminal', () => { + test('clicking another worktree’s row focuses its terminal at once', async ({ hub, page }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['b']); + const [b = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + const [[mainTerm = 0] = [], [bTerm = 0] = []] = await createShells(await watcher(hub, repo), [repo, b]); + await selectWorktree(page, repo); + await page.locator(terminalBox(LOCAL, mainTerm)).click(); + await expect.poll(() => focusedTerminal(page)).toBe(mainTerm); + + await page.locator(worktreeEntry(b)).click(); + await expect(page.locator(worktreeEntry(b))).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => focusedTerminal(page)).toBe(bTerm); + await echoReaches(page, bTerm, 'ROW-B'); + }); + + test('clicking another repo tab gives its terminal the typed text', async ({ hub, page }) => { + const { repo: app } = makeRepoWith(hub, 'app', []); + const { repo: lib } = makeRepoWith(hub, 'lib', []); + hub.writeRepos([app, lib]); + await openUi(hub, page); + const [[appTerm = 0] = []] = await createShells(await watcher(hub, app), [app]); + const [[libTerm = 0] = []] = await createShells(await watcher(hub, lib), [lib]); + await selectRepo(page, app); + await page.locator(terminalBox(LOCAL, appTerm)).click(); + + await page.locator(repoTab(lib)).click(); + await expect(page.locator(repoTab(lib))).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => focusedTerminal(page)).toBe(libTerm); + await echoReaches(page, libTerm, 'REPO-LIB'); + }); + + test('clicking the selected worktree’s row', async ({ hub, page }) => { + const { repo, term } = await oneShell(hub, page); + await page.locator(worktreeEntry(repo)).click(); + await expect.poll(() => focusedTerminal(page)).toBe(term); + await echoReaches(page, term, 'ROW-SAME'); + }); + + test('clicking the active terminal tab', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + await page.locator(termTab(term)).click(); + await expect.poll(() => focusedTerminal(page)).toBe(term); + await echoReaches(page, term, 'TAB-SAME'); + }); + + test('clicking an empty part of the tab bar', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + const newTab = await page.locator(byTestId(TID.newTab)).boundingBox(); + const splitRight = await page.locator(byTestId(TID.splitRight)).boundingBox(); + if (newTab === null || splitRight === null) throw new Error('the tab bar controls are not shown'); + expect(splitRight.x - (newTab.x + newTab.width)).toBeGreaterThan(40); + await page.mouse.click((newTab.x + newTab.width + splitRight.x) / 2, newTab.y + newTab.height / 2); + await expect.poll(() => focusedTerminal(page)).toBe(term); + await echoReaches(page, term, 'BAR-EMPTY'); + }); + + test('clicking a disabled split control', async ({ hub, page }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const client = await watcher(hub, repo); + const terms = await createTerms(client, repo, 8); + await storeTabs(client, repo, [balanced(terms)]); + const target = terms[3] ?? 0; + await expect(page.locator(terminalBox(LOCAL, target))).toBeVisible(); + await page.locator(terminalBox(LOCAL, target)).click(); + const control = page.locator(byTestId(TID.splitRight)); + await expect(control).toBeDisabled(); + await focusBody(page); + + const box = await control.boundingBox(); + if (box === null) throw new Error('the split control is not shown'); + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await echoReaches(page, target, 'DISABLED-OK'); + }); + + test('dragging the sidebar edge', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + const resizer = page.locator(byTestId(TID.sidebarResizer)); + const box = await resizer.boundingBox(); + if (box === null) throw new Error('the sidebar resizer is not shown'); + const before = await resizer.getAttribute('aria-valuenow'); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + 80, box.y + box.height / 2, { steps: 5 }); + await page.mouse.up(); + await expect(resizer).not.toHaveAttribute('aria-valuenow', before ?? ''); + await echoReaches(page, term, 'DRAG-OK'); + }); + + test('closing an exited tab with its close control', async ({ hub, page }) => { + const { term: first } = await oneShell(hub, page); + const second = await newTerminal(page); + await ready(page, second); + // A failed exit keeps the tab, marked exited; a clean one closes it. + await typeLine(page, second, 'exit 1'); + await expect(page.locator(termTab(second))).toContainText('exited'); + + await page.locator(termTab(second)).locator(byTestId(TID.termTabClose)).click(); + await expect(page.locator(termTab(second))).toHaveCount(0); + await expect(page.locator(byTestId(TID.closeDialog))).toHaveCount(0); + await expect.poll(() => focusedTerminal(page)).toBe(first); + await echoReaches(page, first, 'CLOSED-OK'); + }); +}); + +test.describe('keys pressed while nothing holds the keyboard', () => { + test('the first key reaches the terminal exactly once, for every kind of key', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + await startKeyEcho(hub, page, term); + + let expected = ''; + for (const [key, hex] of [ + ['KeyA', '61'], + ['Shift+KeyA', '41'], + ['ArrowUp', '1b5b41'], + ['Backspace', '7f'], + ['Enter', '0d'], + ['Control+KeyC', '03'], + ] as const) { + await focusBody(page); + await page.keyboard.press(key); + expected += `[${hex}]`; + await expect.poll(() => received(page, term), { message: key }).toBe(expected); + expect(await focusedTerminal(page)).toBe(term); + } + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: a duplicate would arrive late + expect(await received(page, term)).toBe(expected); + }); + + test('a shortcut acts and reaches no program', async ({ hub, page }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['b']); + const [b = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + const [[mainTerm = 0] = [], [bTerm = 0] = []] = await createShells(await watcher(hub, repo), [repo, b]); + await selectWorktree(page, b); + await startKeyEcho(hub, page, bTerm); + await selectWorktree(page, repo); + await startKeyEcho(hub, page, mainTerm); + const listed = await page.locator(byTestId(TID.worktree)).evaluateAll((all) => all.map((e) => e.getAttribute('data-path'))); + expect(listed).toEqual([repo, b]); + + await focusBody(page); + await page.keyboard.press('Alt+ArrowDown'); + await expect(page.locator(worktreeEntry(b))).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => focusedTerminal(page)).toBe(bTerm); + await receivedNothing(page, mainTerm); + expect(await received(page, bTerm)).toBe(''); + }); +}); + +test.describe('the window regaining the focus', () => { + test('gives the current terminal the focus when nothing held it', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + await focusBody(page); + await switchWindowAway(page); + await expect.poll(() => focusedTerminal(page)).toBe(term); + await echoReaches(page, term, 'WINDOW-OK'); + }); + + test('leaves a control focused by the page', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + const tab = page.locator(termTab(term)); + await tab.focus(); + await switchWindowAway(page); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(tab).toBeFocused(); + expect(await focusedTerminal(page)).toBeNull(); + }); +}); + +test.describe('fields, menus and focused controls keep their keys', () => { + test('the worktree search', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + await startKeyEcho(hub, page, term); + const search = page.locator(byTestId(TID.worktreeSearch)); + await search.click(); + await page.keyboard.type('zqx'); + await expect(search).toHaveValue('zqx'); + await expect(search).toBeFocused(); + await receivedNothing(page, term); + }); + + test('the add form of the preset picker', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + await startKeyEcho(hub, page, term); + await page.locator(byTestId(TID.newTab)).click(); + const picker = page.locator(byTestId(TID.presetPicker)); + await picker.locator(byTestId(TID.presetAdd)).click(); + const name = picker.locator(byTestId(TID.presetName)); + await expect(name).toBeFocused(); + await page.keyboard.type('nm'); + await expect(name).toHaveValue('nm'); + await receivedNothing(page, term); + }); + + test('the rename field of a terminal tab', async ({ hub, page }) => { + const { term } = await oneShell(hub, page); + await startKeyEcho(hub, page, term); + const tab = page.locator(termTab(term)); + const box = await tab.boundingBox(); + if (box === null) throw new Error('the tab is not shown'); + await tab.dblclick({ position: { x: 8, y: box.height / 2 } }); + const field = tab.locator(byTestId(TID.termTabName)); + await expect(field).toBeFocused(); + expect( + await field.evaluate( + (el) => el instanceof HTMLInputElement && el.value !== '' && el.selectionStart === 0 && el.selectionEnd === el.value.length, + ), + ).toBe(true); + await page.keyboard.type('zz'); + await expect(field).toHaveValue('zz'); + await expect(field).toBeFocused(); + await receivedNothing(page, term); + }); + + test('the open Hubs menu', async ({ hub, page, ssh }) => { + ssh.failHost('box', 'ssh: Could not resolve hostname box: Name or service not known'); + const { repo } = makeRepoWith(hub, 'app', []); + writeHubConfig(hub, { repos: [repo], hosts: [{ name: 'box', ssh: 'box' }] }); + await openUi(hub, page); + const term = await newTerminal(page); + await ready(page, term); + await startKeyEcho(hub, page, term); + + await page.locator(byTestId(TID.hubsMenu)).click(); + const list = page.locator(byTestId(TID.hubsList)); + await expect(list).toBeVisible(); + await page.keyboard.press('KeyQ'); + await receivedNothing(page, term); + await expect(list).toBeVisible(); + }); + + test('a terminal tab focused from the keyboard takes Enter', async ({ hub, page }) => { + const { term: first } = await oneShell(hub, page); + const second = await newTerminal(page); + await ready(page, second); + await startKeyEcho(hub, page, second); + + await page.locator(termTab(first)).focus(); + await page.keyboard.press('Enter'); + await expect(page.locator(termTab(first))).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => focusedTerminal(page)).toBe(first); + await receivedNothing(page, second); + }); + + test('selected page text: Ctrl+C copies it, a plain key reaches the terminal', async ({ hub, page, context }) => { + await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: hub.origin }); + const { repo, term } = await oneShell(hub, page); + await startKeyEcho(hub, page, term); + + // From just right of the checkbox to the end of the label: a pointer selection of the worktree's name. + const checkbox = await page.locator(`${worktreeEntry(repo)} input[type="checkbox"]`).boundingBox(); + const label = await page.locator(worktreeEntry(repo)).locator(byTestId(TID.worktreeLabel)).boundingBox(); + if (checkbox === null || label === null) throw new Error('the worktree entry is not shown'); + const y = label.y + label.height / 2; + await page.mouse.move(checkbox.x + checkbox.width + 3, y); + await page.mouse.down(); + await page.mouse.move(label.x + label.width - 2, y, { steps: 8 }); + await page.mouse.up(); + const selected = await page.evaluate(() => getSelection()?.toString() ?? ''); + expect(selected).not.toBe(''); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: a claim after the click would clear the selection + expect(await page.evaluate(() => getSelection()?.toString() ?? '')).toBe(selected); + + await page.keyboard.press('Control+KeyC'); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(selected); + await receivedNothing(page, term); + await page.keyboard.press('KeyX'); + await expect.poll(() => received(page, term)).toBe('[78]'); + }); + + test('without a current terminal, a click in the terminal area focuses no terminal', async ({ hub, page }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['empty']); + const [empty = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + const [[term = 0] = []] = await createShells(await watcher(hub, repo), [repo]); + await selectWorktree(page, repo); + await page.locator(terminalBox(LOCAL, term)).click(); + await expect.poll(() => focusedTerminal(page)).toBe(term); + + await selectWorktree(page, empty); + const choices = await page.locator(byTestId(TID.presetChoices)).boundingBox(); + if (choices === null) throw new Error('the preset choices are not shown'); + await page.mouse.click(choices.x + choices.width / 2, choices.y + choices.height + 60); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + expect(await focusedTerminal(page)).toBeNull(); + }); +}); diff --git a/test/e2e/keyboard.spec.ts b/test/e2e/keyboard.spec.ts index 5465d30..507c1b3 100644 --- a/test/e2e/keyboard.spec.ts +++ b/test/e2e/keyboard.spec.ts @@ -1,9 +1,11 @@ import type { Page } from '@playwright/test'; -import { byTestId, terminalBox, termTab, TID, worktreeEntry } from './contract.js'; +import { byTestId, repoTab, terminalBox, termTab, TID, worktreeEntry } from './contract.js'; import { activeTerm, + createShells, expect, focusedPane, + focusedTerminal, listedWorktrees, LOCAL, makeRepoWith, @@ -12,6 +14,7 @@ import { PRESETS, ready, screenOf, + selectRepo, selectWorktree, splitPane, test, @@ -82,21 +85,73 @@ test.describe('worktree navigation', () => { }); }); +test.describe('navigation and the keyboard focus', () => { + test('Alt+Down onto a worktree with a terminal leaves the keyboard in its terminal', async ({ hub, page }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['b']); + const [b = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + const [[mainTerm = 0] = [], [bTerm = 0] = []] = await createShells(await watcher(hub, repo), [repo, b]); + expect(await listedWorktrees(page)).toEqual([repo, b]); + await selectWorktree(page, repo); + await page.locator(terminalBox(LOCAL, mainTerm)).click(); + await expect.poll(() => focusedTerminal(page)).toBe(mainTerm); + + await page.keyboard.press('Alt+ArrowDown'); + await selected(page, b); + await expect.poll(() => focusedTerminal(page)).toBe(bTerm); + await page.keyboard.type("echo NAV''-B"); + await page.keyboard.press('Enter'); + await waitScreen(page, bTerm, 'NAV-B'); + }); +}); + +test.describe('repo navigation', () => { + test('Alt+Right twice from the first of three repo tabs selects the third and focuses its terminal, and stops there', async ({ + hub, + page, + }) => { + const repos = ['app', 'lib', 'tool'].map((name) => makeRepoWith(hub, name, []).repo); + const [app = '', lib = '', tool = ''] = repos; + hub.writeRepos(repos); + await openUi(hub, page); + const terms: number[] = []; + for (const repo of repos) { + const [[term = 0] = []] = await createShells(await watcher(hub, repo), [repo]); // NOSONAR(S9382) — sequential setup + terms.push(term); + } + const [appTerm = 0, , toolTerm = 0] = terms; + await selectRepo(page, app); + await page.locator(terminalBox(LOCAL, appTerm)).click(); + + await page.keyboard.press('Alt+ArrowRight'); + await page.keyboard.press('Alt+ArrowRight'); + await expect(page.locator(repoTab(tool))).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => focusedTerminal(page)).toBe(toolTerm); + await page.keyboard.press('Alt+ArrowRight'); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(page.locator(repoTab(tool))).toHaveAttribute('aria-selected', 'true'); + expect(await focusedTerminal(page)).toBe(toolTerm); + await page.keyboard.press('Alt+ArrowLeft'); + await expect(page.locator(repoTab(lib))).toHaveAttribute('aria-selected', 'true'); + }); +}); + test.describe('tab and pane navigation', () => { - test('Alt+Right twice from the first of three tabs shows the third, and stops there', async ({ hub, page }) => { + test('Ctrl+Shift+Right twice from the first of three tabs shows the third, and stops there', async ({ hub, page }) => { const { repo } = makeRepoWith(hub, 'app', []); hub.writeRepos([repo]); await openUi(hub, page); const [, second = 0, third = 0] = await threeTabs(page); - await page.keyboard.press('Alt+ArrowRight'); - await page.keyboard.press('Alt+ArrowRight'); + await page.keyboard.press('Control+Shift+ArrowRight'); + await page.keyboard.press('Control+Shift+ArrowRight'); await expect(page.locator(termTab(third))).toHaveAttribute('aria-selected', 'true'); await expect(page.locator(terminalBox(LOCAL, third))).toBeVisible(); - await page.keyboard.press('Alt+ArrowRight'); + await page.keyboard.press('Control+Shift+ArrowRight'); await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on expect(await activeTerm(page)).toBe(third); - await page.keyboard.press('Alt+ArrowLeft'); + await page.keyboard.press('Control+Shift+ArrowLeft'); await expect(page.locator(termTab(second))).toHaveAttribute('aria-selected', 'true'); }); @@ -138,7 +193,7 @@ test.describe('tab and pane navigation', () => { const first = await newTerminal(page); const second = await newTerminal(page); await page.locator(byTestId(TID.filterChecked)).focus(); - await page.keyboard.press('Alt+ArrowLeft'); + await page.keyboard.press('Control+Shift+ArrowLeft'); await expect(page.locator(termTab(first))).toHaveAttribute('aria-selected', 'true'); await page.locator(byTestId(TID.filterChecked)).focus(); await page.keyboard.press('Control+Shift+KeyT'); @@ -165,12 +220,14 @@ test.describe('shortcuts and the terminal program', () => { await waitScreen(page, term, 'PRESET-CAT'); await page.locator(terminalBox(LOCAL, term)).click(); - // Each does nothing here: one worktree, one tab, one pane, no selection. + // Each does nothing here: one repo, one worktree, one tab, one pane, no selection. for (const key of [ 'Alt+ArrowUp', 'Alt+ArrowDown', 'Alt+ArrowLeft', 'Alt+ArrowRight', + 'Control+Shift+ArrowLeft', + 'Control+Shift+ArrowRight', 'Alt+Shift+ArrowLeft', 'Alt+Shift+ArrowRight', 'Alt+Shift+ArrowUp', @@ -273,6 +330,7 @@ test.describe('shortcuts while a picker or dialog is open', () => { await expect(picker).toBeVisible(); await page.keyboard.press('Alt+ArrowDown'); await page.keyboard.press('Alt+ArrowRight'); + await page.keyboard.press('Control+Shift+ArrowRight'); await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on await selected(page, worktree); expect(await activeTerm(page)).toBe(first); @@ -294,6 +352,7 @@ test.describe('shortcuts while a picker or dialog is open', () => { const mark = wire.markSent(); await page.keyboard.press('Alt+ArrowDown'); await page.keyboard.press('Alt+ArrowRight'); + await page.keyboard.press('Control+Shift+ArrowRight'); await page.keyboard.press('Control+Shift+KeyT'); await page.waitForTimeout(500); // NOSONAR(S2925) — absence check: nothing to synchronise on await selected(page, worktree); @@ -313,12 +372,14 @@ test.describe('held shortcuts', () => { await openUi(hub, page); const [, , third = 0] = await threeTabs(page); - await page.keyboard.down('Alt'); + await page.keyboard.down('Control'); + await page.keyboard.down('Shift'); await page.keyboard.down('ArrowRight'); // A second keydown of a held key is an auto-repeat. await page.keyboard.down('ArrowRight'); await page.keyboard.up('ArrowRight'); - await page.keyboard.up('Alt'); + await page.keyboard.up('Shift'); + await page.keyboard.up('Control'); await expect(page.locator(termTab(third))).toHaveAttribute('aria-selected', 'true'); }); diff --git a/test/e2e/splits.spec.ts b/test/e2e/splits.spec.ts index b81b91c..41db699 100644 --- a/test/e2e/splits.spec.ts +++ b/test/e2e/splits.spec.ts @@ -395,9 +395,9 @@ test.describe('dragging dividers', () => { await page.locator(terminalBox(LOCAL, left)).click(); holding = true; - await page.keyboard.press('Alt+ArrowRight'); + await page.keyboard.press('Control+Shift+ArrowRight'); await expect.poll(() => paneIds(page)).toEqual([other]); - await page.keyboard.press('Alt+ArrowLeft'); + await page.keyboard.press('Control+Shift+ArrowLeft'); await expect.poll(() => paneIds(page)).toEqual([left, right]); await startDrag(page, '', 'right', await pointFor(page, left, right, 'right', 0.3)); await expect.poll(() => shareOf(page, left, right, 'right')).toBeCloseTo(0.3, 1); From 6e3664834ccbdc7dcb9ee02da2bce9a2b48e0315 Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 13:40:35 +0100 Subject: [PATCH 3/7] Typed keys and clicks give the current terminal the focus; repo tabs on Alt+Left/Right, terminal tabs on Ctrl+Shift+Left/Right --- README.md | 19 ++-- src/web/main/index.ts | 25 ++++- src/web/terminals/manager.ts | 33 +++++++ src/web/ui/app.tsx | 19 +--- src/web/ui/focus.ts | 187 +++++++++++++++++++++++++++++++++++ src/web/ui/index.ts | 1 + src/web/ui/keymap.ts | 8 +- src/web/ui/picker.ts | 37 ------- src/web/ui/view.test.ts | 12 ++- src/web/ui/view.ts | 43 +++++++- 10 files changed, 314 insertions(+), 70 deletions(-) create mode 100644 src/web/ui/focus.ts diff --git a/README.md b/README.md index cf46552..42f5fd3 100644 --- a/README.md +++ b/README.md @@ -154,15 +154,16 @@ This machine's hub then listens on the host's `port` on `127.0.0.1` and relays e ## Keyboard -| Keys | Action | -| --------------------------- | --------------------------------------------------------- | -| Alt+Up / Alt+Down | Previous / next worktree in the sidebar, under its filter | -| Alt+Left / Alt+Right | Previous / next terminal tab | -| Alt+Shift+arrows | Focus the pane in that direction | -| Ctrl+Shift+T | New tab | -| Ctrl+Shift+D / Ctrl+Shift+E | Split the focused pane right / down | -| Ctrl+Shift+W | Close the focused pane | -| Ctrl+Shift+C / Ctrl+Shift+V | Copy the selection / paste | +| Keys | Action | +| ---------------------------------- | --------------------------------------------------------- | +| Alt+Up / Alt+Down | Previous / next worktree in the sidebar, under its filter | +| Alt+Left / Alt+Right | Previous / next repo tab | +| Ctrl+Shift+Left / Ctrl+Shift+Right | Previous / next terminal tab | +| Alt+Shift+arrows | Focus the pane in that direction | +| Ctrl+Shift+T | New tab | +| Ctrl+Shift+D / Ctrl+Shift+E | Split the focused pane right / down | +| Ctrl+Shift+W | Close the focused pane | +| Ctrl+Shift+C / Ctrl+Shift+V | Copy the selection / paste | The preset picker takes 1–9, the arrow keys and Enter, and Escape cancels it. diff --git a/src/web/main/index.ts b/src/web/main/index.ts index 20fd7b4..a64e579 100644 --- a/src/web/main/index.ts +++ b/src/web/main/index.ts @@ -1,7 +1,7 @@ import { h, render } from 'preact'; import { HubClient, pageTitle, RequestError, Restorer } from '../client/index.js'; import { TerminalManager } from '../terminals/index.js'; -import { App, View } from '../ui/index.js'; +import { App, FocusOrigin, readPageFocus, trackFocusOrigin, View } from '../ui/index.js'; /** The package version, defined at build time. */ declare const __WTD_VERSION__: string; @@ -10,10 +10,31 @@ const client = new HubClient(__WTD_VERSION__); const manager = new TerminalManager(client); const view = new View(client, manager); +const origin = new FocusOrigin(); +trackFocusOrigin(origin); + manager.setKeyFilter((event) => !view.handleKey(event, true)); document.addEventListener('keydown', (event) => { // Keys in a terminal reach the view through the terminal's key filter. - if (!manager.owns(event.target instanceof Node ? event.target : null)) view.handleKey(event, false); + if (manager.owns(event.target instanceof Node ? event.target : null)) return; + view.handleKey(event, false); + view.claimKey(event, readPageFocus(manager, origin)); +}); + +// A click claims once its own handlers and renders have run; a double click leaves the focus to them. +let clickClaim: ReturnType | undefined; +document.addEventListener('click', (event) => { + if (event.detail === 0) return; + clearTimeout(clickClaim); + clickClaim = setTimeout(() => { + view.claimFocus('click', readPageFocus(manager, origin)); + }); +}); +document.addEventListener('dblclick', () => { + clearTimeout(clickClaim); +}); +window.addEventListener('focus', () => { + view.claimFocus('windowFocus', readPageFocus(manager, origin)); }); const restorer = new Restorer({ diff --git a/src/web/terminals/manager.ts b/src/web/terminals/manager.ts index cadb38c..2f2c653 100644 --- a/src/web/terminals/manager.ts +++ b/src/web/terminals/manager.ts @@ -118,6 +118,26 @@ const openLink = (_event: MouseEvent, uri: string): void => { window.open(uri, '_blank', 'noopener,noreferrer'); }; +/** A cancelable copy of the `keydown` `event`, carrying the legacy `keyCode` xterm.js reads. */ +const replayOf = (event: KeyboardEvent): KeyboardEvent => { + const copy = new KeyboardEvent('keydown', { + bubbles: true, + cancelable: true, + key: event.key, + code: event.code, + location: event.location, + repeat: event.repeat, + isComposing: event.isComposing, + ctrlKey: event.ctrlKey, + shiftKey: event.shiftKey, + altKey: event.altKey, + metaKey: event.metaKey, + }); + // The legacy fields are not part of the event init. + for (const name of ['keyCode', 'which'] as const) Object.defineProperty(copy, name, { value: event[name] }); + return copy; +}; + /** One xterm.js terminal per daemon terminal, kept outside Preact and never re-created while its PTY lives (design D11, D12). */ export class TerminalManager { private readonly layer = document.createElement('div'); @@ -214,6 +234,19 @@ export class TerminalManager { this.entries.get(keyOf(host, termId))?.term.focus(); } + /** + * Focuses the terminal and replays the `keydown` `event`, pressed elsewhere, on it; cancels `event` when + * the terminal handled the replay, else lets its default proceed so the following `keypress` reaches the terminal. + */ + forwardKey(host: number, termId: number, event: KeyboardEvent): void { + const entry = this.entries.get(keyOf(host, termId)); + if (entry === undefined) return; + entry.term.focus(); + const textarea = entry.term.textarea; + if (textarea === undefined || document.activeElement !== textarea) return; + if (!textarea.dispatchEvent(replayOf(event))) event.preventDefault(); + } + /** The terminal's selected text; empty without a selection. */ selection(host: number, termId: number): string { return this.entries.get(keyOf(host, termId))?.term.getSelection() ?? ''; diff --git a/src/web/ui/app.tsx b/src/web/ui/app.tsx index 904fcc7..017856f 100644 --- a/src/web/ui/app.tsx +++ b/src/web/ui/app.tsx @@ -8,7 +8,8 @@ import { hasBanner, hostAction, statusText } from './hosts.js'; import { hubLineText, hubsMenu, hubStep, initialHubState, type HubAction, type HubLine, type HubTarget } from './hubs.js'; import { EDITOR_HINT, EDITOR_TITLE, editorBlocker, editorFailure, editorSave, type EditorFailure } from './editor.js'; import { aggregate, exitNote, markTitle, ringTitle, worktreeTitle, type Aggregate } from './marks.js'; -import { choicesTakeFocus, dropPosition, focusSpot, pickerKey, presetFromForm, type FocusSpot } from './picker.js'; +import { activeSpot, choicesTakeFocus } from './focus.js'; +import { dropPosition, pickerKey, presetFromForm } from './picker.js'; import { SIDEBAR_WIDTH, type SidebarEntry } from './sidebar.js'; import type { RepoTab } from './repo-tabs.js'; import { @@ -1299,22 +1300,6 @@ const PresetPicker = ({ view, presets }: { view: View; presets: readonly Preset[ ); }; -/** Where the page's keyboard focus is. */ -const activeSpot = (manager: TerminalManager): FocusSpot => { - const active = document.activeElement; - return focusSpot( - active === null - ? null - : { - tag: active.tagName.toLowerCase(), - type: active instanceof HTMLInputElement ? active.type : '', - editable: active instanceof HTMLElement && active.isContentEditable, - terminal: manager.owns(active), - menu: active.getAttribute('aria-expanded') === 'true' || active.closest('[role="menu"]') !== null, - }, - ); -}; - /** The presets a worktree without terminals offers; they take the keyboard focus as `choicesTakeFocus` says. */ const PresetChoices = ({ view, manager, presets }: { view: View; manager: TerminalManager; presets: readonly Preset[] }) => { const [index, setIndex] = useState(0); diff --git a/src/web/ui/focus.ts b/src/web/ui/focus.ts new file mode 100644 index 0000000..0cf62c2 --- /dev/null +++ b/src/web/ui/focus.ts @@ -0,0 +1,187 @@ +import type { TerminalManager } from '../terminals/index.js'; + +/** The focused element as far as the focus policy depends on it. */ +export interface FocusedElement { + /** Lower-case tag name. */ + tag: string; + /** Lower-case `type` of an input, else empty. */ + type: string; + /** Inside an editable (contenteditable) element. */ + editable: boolean; + /** Owned by a terminal. */ + terminal: boolean; + /** On a control whose menu is open, or inside an open menu. */ + menu: boolean; +} + +export type FocusSpot = 'none' | 'terminal' | 'menu' | 'textField' | 'other'; + +const TEXT_INPUT_TYPES = new Set(['text', 'search', 'email', 'url', 'tel', 'password', 'number']); + +/** Where the keyboard focus is: nowhere (the page body), a terminal, an open menu, a text field, or any other element. */ +export const focusSpot = (element: FocusedElement | null): FocusSpot => { + if (element === null) return 'none'; + if (element.terminal) return 'terminal'; + if (element.menu) return 'menu'; + if (element.editable || element.tag === 'textarea') return 'textField'; + if (element.tag === 'input' && TEXT_INPUT_TYPES.has(element.type)) return 'textField'; + return element.tag === 'body' ? 'none' : 'other'; +}; + +/** Why a worktree's preset choices consider taking the focus: just shown, or a picker or dialog over them just closed. */ +export type ChoicesTrigger = 'shown' | 'modalClosed'; + +/** Whether a worktree's preset choices take the keyboard focus from `spot`. */ +export const choicesTakeFocus = (trigger: ChoicesTrigger, spot: FocusSpot, modalOpen: boolean): boolean => { + if (modalOpen) return false; + return trigger === 'shown' ? spot !== 'textField' && spot !== 'menu' : spot === 'none'; +}; + +/** The parts of a key event the claim rule reads. */ +export interface ClaimKey { + key: string; + ctrlKey: boolean; + metaKey: boolean; + isComposing: boolean; +} + +/** What makes the current terminal consider taking the keyboard focus. */ +export type ClaimTrigger = { t: 'click' } | { t: 'windowFocus' } | { t: 'key'; key: ClaimKey }; + +/** The page's keyboard focus as the claim rule reads it from the DOM. */ +export interface PageFocus { + spot: FocusSpot; + /** The focused element got the focus from a pointer interaction. */ + clicked: boolean; + /** A menu is open somewhere on the page. */ + menuOpen: boolean; + /** Text outside the terminals is selected. */ + pageSelection: boolean; +} + +export interface FocusWorld extends PageFocus { + /** A picker or dialog is open. */ + modal: boolean; + /** A current terminal exists. */ + currentTerminal: boolean; +} + +const composing = (key: ClaimKey): boolean => key.isComposing || key.key === 'Process' || key.key === 'Dead'; + +/** Whether `trigger` gives the keyboard focus (and, for a key, the key) to the current terminal. */ +export const terminalTakesFocus = (trigger: ClaimTrigger, world: FocusWorld): boolean => { + const nothingHolds = world.spot === 'none' || (world.spot === 'other' && world.clicked); + if (!world.currentTerminal || world.modal || world.menuOpen || !nothingHolds) return false; + if (trigger.t !== 'key') return !world.pageSelection; + const { key } = trigger; + return !composing(key) && !(world.pageSelection && (key.ctrlKey || key.metaKey)); +}; + +/** Remembers whether the focused element got the focus during a pointer interaction. */ +export class FocusOrigin { + private pointing = false; + private clickedElement: T | null = null; + + /** A pointer interaction starts. */ + pointerDown(): void { + this.pointing = true; + } + + /** The pointer interaction, its click included, is over. */ + pointerSettled(): void { + this.pointing = false; + } + + /** `element` received the focus. */ + focused(element: T): void { + this.clickedElement = this.pointing ? element : null; + } + + clicked(element: T | null): boolean { + return element !== null && element === this.clickedElement; + } +} + +/** The document selection as far as `pageTextSelected` depends on it. */ +export interface SelectionFacts { + collapsed: boolean; + anchorInTerminals: boolean; + focusInTerminals: boolean; + /** Both endpoints are still in the document. */ + connected: boolean; +} + +/** Whether a selection covers text outside the terminals. */ +export const pageTextSelected = (facts: SelectionFacts | null): boolean => + facts !== null && facts.connected && !facts.collapsed && !(facts.anchorInTerminals && facts.focusInTerminals); + +type Owner = Pick; + +/** Where the page's keyboard focus is. */ +export const activeSpot = (manager: Owner): FocusSpot => { + const active = document.activeElement; + return focusSpot( + active === null + ? null + : { + tag: active.tagName.toLowerCase(), + type: active instanceof HTMLInputElement ? active.type : '', + editable: active instanceof HTMLElement && active.isContentEditable, + terminal: manager.owns(active), + menu: active.getAttribute('aria-expanded') === 'true' || active.closest('[role="menu"]') !== null, + }, + ); +}; + +const selectionFacts = (manager: Owner): SelectionFacts | null => { + const selection = document.getSelection(); + if (selection === null || selection.rangeCount === 0) return null; + const { anchorNode, focusNode } = selection; + return { + collapsed: selection.isCollapsed, + anchorInTerminals: manager.owns(anchorNode), + focusInTerminals: manager.owns(focusNode), + connected: anchorNode?.isConnected === true && focusNode?.isConnected === true, + }; +}; + +/** The page's keyboard focus, read from the DOM. */ +export const readPageFocus = (manager: Owner, origin: FocusOrigin): PageFocus => ({ + spot: activeSpot(manager), + clicked: origin.clicked(document.activeElement), + menuOpen: document.querySelector('[aria-expanded="true"], [role="menu"]') !== null, + pageSelection: pageTextSelected(selectionFacts(manager)), +}); + +/** Feeds `origin` the page's pointer interactions and focus changes. */ +export const trackFocusOrigin = (origin: FocusOrigin): void => { + let target: Node | null = null; + const settleLater = (): void => { + // After the click this interaction dispatches and the renders it causes. + setTimeout(() => { + // A click on the already focused control does not move the focus, but still makes it clicked. + const active = document.activeElement; + if (active !== null && target !== null && active.contains(target)) origin.focused(active); + origin.pointerSettled(); + }); + }; + window.addEventListener( + 'pointerdown', + (event) => { + target = event.target instanceof Node ? event.target : null; + origin.pointerDown(); + }, + true, + ); + for (const type of ['pointerup', 'pointercancel', 'contextmenu'] as const) window.addEventListener(type, settleLater, true); + window.addEventListener('blur', () => { + origin.pointerSettled(); + }); + document.addEventListener( + 'focusin', + (event) => { + if (event.target instanceof Element) origin.focused(event.target); + }, + true, + ); +}; diff --git a/src/web/ui/index.ts b/src/web/ui/index.ts index 2d815cf..ed0eb75 100644 --- a/src/web/ui/index.ts +++ b/src/web/ui/index.ts @@ -1,2 +1,3 @@ export { App, type AppProps } from './app.js'; export { SWITCH_END, SWITCH_START, View } from './view.js'; +export { FocusOrigin, readPageFocus, trackFocusOrigin } from './focus.js'; diff --git a/src/web/ui/keymap.ts b/src/web/ui/keymap.ts index 230a766..4787885 100644 --- a/src/web/ui/keymap.ts +++ b/src/web/ui/keymap.ts @@ -14,6 +14,7 @@ export interface KeyLike { export type Action = | { t: 'worktree'; dir: -1 | 1 } + | { t: 'repo'; dir: -1 | 1 } | { t: 'tab'; dir: -1 | 1 } | { t: 'pane'; dir: Direction } | { t: 'newTab' } @@ -46,9 +47,9 @@ const altArrow = (dir: Direction): Action => { case 'down': return { t: 'worktree', dir: 1 }; case 'left': - return { t: 'tab', dir: -1 }; + return { t: 'repo', dir: -1 }; case 'right': - return { t: 'tab', dir: 1 }; + return { t: 'repo', dir: 1 }; } }; @@ -58,6 +59,9 @@ const actionOf = (e: KeyLike): { action: Action; navigation: boolean } | null => if (arrow !== undefined && e.altKey && !e.ctrlKey) { return { action: e.shiftKey ? { t: 'pane', dir: arrow } : altArrow(arrow), navigation: true }; } + if ((arrow === 'left' || arrow === 'right') && e.ctrlKey && e.shiftKey && !e.altKey) { + return { action: { t: 'tab', dir: arrow === 'left' ? -1 : 1 }, navigation: true }; + } const action = CTRL_SHIFT[e.code]; if (action !== undefined && e.ctrlKey && e.shiftKey && !e.altKey) return { action, navigation: false }; return null; diff --git a/src/web/ui/picker.ts b/src/web/ui/picker.ts index 3d22b5b..79e94c1 100644 --- a/src/web/ui/picker.ts +++ b/src/web/ui/picker.ts @@ -53,43 +53,6 @@ export const pickerKey = (key: string, index: number, count: number, repeat: boo } }; -/** The focused element as far as the focus policy depends on it. */ -export interface FocusedElement { - /** Lower-case tag name. */ - tag: string; - /** Lower-case `type` of an input, else empty. */ - type: string; - /** Inside an editable (contenteditable) element. */ - editable: boolean; - /** Owned by a terminal. */ - terminal: boolean; - /** On a control whose menu is open, or inside an open menu. */ - menu: boolean; -} - -export type FocusSpot = 'none' | 'terminal' | 'menu' | 'textField' | 'other'; - -const TEXT_INPUT_TYPES = new Set(['text', 'search', 'email', 'url', 'tel', 'password', 'number']); - -/** Where the keyboard focus is: nowhere (the page body), a terminal, an open menu, a text field, or any other element. */ -export const focusSpot = (element: FocusedElement | null): FocusSpot => { - if (element === null) return 'none'; - if (element.terminal) return 'terminal'; - if (element.menu) return 'menu'; - if (element.editable || element.tag === 'textarea') return 'textField'; - if (element.tag === 'input' && TEXT_INPUT_TYPES.has(element.type)) return 'textField'; - return element.tag === 'body' ? 'none' : 'other'; -}; - -/** Why a worktree's preset choices consider taking the focus: just shown, or a picker or dialog over them just closed. */ -export type ChoicesTrigger = 'shown' | 'modalClosed'; - -/** Whether a worktree's preset choices take the keyboard focus from `spot`. */ -export const choicesTakeFocus = (trigger: ChoicesTrigger, spot: FocusSpot, modalOpen: boolean): boolean => { - if (modalOpen) return false; - return trigger === 'shown' ? spot !== 'textField' && spot !== 'menu' : spot === 'none'; -}; - const MAX_PRESET_NAME = 64; const MAX_PRESET_COMMAND = 4096; diff --git a/src/web/ui/view.test.ts b/src/web/ui/view.test.ts index 38e24c2..72fc029 100644 --- a/src/web/ui/view.test.ts +++ b/src/web/ui/view.test.ts @@ -165,6 +165,14 @@ const report = (client: HubClient, hostIdx: number, repo: string, terms: readonl }); }; +/** Opens the remove-repo confirmation for the shown repo tab. */ +const openDialog = (view: View): void => { + const tab = view.tab.value; + if (tab === null) throw new Error('no repo tab is shown'); + view.requestRemoveRepo(tab); + expect(view.modal.value).toBe(true); +}; + const NOTHING_HOLDS: PageFocus = { spot: 'none', clicked: false, menuOpen: false, pageSelection: false }; describe('View', () => { @@ -219,7 +227,7 @@ describe('View', () => { }); it('leaves the focus while a picker or dialog is open', () => { - view.openWorktreeMenu('/r/app', 10, 10); + openDialog(view); manager.clear(); view.claimFocus('click', NOTHING_HOLDS); view.claimFocus('windowFocus', NOTHING_HOLDS); @@ -310,7 +318,7 @@ describe('View', () => { }); it('does nothing while a picker or dialog is open', () => { - view.openWorktreeMenu('/r/a', 10, 10); + openDialog(view); press('ArrowRight'); expect(shown()).toBe('/r/a'); }); diff --git a/src/web/ui/view.ts b/src/web/ui/view.ts index a330b9b..5d513bd 100644 --- a/src/web/ui/view.ts +++ b/src/web/ui/view.ts @@ -26,6 +26,7 @@ import { import type { Box, TerminalManager } from '../terminals/index.js'; import { closeTargets, needsConfirm } from './closing.js'; import type { EditorFailure } from './editor.js'; +import { terminalTakesFocus, type ClaimTrigger, type PageFocus } from './focus.js'; import { hostAction, Latest, offeredRepos, type HostAction } from './hosts.js'; import { keymap, type Action } from './keymap.js'; import { pickerValid, type PickerContext, type PickerOp, type PickerWorld } from './picker.js'; @@ -194,6 +195,12 @@ export interface AddRepoDialog { error: string | null; } +/** The terminal manager calls the view makes. */ +export type ViewTerminals = Pick< + TerminalManager, + 'has' | 'open' | 'focus' | 'forwardKey' | 'show' | 'sizeFor' | 'selection' | 'paste' | 'onFocus' +>; + /** The page's selection, stored per browser, and what it shows; keeps the terminal manager in step. */ export class View { readonly selectedRepo = signal(load(REPO_KEY)); @@ -371,7 +378,7 @@ export class View { constructor( private readonly client: HubClient, - private readonly manager: TerminalManager, + private readonly manager: ViewTerminals, ) { effect(() => { this.sync(); @@ -798,11 +805,37 @@ export class View { return true; } + /** Gives the current terminal the keyboard focus after a pointer click or the window regaining the focus, if the rule allows. */ + claimFocus(trigger: 'click' | 'windowFocus', page: PageFocus): void { + const target = this.claimTarget({ t: trigger }, page); + if (target !== null) this.manager.focus(target.host, target.termId); + } + + /** Delivers a key pressed outside the terminals to the current terminal, if the rule allows; run after `handleKey`. */ + claimKey(event: KeyboardEvent, page: PageFocus): void { + if (event.defaultPrevented) return; + const target = this.claimTarget({ t: 'key', key: event }, page); + if (target !== null) this.manager.forwardKey(target.host, target.termId, event); + } + + /** The current terminal, when `trigger` gives it the keyboard focus. */ + private claimTarget(trigger: ClaimTrigger, page: PageFocus): { host: number; termId: number } | null { + const host = this.tab.peek()?.host; + const termId = this.focused.peek(); + const current = host !== undefined && termId !== null && this.manager.has(host, termId); + const modal = this.modal.peek(); + if (!terminalTakesFocus(trigger, { ...page, modal, currentTerminal: current }) || host === undefined || termId === null) return null; + return { host, termId }; + } + private act(action: Action): void { switch (action.t) { case 'worktree': this.stepWorktree(action.dir); return; + case 'repo': + this.stepRepo(action.dir); + return; case 'tab': this.stepTab(action.dir); return; @@ -837,6 +870,14 @@ export class View { if (next !== undefined && next.path !== this.worktree.value) this.selectWorktree(next.path); } + private stepRepo(dir: -1 | 1): void { + const tabs = this.tabs.value; + const current = this.tab.value; + const index = current === null ? -1 : tabs.findIndex((t) => t.host === current.host && t.repo === current.repo); + const next = index < 0 ? undefined : tabs[index + dir]; + if (next !== undefined) this.selectRepo(next); + } + private stepTab(dir: -1 | 1): void { const { tabs, active } = this.termTabs.value; const index = tabs.findIndex((t) => t.termId === active); From 38bbf699d38ffed4a8afd397eaacba000f6aa1c3 Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 14:00:51 +0100 Subject: [PATCH 4/7] Tick the implemented tasks; record the sync() focus probe --- .../tasks.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md index bce0ea3..2062907 100644 --- a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md @@ -10,25 +10,26 @@ ## 2. Focus rule and tracking (`src/web/ui/focus.ts`) -- [ ] 2.1 Create `focus.ts`; move `focusSpot`, `FocusSpot`, `FocusedElement`, `choicesTakeFocus`, `ChoicesTrigger` from `picker.ts` and `activeSpot` from `app.tsx`; update imports; verify `pnpm test` unit tier for picker/focus passes -- [ ] 2.2 Implement `terminalTakesFocus`, the page-selection classifier and the focus-origin tracker (design D2–D4, D6–D8); verify 1.1–1.2 pass +- [x] 2.1 Create `focus.ts`; move `focusSpot`, `FocusSpot`, `FocusedElement`, `choicesTakeFocus`, `ChoicesTrigger` from `picker.ts` and `activeSpot` from `app.tsx`; update imports; verify `pnpm test` unit tier for picker/focus passes +- [x] 2.2 Implement `terminalTakesFocus`, the page-selection classifier and the focus-origin tracker (design D2–D4, D6–D8); verify 1.1–1.2 pass ## 3. Terminal key delivery (`src/web/terminals/manager.ts`) -- [ ] 3.1 Add public `forwardKey(host, termId, event)` per design D5 (replay keydown on xterm's textarea with `keyCode` defined, cancel the original only when xterm handled the replay); verify the first-key e2e scenario passes with no duplicate input +- [x] 3.1 Add public `forwardKey(host, termId, event)` per design D5 (replay keydown on xterm's textarea with `keyCode` defined, cancel the original only when xterm handled the replay); verify the first-key e2e scenario passes with no duplicate input ## 4. Wiring (`view.ts`, `main/index.ts`) -- [ ] 4.1 `View`: claim method applying the rule for the three triggers; key trigger runs after `handleKey` and skips default-prevented keys; verify 1.3 passes -- [ ] 4.2 `main/index.ts`: document `keydown` → claim; document `click` (pointer clicks only, `detail !== 0`) → claim a task later, re-reading the focus, cancelled by `dblclick`; `window` `focus` → claim; install the origin tracker (design D9) -- [ ] 4.3 Find why `sync()`'s own focus call loses after clicking a new worktree row or repo tab and remove that cause (design D10); verify the `Clicking another worktree/repo tab` scenarios pass +- [x] 4.1 `View`: claim method applying the rule for the three triggers; key trigger runs after `handleKey` and skips default-prevented keys; verify 1.3 passes +- [x] 4.2 `main/index.ts`: document `keydown` → claim; document `click` (pointer clicks only, `detail !== 0`) → claim a task later, re-reading the focus, cancelled by `dblclick`; `window` `focus` → claim; install the origin tracker (design D9) +- [x] 4.3 Find why `sync()`'s own focus call loses after clicking a new worktree row or repo tab and remove that cause (design D10); verify the `Clicking another worktree/repo tab` scenarios pass + - Probe: with the click claim disabled, `sync()`'s focus call already wins for a new or previously viewed worktree row and repo tab, with fast and slow clicks; no losing cause reproduced, nothing removed. Both scenarios pass with and without the click claim. ## 5. Shortcuts -- [ ] 5.1 `keymap.ts`: new `repo` action on Alt+Left/Right, `tab` on Ctrl+Shift+Left/Right (navigation); `View.stepRepo` over the shown repo tabs; verify 1.4 and 1.6 pass -- [ ] 5.2 README shortcut table updated to the new bindings +- [x] 5.1 `keymap.ts`: new `repo` action on Alt+Left/Right, `tab` on Ctrl+Shift+Left/Right (navigation); `View.stepRepo` over the shown repo tabs; verify 1.4 and 1.6 pass +- [x] 5.2 README shortcut table updated to the new bindings ## 6. Gates - [ ] 6.1 Run the local test scope (`la-affected-tests --base main` plus the e2e specs above, `keyboard.spec.ts`, `splits.spec.ts`, `picker.spec.ts`, `sidebar.spec.ts`, `tab-names.spec.ts`, `terminals.spec.ts`); all green -- [ ] 6.2 Enforcement bundle: `la-arch-check`, LikeC4 validation, `tsc -b`, `pnpm lint`; all green +- [x] 6.2 Enforcement bundle: `la-arch-check`, LikeC4 validation, `tsc -b`, `pnpm lint`; all green From 57a8ed3ff6b9a1f7d18fded932e6f2f697a62cef Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 14:59:05 +0100 Subject: [PATCH 5/7] Click claim sees clicks controls keep to themselves; pointer-origin tracking ignores stale settles and keyboard focus during a press; Hubs Escape gives the button the keyboard - Capture-phase click/dblclick listeners, so the star checkbox's click claims too - FocusOrigin: per-interaction ids, a key during a press ends pointer attribution, a late settle never overrides a focus moved after the press - Hubs Escape re-focuses via blur so the button holds the keyboard - Tests: star click, Hubs Escape then Space, double-click selection copies, Ctrl+Shift+Right changes the tab, modifier held before focusing the body, worktree list polled --- src/web/main/index.ts | 29 +++++++++----- src/web/ui/app.tsx | 7 +++- src/web/ui/focus.test.ts | 39 ++++++++++++++++++ src/web/ui/focus.ts | 41 ++++++++++++++----- src/web/ui/view.test.ts | 21 ++++++++++ test/e2e/focus.spec.ts | 83 ++++++++++++++++++++++++++++++++------- test/e2e/keyboard.spec.ts | 2 +- 7 files changed, 185 insertions(+), 37 deletions(-) diff --git a/src/web/main/index.ts b/src/web/main/index.ts index a64e579..ff50b4c 100644 --- a/src/web/main/index.ts +++ b/src/web/main/index.ts @@ -22,17 +22,26 @@ document.addEventListener('keydown', (event) => { }); // A click claims once its own handlers and renders have run; a double click leaves the focus to them. +// Captured, so controls that stop a click's propagation are seen too. let clickClaim: ReturnType | undefined; -document.addEventListener('click', (event) => { - if (event.detail === 0) return; - clearTimeout(clickClaim); - clickClaim = setTimeout(() => { - view.claimFocus('click', readPageFocus(manager, origin)); - }); -}); -document.addEventListener('dblclick', () => { - clearTimeout(clickClaim); -}); +document.addEventListener( + 'click', + (event) => { + if (event.detail === 0) return; + clearTimeout(clickClaim); + clickClaim = setTimeout(() => { + view.claimFocus('click', readPageFocus(manager, origin)); + }); + }, + true, +); +document.addEventListener( + 'dblclick', + () => { + clearTimeout(clickClaim); + }, + true, +); window.addEventListener('focus', () => { view.claimFocus('windowFocus', readPageFocus(manager, origin)); }); diff --git a/src/web/ui/app.tsx b/src/web/ui/app.tsx index 017856f..0637c7a 100644 --- a/src/web/ui/app.tsx +++ b/src/web/ui/app.tsx @@ -174,8 +174,11 @@ const Hubs = ({ client }: { client: HubClient }) => { if (event.key !== 'Escape') return; event.stopPropagation(); setOpen(false); - // The focused entry goes with the menu: keep the keyboard on the Hubs button. - menuButton.current?.focus(); + // The focused entry goes with the menu: keep the keyboard on the Hubs button. Re-focusing an already focused + // button fires no focusin, so blur it first: the focus is then the page's, not a click's. + const button = menuButton.current; + if (button !== null && button === document.activeElement) button.blur(); + button?.focus(); }; const install = (): void => { const pending = stateRef.current.line; diff --git a/src/web/ui/focus.test.ts b/src/web/ui/focus.test.ts index 63a1bce..c6cd9f2 100644 --- a/src/web/ui/focus.test.ts +++ b/src/web/ui/focus.test.ts @@ -317,6 +317,45 @@ describe('FocusOrigin', () => { expect(origin.clicked(b)).toBe(true); }); + it('does not mark an element a key focuses during a pointer interaction', () => { + const origin = new FocusOrigin(); + origin.pointerDown(); + origin.focused(a); + origin.keyDown(); + origin.focused(b); + origin.pointerSettled(); + expect(origin.clicked(b)).toBe(false); + }); + + it('marks the focused element an interaction settles on without moving the focus, even after a key', () => { + const origin = new FocusOrigin(); + origin.focused(a); + const id = origin.pointerDown(); + origin.keyDown(); + origin.pointerSettled(id, a); + expect(origin.clicked(a)).toBe(true); + }); + + it('keeps a focus the page moved after the press when the interaction settles late', () => { + const origin = new FocusOrigin(); + const id = origin.pointerDown(); + origin.focused(a); + origin.keyDown(); + origin.focused(a); + origin.pointerSettled(id, a); + expect(origin.clicked(a)).toBe(false); + }); + + it('ignores the settling of an earlier interaction once a later one started', () => { + const origin = new FocusOrigin(); + const first = origin.pointerDown(); + origin.pointerDown(); + origin.pointerSettled(first, a); + expect(origin.clicked(a)).toBe(false); + origin.focused(b); + expect(origin.clicked(b)).toBe(true); + }); + it('reports nothing focused as not clicked', () => { const origin = new FocusOrigin(); origin.pointerDown(); diff --git a/src/web/ui/focus.ts b/src/web/ui/focus.ts index 0cf62c2..377529c 100644 --- a/src/web/ui/focus.ts +++ b/src/web/ui/focus.ts @@ -80,20 +80,37 @@ export const terminalTakesFocus = (trigger: ClaimTrigger, world: FocusWorld): bo /** Remembers whether the focused element got the focus during a pointer interaction. */ export class FocusOrigin { private pointing = false; + private interaction = 0; + /** The focus moved since the latest interaction started. */ + private moved = false; private clickedElement: T | null = null; - /** A pointer interaction starts. */ - pointerDown(): void { + /** A pointer interaction starts; returns its id. */ + pointerDown(): number { this.pointing = true; + this.moved = false; + this.interaction += 1; + return this.interaction; } - /** The pointer interaction, its click included, is over. */ - pointerSettled(): void { + /** A key is pressed: later focus changes are not the pointer's. */ + keyDown(): void { + this.pointing = false; + } + + /** + * Interaction `id` (default: the latest), its click included, is over; `stayed` is the focused element it pressed, + * which counts as clicked unless the focus moved since the press. An earlier interaction's id changes nothing. + */ + pointerSettled(id = this.interaction, stayed: T | null = null): void { + if (id !== this.interaction) return; + if (stayed !== null && !this.moved) this.clickedElement = stayed; this.pointing = false; } /** `element` received the focus. */ focused(element: T): void { + this.moved = true; this.clickedElement = this.pointing ? element : null; } @@ -155,25 +172,31 @@ export const readPageFocus = (manager: Owner, origin: FocusOrigin): Pag /** Feeds `origin` the page's pointer interactions and focus changes. */ export const trackFocusOrigin = (origin: FocusOrigin): void => { - let target: Node | null = null; + let pressed: { id: number; target: Node | null } = { id: 0, target: null }; const settleLater = (): void => { + const { id, target } = pressed; // After the click this interaction dispatches and the renders it causes. setTimeout(() => { // A click on the already focused control does not move the focus, but still makes it clicked. const active = document.activeElement; - if (active !== null && target !== null && active.contains(target)) origin.focused(active); - origin.pointerSettled(); + origin.pointerSettled(id, active !== null && target !== null && active.contains(target) ? active : null); }); }; window.addEventListener( 'pointerdown', (event) => { - target = event.target instanceof Node ? event.target : null; - origin.pointerDown(); + pressed = { id: origin.pointerDown(), target: event.target instanceof Node ? event.target : null }; }, true, ); for (const type of ['pointerup', 'pointercancel', 'contextmenu'] as const) window.addEventListener(type, settleLater, true); + window.addEventListener( + 'keydown', + () => { + origin.keyDown(); + }, + true, + ); window.addEventListener('blur', () => { origin.pointerSettled(); }); diff --git a/src/web/ui/view.test.ts b/src/web/ui/view.test.ts index 72fc029..0768829 100644 --- a/src/web/ui/view.test.ts +++ b/src/web/ui/view.test.ts @@ -324,7 +324,28 @@ describe('View', () => { }); it('chooses terminal tabs with Ctrl+Shift+arrows instead', () => { + client.store.apply(0, { + t: 'repoState', + repo: '/r/a', + worktrees: [worktree('/r/a', true)], + terminals: [terminal(1, '/r/a'), terminal(4, '/r/a')], + checked: [], + layouts: [ + { + worktree: '/r/a', + layout: { + tabs: [ + { id: 't1', root: { term: 1 } }, + { id: 't2', root: { term: 4 } }, + ], + active: 0, + }, + }, + ], + }); + expect(view.termTabs.value.active).toBe(1); expect(view.handleKey(new TestKey('ArrowRight', 'ArrowRight', { ctrlKey: true, shiftKey: true }), false)).toBe(true); + expect(view.termTabs.value.active).toBe(4); expect(shown()).toBe('/r/a'); }); }); diff --git a/test/e2e/focus.spec.ts b/test/e2e/focus.spec.ts index 5879a0c..7617538 100644 --- a/test/e2e/focus.spec.ts +++ b/test/e2e/focus.spec.ts @@ -1,6 +1,7 @@ import type { Page } from '@playwright/test'; import { writeFileSync } from 'node:fs'; import { join } from 'node:path'; +import type { FakeSsh } from '../support/fake-ssh.js'; import type { HubHost } from '../support/hub-host.js'; import { byTestId, repoTab, terminalBox, termTab, TID, worktreeEntry } from './contract.js'; import { @@ -71,6 +72,18 @@ const oneShell = async (hub: HubHost, page: Page): Promise<{ repo: string; term: return { repo, term }; }; +/** A shell with the key echo running, on a page that shows the Hubs menu; returns the terminal. */ +const hubsShell = async (hub: HubHost, page: Page, ssh: FakeSsh): Promise => { + ssh.failHost('box', 'ssh: Could not resolve hostname box: Name or service not known'); + const { repo } = makeRepoWith(hub, 'app', []); + writeHubConfig(hub, { repos: [repo], hosts: [{ name: 'box', ssh: 'box' }] }); + await openUi(hub, page); + const term = await newTerminal(page); + await ready(page, term); + await startKeyEcho(hub, page, term); + return term; +}; + /** Lets the page see the window lose the focus and regain it. */ const switchWindowAway = (page: Page): Promise => page.evaluate(() => { @@ -125,6 +138,13 @@ test.describe('typing after a click reaches the current terminal', () => { await echoReaches(page, term, 'TAB-SAME'); }); + test('clicking a worktree’s star, which keeps its click to itself', async ({ hub, page }) => { + const { repo, term } = await oneShell(hub, page); + await page.locator(`${worktreeEntry(repo)} input[type="checkbox"]`).click(); + await expect.poll(() => focusedTerminal(page)).toBe(term); + await echoReaches(page, term, 'STAR-OK'); + }); + test('clicking an empty part of the tab bar', async ({ hub, page }) => { const { term } = await oneShell(hub, page); const newTab = await page.locator(byTestId(TID.newTab)).boundingBox(); @@ -192,16 +212,19 @@ test.describe('keys pressed while nothing holds the keyboard', () => { await startKeyEcho(hub, page, term); let expected = ''; - for (const [key, hex] of [ - ['KeyA', '61'], - ['Shift+KeyA', '41'], - ['ArrowUp', '1b5b41'], - ['Backspace', '7f'], - ['Enter', '0d'], - ['Control+KeyC', '03'], + for (const [modifier, key, hex] of [ + [null, 'KeyA', '61'], + ['Shift', 'KeyA', '41'], + [null, 'ArrowUp', '1b5b41'], + [null, 'Backspace', '7f'], + [null, 'Enter', '0d'], + ['Control', 'KeyC', '03'], ] as const) { + // The modifier's own keydown already claims, so the body takes the focus back before the key. + if (modifier !== null) await page.keyboard.down(modifier); await focusBody(page); await page.keyboard.press(key); + if (modifier !== null) await page.keyboard.up(modifier); expected += `[${hex}]`; await expect.poll(() => received(page, term), { message: key }).toBe(expected); expect(await focusedTerminal(page)).toBe(term); @@ -298,14 +321,7 @@ test.describe('fields, menus and focused controls keep their keys', () => { }); test('the open Hubs menu', async ({ hub, page, ssh }) => { - ssh.failHost('box', 'ssh: Could not resolve hostname box: Name or service not known'); - const { repo } = makeRepoWith(hub, 'app', []); - writeHubConfig(hub, { repos: [repo], hosts: [{ name: 'box', ssh: 'box' }] }); - await openUi(hub, page); - const term = await newTerminal(page); - await ready(page, term); - await startKeyEcho(hub, page, term); - + const term = await hubsShell(hub, page, ssh); await page.locator(byTestId(TID.hubsMenu)).click(); const list = page.locator(byTestId(TID.hubsList)); await expect(list).toBeVisible(); @@ -314,6 +330,21 @@ test.describe('fields, menus and focused controls keep their keys', () => { await expect(list).toBeVisible(); }); + test('Escape from a clicked Hubs menu leaves the keyboard on the Hubs button', async ({ hub, page, ssh }) => { + const term = await hubsShell(hub, page, ssh); + const button = page.locator(byTestId(TID.hubsMenu)); + await button.click(); + const list = page.locator(byTestId(TID.hubsList)); + await expect(list).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(list).toHaveCount(0); + expect(await button.evaluate((el) => el === document.activeElement)).toBe(true); + + await page.keyboard.press('Space'); + await expect(list).toBeVisible(); + await receivedNothing(page, term); + }); + test('a terminal tab focused from the keyboard takes Enter', async ({ hub, page }) => { const { term: first } = await oneShell(hub, page); const second = await newTerminal(page); @@ -353,6 +384,28 @@ test.describe('fields, menus and focused controls keep their keys', () => { await expect.poll(() => received(page, term)).toBe('[78]'); }); + test('a word selected by a double click: Ctrl+C copies it', async ({ hub, page, context }) => { + await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: hub.origin }); + const { repo, term } = await oneShell(hub, page); + await startKeyEcho(hub, page, term); + + const tab = await page.locator(repoTab(repo)).boundingBox(); + if (tab === null) throw new Error('the repo tab is not shown'); + // A person's double click: the first click's own task runs before the second press. + await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2); + await page.mouse.down({ clickCount: 1 }); + await page.mouse.up({ clickCount: 1 }); + await page.waitForTimeout(120); // NOSONAR(S2925) — the gap between a person's two clicks + await page.mouse.down({ clickCount: 2 }); + await page.mouse.up({ clickCount: 2 }); + const selected = await page.evaluate(() => getSelection()?.toString() ?? ''); + expect(selected).not.toBe(''); + + await page.keyboard.press('Control+KeyC'); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(selected); + await receivedNothing(page, term); + }); + test('without a current terminal, a click in the terminal area focuses no terminal', async ({ hub, page }) => { const { repo, worktrees } = makeRepoWith(hub, 'app', ['empty']); const [empty = ''] = worktrees; diff --git a/test/e2e/keyboard.spec.ts b/test/e2e/keyboard.spec.ts index 507c1b3..c64f9a2 100644 --- a/test/e2e/keyboard.spec.ts +++ b/test/e2e/keyboard.spec.ts @@ -92,7 +92,7 @@ test.describe('navigation and the keyboard focus', () => { hub.writeRepos([repo]); await openUi(hub, page); const [[mainTerm = 0] = [], [bTerm = 0] = []] = await createShells(await watcher(hub, repo), [repo, b]); - expect(await listedWorktrees(page)).toEqual([repo, b]); + await expect.poll(() => listedWorktrees(page)).toEqual([repo, b]); await selectWorktree(page, repo); await page.locator(terminalBox(LOCAL, mainTerm)).click(); await expect.poll(() => focusedTerminal(page)).toBe(mainTerm); From b636d11d57e4b7e41cd61a12276d02a1118e6bfa Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 15:05:10 +0100 Subject: [PATCH 6/7] Tick the local test scope gate --- .../tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md index 2062907..c5614b9 100644 --- a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md +++ b/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md @@ -31,5 +31,5 @@ ## 6. Gates -- [ ] 6.1 Run the local test scope (`la-affected-tests --base main` plus the e2e specs above, `keyboard.spec.ts`, `splits.spec.ts`, `picker.spec.ts`, `sidebar.spec.ts`, `tab-names.spec.ts`, `terminals.spec.ts`); all green +- [x] 6.1 Run the local test scope (`la-affected-tests --base main` plus the e2e specs above, `keyboard.spec.ts`, `splits.spec.ts`, `picker.spec.ts`, `sidebar.spec.ts`, `tab-names.spec.ts`, `terminals.spec.ts`); all green - [x] 6.2 Enforcement bundle: `la-arch-check`, LikeC4 validation, `tsc -b`, `pnpm lint`; all green From fe406074088e7b7b36309c68969d3f3a7de853e5 Mon Sep 17 00:00:00 2001 From: Egor Kraev Date: Wed, 18 Nov 2026 15:12:05 +0100 Subject: [PATCH 7/7] Archive the OpenSpec change: merge the Pane focus and Keyboard shortcuts deltas into the web spec --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/web/spec.md | 0 .../tasks.md | 0 openspec/specs/web/spec.md | 91 ++++++++++++++++++- 6 files changed, 86 insertions(+), 5 deletions(-) rename openspec/changes/{dev-2339-worktree-term-typing-in-the-focused-wtd-window => archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window}/.openspec.yaml (100%) rename openspec/changes/{dev-2339-worktree-term-typing-in-the-focused-wtd-window => archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window}/design.md (100%) rename openspec/changes/{dev-2339-worktree-term-typing-in-the-focused-wtd-window => archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window}/proposal.md (100%) rename openspec/changes/{dev-2339-worktree-term-typing-in-the-focused-wtd-window => archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window}/specs/web/spec.md (100%) rename openspec/changes/{dev-2339-worktree-term-typing-in-the-focused-wtd-window => archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window}/tasks.md (100%) diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml b/openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml similarity index 100% rename from openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml rename to openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/.openspec.yaml diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md b/openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md similarity index 100% rename from openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md rename to openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/design.md diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md b/openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md similarity index 100% rename from openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md rename to openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/proposal.md diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md b/openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md similarity index 100% rename from openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md rename to openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/specs/web/spec.md diff --git a/openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md b/openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md similarity index 100% rename from openspec/changes/dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md rename to openspec/changes/archive/2026-11-18-dev-2339-worktree-term-typing-in-the-focused-wtd-window/tasks.md diff --git a/openspec/specs/web/spec.md b/openspec/specs/web/spec.md index 2d24c6c..c58e1ec 100644 --- a/openspec/specs/web/spec.md +++ b/openspec/specs/web/spec.md @@ -366,7 +366,7 @@ Splitting SHALL start a new terminal through the preset picker, send `createTerm - **THEN** both new terminals stay visible, each in the layout or as a further tab ### Requirement: Pane focus -Each tab SHALL have one focused pane, kept per page and not stored: the first pane until the user chooses another, the pane the user clicks, a new pane once created, and, when the focused pane's terminal closes, the first pane of the subtree that took its place. In a split, the focused pane's header SHALL be shown in the accent colour. The focused pane SHALL hold the keyboard focus whenever its tab is shown and no picker or dialog is open. +Each tab SHALL have one focused pane, kept per page and not stored: the first pane until the user chooses another, the pane the user clicks, a new pane once created, and, when the focused pane's terminal closes, the first pane of the subtree that took its place. In a split, the focused pane's header SHALL be shown in the accent colour. While its tab is shown and no picker or dialog is open, the focused pane's terminal is the current terminal: it SHALL take the keyboard focus when its tab is shown, when it becomes the focused pane and when a picker or dialog closes. Nothing holds the keyboard while the keyboard focus is on the page body or on a control the user clicked, and no text field, open menu, picker or dialog is present to hold it; a control focused from the keyboard or by the page holds it. While nothing holds the keyboard, a pointer click and the window regaining the focus SHALL give the keyboard focus to the current terminal unless text outside the terminals is selected, and a key SHALL reach the current terminal, the first key included, unless it is a keyboard shortcut, is being composed with an input method, or is pressed with Ctrl or Meta while text outside the terminals is selected. Without a current terminal, none of this SHALL move the keyboard focus. #### Scenario: Focus follows a closed pane's sibling - **WHEN** the focused pane of a two-pane split is closed @@ -376,6 +376,78 @@ Each tab SHALL have one focused pane, kept per page and not stored: the first pa - **WHEN** the user types `exit` in the focused pane of a two-pane split - **THEN** the remaining pane is focused and receives typed input +#### Scenario: Clicking another worktree focuses its terminal +- **WHEN** a terminal of the selected worktree has the keyboard focus, the user clicks the row of another worktree that has a terminal, and types `echo b` and Enter +- **THEN** the other worktree's current terminal has the keyboard focus and runs `echo b`, without a further click + +#### Scenario: Clicking another repo tab focuses its terminal +- **WHEN** the user clicks another repo tab whose selected worktree has a terminal and types text +- **THEN** the text reaches that repo's current terminal + +#### Scenario: Typing after clicking the selected worktree's row +- **WHEN** the user clicks the selected worktree's row and types `echo row` +- **THEN** `echo row` reaches the current terminal + +#### Scenario: Typing after clicking the active terminal tab +- **WHEN** the user clicks the active terminal tab and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after clicking the page background +- **WHEN** the user clicks an empty part of the tab bar and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after clicking a disabled control +- **WHEN** the split controls are disabled, the user clicks one and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after dragging the sidebar edge +- **WHEN** the user drags the sidebar's right edge to a new width and types text +- **THEN** the text reaches the current terminal + +#### Scenario: Typing after the clicked control disappears +- **WHEN** the user closes a tab whose terminal exited with its close control, no dialog is shown, and the user types text +- **THEN** the text reaches the current terminal + +#### Scenario: First key not lost +- **WHEN** the keyboard focus is on the page body and the user presses, one at a time, a lower-case letter, an upper-case letter, an arrow key, Backspace, Enter and Ctrl+C +- **THEN** the current terminal's program receives each of those keys exactly once, the first included + +#### Scenario: Window refocus +- **WHEN** the keyboard focus is on the page body or on a control the user clicked, the window loses the focus and regains it, and the user types text +- **THEN** the current terminal has the keyboard focus and the text reaches it + +#### Scenario: Search keeps its keys +- **WHEN** the worktree search has the keyboard focus and the user types text +- **THEN** the text appears in the search and nothing reaches the current terminal + +#### Scenario: Add form keeps its keys +- **WHEN** the add form in the preset picker has the keyboard focus and the user types text +- **THEN** the text appears in the form and nothing reaches the current terminal + +#### Scenario: Rename field keeps its keys +- **WHEN** the user double-clicks a terminal tab and types text +- **THEN** the rename field has the keyboard focus with its text selected before typing, the typed text replaces it, and nothing reaches the current terminal + +#### Scenario: Open menu keeps its keys +- **WHEN** the Hubs menu is open and the user types a letter +- **THEN** the menu stays open and nothing reaches the current terminal + +#### Scenario: A control focused from the keyboard keeps its keys +- **WHEN** the user focuses an inactive terminal tab from the keyboard and presses Enter +- **THEN** that tab is shown with its terminal focused, and no Enter reached the previously focused terminal's program + +#### Scenario: Copying selected page text +- **WHEN** the user selects a worktree's name in the sidebar with the pointer and presses Ctrl+C, then types `x` +- **THEN** the name is copied to the clipboard, the current terminal's program receives no Ctrl+C, and `x` reaches the current terminal + +#### Scenario: Shortcut while nothing holds the keyboard +- **WHEN** the keyboard focus is on the page body and the user presses Alt+Down +- **THEN** the next worktree is selected, its current terminal has the keyboard focus, and nothing reached any terminal's program + +#### Scenario: No current terminal +- **WHEN** the selected worktree has no terminals and the user clicks an empty part of the terminal area +- **THEN** no terminal takes the keyboard focus + ### Requirement: Preset picker The page SHALL keep the presets the hub sent for the session and forget them when the session closes. Starting a new terminal SHALL open a picker listing the presets in order, over the terminal area, for the selected worktree and the requested operation; with exactly one preset it SHALL use that preset without showing the picker. Digits 1–9 SHALL choose the preset at that position; arrow keys and Enter SHALL move and choose; Escape or a click outside SHALL cancel without creating anything. The picker SHALL close without creating anything when the selected worktree changes, its host leaves `connected`, the pane it would split closes, or the operation is no longer possible; choosing SHALL check again that the operation is possible. A worktree without terminals SHALL show the same list in the terminal area, choosable by click, digits or arrows and Enter. In either list, the repeats of a held digit or Enter SHALL choose nothing; the repeats of a held arrow key SHALL keep moving. @@ -425,13 +497,14 @@ Each pane SHALL have a close control that closes its terminal, and Ctrl+Shift+W ### Requirement: Keyboard shortcuts The page SHALL handle these shortcuts whether the keyboard focus is in a terminal or elsewhere on the page, except while a picker or dialog is open or text is being composed with an input method; a handled shortcut SHALL act once per key press, SHALL NOT reach the terminal's program, and SHALL suppress the browser's own action: - Alt+Up / Alt+Down: select the previous / next worktree as listed in the sidebar under the current filter, doing nothing at either end. -- Alt+Left / Alt+Right: choose the previous / next terminal tab, doing nothing at either end. +- Alt+Left / Alt+Right: select the previous / next repo tab in the order the tabs are shown, doing nothing at either end. +- Ctrl+Shift+Left / Ctrl+Shift+Right: choose the previous / next terminal tab, doing nothing at either end. - Alt+Shift+Left/Right/Up/Down: focus the pane in that direction — among panes lying wholly beyond the focused pane's edge on that side, the one overlapping it most along the other axis, then the nearest, then the first in the tab's order; nothing when there is none. - Ctrl+Shift+T: new tab; Ctrl+Shift+D: split right; Ctrl+Shift+E: split down; each through the preset picker and only when the corresponding control is enabled. - Ctrl+Shift+W: close the focused pane, as specified for closing terminals. - Ctrl+Shift+C: copy the focused terminal's selection to the clipboard; nothing without a selection; a failed copy SHALL be reported on the page. - Ctrl+Shift+V: paste the clipboard into the focused terminal as pasted text; the browser's paste SHALL be let through to the terminal. -Holding a navigation shortcut SHALL repeat it; holding any other shortcut SHALL act once. +Holding a navigation shortcut (worktree, repo tab, terminal tab or pane) SHALL repeat it; holding any other shortcut SHALL act once. #### Scenario: Worktree navigation respects the filter - **WHEN** the filter is "checked only" and the user presses Alt+Down @@ -441,8 +514,16 @@ Holding a navigation shortcut SHALL repeat it; holding any other shortcut SHALL - **WHEN** the last listed worktree is selected and the user presses Alt+Down - **THEN** the selection does not change +#### Scenario: Navigation keeps the keyboard in the terminal +- **WHEN** a terminal has the keyboard focus and the user presses Alt+Down onto a worktree that has a terminal, then types text +- **THEN** that worktree's current terminal has the keyboard focus and the text reaches it + +#### Scenario: Repo navigation +- **WHEN** the first of three repo tabs is selected and the user presses Alt+Right twice, then once more +- **THEN** the third repo tab is selected, its current terminal has the keyboard focus, and the last press changes nothing + #### Scenario: Tab navigation -- **WHEN** the first of three terminal tabs is active and the user presses Alt+Right twice +- **WHEN** the first of three terminal tabs is active and the user presses Ctrl+Shift+Right twice - **THEN** the third tab is active #### Scenario: Pane navigation @@ -450,7 +531,7 @@ Holding a navigation shortcut SHALL repeat it; holding any other shortcut SHALL - **THEN** the left pane is focused and then the bottom-right pane, the one overlapping the left pane most #### Scenario: Shortcut does not reach the program -- **WHEN** a terminal running `cat -v` is focused and the user presses Alt+Up +- **WHEN** a terminal running `cat -v` is focused and the user presses Alt+Up, Alt+Left or Ctrl+Shift+Left - **THEN** nothing is echoed by `cat` #### Scenario: Copy and paste