diff --git a/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/.openspec.yaml b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/.openspec.yaml new file mode 100644 index 0000000..55ab199 --- /dev/null +++ b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/design.md b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/design.md new file mode 100644 index 0000000..30103b7 --- /dev/null +++ b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/design.md @@ -0,0 +1,44 @@ +## Context + +Two unrelated places decide the keyboard focus in the terminal area: `View`'s focus effect gives it to the focused pane, and `PresetChoices` decides once at mount from `emptied && activeElement === body`, with `TerminalArea` tracking `last`/`emptied` to know whether the worktree just lost its last terminal. `PresetChoices` is not keyed, so switching between two worktrees without terminals keeps its highlight and never decides again. `PresetList` refocuses its highlighted option after every index or order change once shown, which pulls the focus out of its own add form when another page reorders presets. The `PresetList` key handler consumes Alt+Up/Down for reordering, so in the choices they never reach the page's worktree shortcuts. + +Architecture: element `typescript.web` (`ui`). Applicable principles: web 1 (no Node APIs), web 3 (`terminals` never depends on `ui`; `ui` may call `manager.owns`), web 4 (terminals never re-created), web 5 (switching makes no network round trip; focus is local), system 1–2 (imports via `index.ts`), system 4 (strict compiler/lint), system 8 (unit beside the code, e2e in `test/e2e`). No model, arc42 or `index.yaml` change; the delta stays in the `web` spec. + +## Goals / Non-Goals + +**Goals:** +- One focus policy for both preset lists, decided by pure functions in `picker.ts` and applied in `PresetList`; the `emptied` machinery is deleted. +- Every path that shows a worktree's choices behaves the same. + +**Non-Goals:** +- A pane taking the focus from a text field (`View` focus effect, e.g. another page creating a terminal while the user types in the search) is unchanged. +- No component-level DOM test tier (jsdom); DOM focus behaviour is covered by Playwright. +- The picker's focus on open is unchanged: it takes the focus from anywhere, the search included. + +## Decisions + +1. **Structural fix over a patched condition.** The focus decision moves into `picker.ts` and `PresetList`, replacing the mount-time `emptied` check and the `last` ref in `TerminalArea`. Alternative: widen the `PresetChoices` condition — keeps two code paths that must agree by hand. (default) +2. **Alt+Up/Down in the choices act as worktree shortcuts; keyboard reordering only in the picker; dragging in both.** Options: (A) this; (B) keep reordering in the choices — navigation stalls at every empty worktree and silently reorders the hub's presets; (C) a new reorder key in both lists — changes an existing binding. A matches the "Keyboard shortcuts" requirement (shortcuts work everywhere except while a picker or dialog is open). (user: deferred to the recommendation, A) +3. **The choices take the focus when shown, and again when a picker or dialog over them closes; never from a text field.** Option: only on first showing — leaves Escape-out-of-the-picker with dead keys. (user) +4. **Repeats of a held digit or Enter choose nothing in either list; held arrows keep moving.** Guards "no terminal SHALL be created without the user choosing one" against a held Enter that selected the worktree, or one that ended the last terminal, landing in the newly focused list. Option: no guard. (user) +5. **Text field** = an `input` of type `text`, `search`, `email`, `url`, `tel`, `password` or `number`, a `textarea`, or an element inside an editable (contenteditable) ancestor; an element the terminal manager owns (`manager.owns`, checked first) is a terminal, never a text field. The classifier works on a plain description of the active element (tag, type, editable, owned by a terminal) so it is unit-testable without a DOM. (default; precision from codex) +6. **Choices keyed per worktree** on the `PresetChoices` vnode in `TerminalArea`, key `` `${host}\n${repo}\n${worktree}` ``: each showing is a fresh mount with the first preset highlighted; an open add form closes on a switch. A reconnect that briefly unmounts the choices (`canCreate` false or presets null) loses an open form, as today; on return they take the focus unless it is in a text field. (default; key placement from codex) +7. **Picker focus on open unchanged.** (default) +8. **Explicit focus triggers.** The pure decision (`choicesTakeFocus`) only judges whether the current focus may be taken; when it is consulted is fixed by `PresetList`/`PresetChoices`: on mount, and on the falling edge of `view.modal` (true → false). Ordinary re-renders and preset updates never consult it. (codex) +9. **After a modal closes, the choices take the focus only when it is on the page body.** Options: (A) only from the body; (B) from anything but a text field — would pull the focus from a control the user just clicked to dismiss a menu (e.g. the Starred switch). (user, A; raised by codex) +10. **Refocus after an index or order change only if the list held the focus**, read as `list.contains(document.activeElement)` during the render, before the DOM changes — not a sticky flag. A removed highlighted preset clamps the index and focuses the surviving option under the same condition. (default; precision from codex) +11. **Closing the add form returns the focus to the list's highlighted preset**, in both lists, for Escape, Cancel and a resolved submit; a refused or failed submit keeps the focus in the form. `PresetAdder` only reports the close; the parent's layout effect focuses after the form has left the DOM, avoiding a race with Preact's commit. (user approved the extension; scheduling from codex) +12. **Alt+Up/Down in the choices pass through untouched**: no `preventDefault`, no `stopPropagation`, not consumed by `pickerKey`, so the document listener in `src/web/main/index.ts` navigates once per press with the existing repeat semantics. (codex) +13. **`pickerKey` takes the key press's `repeat`**; the existing `pickerKey` unit-test calls are aligned to the new signature. (user approved with the spec) +14. **Acceptance e2e asserts every step**: first option focused and selected once shown, second after ArrowDown, exactly one `createTerm` for the second preset in that worktree after Enter. (codex) +15. **Race e2e scenarios added**: presets arriving after a reconnect while the search has the focus; a close dialog for the last terminal ending by itself when another page closes the terminal. (codex) +16. Rejected (codex): drop the held-key guard as out of scope and as contradicting "number keys keep working as before" — the user chose it, single presses are unchanged, and a creation guard in `View` would not stop the first, accidental creation. +17. Rejected (codex): add component-level DOM tests — the repo's tiers are pure unit tests plus Playwright, and every focus scenario is asserted on the real active element in e2e. +18. Rejected (codex): narrow the spec to the issue's wording — the user approved both widenings (decisions 3 and 4). + +## Risks / Trade-offs + +- [The xterm helper textarea of a hidden terminal is still the active element after Alt+Down] → `manager.owns` is checked before the text-field test, so it counts as a terminal and the focus is taken. +- [Preact renders signal updates in a microtask, so Enter on a worktree label moves the focus into the list before the key repeats] → decision 4. +- [A keyed reorder can blur the focused option before the effect runs] → decision 10 reads the containment during render, before the DOM changes. +- [The two lists now differ for Alt+Up/Down] → the picker is modal (global shortcuts are off there); dragging still reorders in the choices. diff --git a/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/proposal.md b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/proposal.md new file mode 100644 index 0000000..aa1a557 --- /dev/null +++ b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/proposal.md @@ -0,0 +1,24 @@ +## Why + +A worktree without terminals shows its preset choices ("Start a terminal"), but they take the keyboard focus only after the worktree's last terminal closed with the focus left on the page body. Selecting such a worktree by click, keyboard navigation or a repo-tab switch leaves ↑/↓/Enter dead until the user clicks into the choices. + +## What Changes + +- The choices take the keyboard focus, on their first preset, every time they are shown for a worktree, unless the focus is in a text field of the page other than a terminal; they take it again when a picker or dialog over them closes and leaves the focus on the page body. +- Each showing of a worktree's choices starts with its first preset highlighted. +- In either preset list, a change to the presets never moves the focus out of the add form; closing the add form returns the focus to the list's highlighted preset. +- In a worktree's choices, Alt+Up / Alt+Down act as the page's worktree shortcuts; keyboard reordering of presets stays in the picker. Dragging still reorders in both lists. +- In either preset list, the repeats of a held digit or Enter choose nothing. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `web`: "Terminal tabs" (when the choices take the focus), "Preset picker" (held keys), "Editing presets" (Alt+Up/Down only in the picker; focus around the add form). + +## Impact + +- `src/web/ui/picker.ts` (key and focus decisions), `src/web/ui/app.tsx` (`PresetList`, `PresetAdder`, `PresetChoices`, `TerminalArea`). +- Tests: `src/web/ui/picker.test.ts`, `test/e2e/terminals.spec.ts`, `test/e2e/picker.spec.ts`. +- No protocol, hub or daemon change; no new dependency; no architecture model or arc42 change. diff --git a/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/specs/web/spec.md b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/specs/web/spec.md new file mode 100644 index 0000000..65cb7cc --- /dev/null +++ b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/specs/web/spec.md @@ -0,0 +1,175 @@ +## MODIFIED Requirements + +### Requirement: Terminal tabs +The terminal area SHALL show the selected worktree's layout tabs, each labelled by its name, or without a name by its first terminal, with the layout's active tab shown and its tab shown in the accent colour; live terminals of the worktree missing from its layout SHALL be shown as further single-pane tabs. Choosing a tab SHALL show it at once and then store it as active with `setLayout`. The tab bar SHALL offer controls to create a new tab, split the focused pane right and split it down, each naming its keyboard shortcut on hover and each starting a new terminal through the preset picker; the new-tab control SHALL sit directly after the last tab, or at the left end of the tab bar when there are no tabs, and the split controls at the tab bar's right end; when the tabs overflow the tab bar they SHALL scroll horizontally while all three controls stay fully visible and usable, without making the tab bar taller; the split controls SHALL be disabled when the focused pane's tab cannot be split further, the new-tab control when the layout holds 64 tabs, and all of them while the host is not `connected`, the worktree is prunable or gone, or no presets have been received. Double-clicking a tab, outside its close button, SHALL replace its label with a text field holding the label's text without its exit note and marks, selected and focused; keys typed in the field SHALL reach only the field. Enter or the field losing focus SHALL close the field and, unless the trimmed text equals the text it started with, store it, at most 64 characters, as the tab's name with exactly one `setLayout`, an empty text removing the name; Escape SHALL close the field and store nothing. Each edit SHALL end exactly once, however Enter, Escape and the loss of focus follow one another. Renaming a tab missing from the layout SHALL add it to the layout as choosing it does; such a tab SHALL NOT be renamable while the layout holds 64 tabs. A new tab SHALL send `createTerm` with the chosen preset's name and command and the size of the terminal area, then add the terminal as a new active tab with `setLayout`. A terminal SHALL never be created again because a request failed or the session closed. The tab of a terminal whose process failed, and its pane header in a split, SHALL show that it exited and keep its screen readable until closed; a terminal whose process exited cleanly SHALL leave the tabs of every page, as any closed terminal does. A worktree without terminals SHALL show the presets as choices in the terminal area; no terminal SHALL be created without the user choosing one. Each time a worktree's choices are shown, their first preset SHALL be highlighted. When the choices are shown they SHALL take the keyboard focus, on their highlighted preset, unless the keyboard focus is in a text field of the page other than a terminal; when a picker or dialog over them closes and leaves the keyboard focus on the page body, they SHALL take it again. Showing the choices SHALL NOT otherwise move the keyboard focus. + +#### Scenario: New terminal +- **WHEN** the user picks a preset in a worktree without terminals +- **THEN** that preset runs in that worktree's directory, its tab is active, and it is listed in the layout of every page + +#### Scenario: Terminal without a layout tab still shown +- **WHEN** a live terminal of the worktree is missing from its layout +- **THEN** it is shown as a tab + +#### Scenario: Created terminal survives a lost layout write +- **WHEN** the session closes after a terminal is created and before its `setLayout` is answered +- **THEN** after reconnecting the terminal is shown as a tab, and no second terminal was created + +#### Scenario: Exited terminal +- **WHEN** the shell in a terminal runs `exit 1` +- **THEN** its tab shows that it exited and its screen stays readable until it is closed + +#### Scenario: Clean exit closes the tab +- **WHEN** the shell in one of a worktree's two single-pane tabs runs `exit` +- **THEN** its tab disappears from every page showing the worktree and the remaining tab is shown + +#### Scenario: Last terminal leaves the choices +- **WHEN** the user types `exit` in the only terminal of the selected worktree and then presses 1 +- **THEN** the preset choices are shown, and the first preset starts as a new terminal of that worktree + +#### Scenario: Confirmed close leaves the choices focused +- **WHEN** the user closes the only, running, terminal of the selected worktree, confirms, and then presses 1 +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Choices leave the focus elsewhere alone +- **WHEN** the only terminal of the selected worktree exits cleanly while the keyboard focus is in the worktree search +- **THEN** the preset choices are shown and the search keeps the keyboard focus + +#### Scenario: Choices focused on selection +- **WHEN** the user clicks a worktree without terminals in the sidebar, then presses ArrowDown and Enter +- **THEN** the first preset is highlighted and focused once the choices are shown, then the second, and exactly one `createTerm` is sent, for the second preset in that worktree + +#### Scenario: Choices focused after worktree navigation +- **WHEN** a terminal has the keyboard focus, the user presses Alt+Down onto a worktree without terminals and then presses Enter +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Choices focused after a repo switch +- **WHEN** the user selects a repo tab whose selected worktree has no terminals and then presses Enter +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Each showing starts at the first preset +- **WHEN** the user highlights the second preset in the choices of one worktree without terminals and then selects another worktree without terminals +- **THEN** the other worktree's choices show the first preset highlighted and focused + +#### Scenario: Choices focused again after the picker +- **WHEN** the selected worktree has no terminals and the user presses Ctrl+Shift+T, then Escape, then Enter +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Choices focused after a close dialog ends by itself +- **WHEN** the close dialog for the only, running, terminal of the selected worktree is open and another page closes that terminal +- **THEN** the dialog closes, the preset choices are shown with their first preset focused, and Enter starts it in that worktree + +#### Scenario: Presets arriving after a reconnect leave the search focused +- **WHEN** the selected worktree has no terminals, the keyboard focus is in the worktree search, and the session closes and reconnects +- **THEN** the preset choices are shown again and the search keeps the keyboard focus + +#### Scenario: New-tab control follows the last tab +- **WHEN** the selected worktree shows two tabs and the user opens a third, then closes it +- **THEN** the new-tab control sits directly after the last tab each time, and the split controls stay at the tab bar's right end + +#### Scenario: New-tab control without tabs +- **WHEN** the selected worktree has no terminals +- **THEN** the new-tab control sits at the left end of the tab bar and the split controls at its right end + +#### Scenario: Overflowing tabs keep the controls visible +- **WHEN** the selected worktree shows more tabs than fit in the tab bar +- **THEN** the tabs scroll horizontally, the tab bar keeps its height, and the new-tab and split controls stay fully visible and clickable at either end of the scroll + +#### Scenario: Rename a tab +- **WHEN** the user double-clicks a tab, types "build server" and presses Enter +- **THEN** exactly one `setLayout` names the tab "build server", and the tab is labelled "build server" on every page showing the worktree, and still after a reload + +#### Scenario: Rename by leaving the field +- **WHEN** the user double-clicks a tab, types "logs" and clicks elsewhere on the page +- **THEN** the tab is labelled "logs" + +#### Scenario: Escape keeps the name +- **WHEN** the user double-clicks a tab named "logs", types "other" and presses Escape +- **THEN** the tab is still labelled "logs" on every page, and no `setLayout` changes its name + +#### Scenario: Unchanged label stores no name +- **WHEN** the user double-clicks an unnamed tab of an exited terminal and presses Enter without typing +- **THEN** the tab stays unnamed and its label still shows that it exited + +#### Scenario: Clearing the name +- **WHEN** the user double-clicks a tab named "logs", clears the field and presses Enter +- **THEN** the tab is labelled by its first terminal again and the stored tab has no name + +#### Scenario: Typing in the field stays in the field +- **WHEN** the user renames a tab and types a space, Ctrl+Shift+T and letters into the field +- **THEN** the characters go into the field, no tab is chosen or created, and the terminal receives no input + +#### Scenario: Renaming a tab missing from the layout +- **WHEN** the user renames a tab whose live terminal is missing from the layout +- **THEN** the tab is added to the layout with that name + +#### Scenario: Name kept when a pane closes +- **WHEN** one terminal of a split tab named "build" is closed +- **THEN** the remaining tab is still labelled "build" + +### 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. + +#### Scenario: Held Enter starts nothing +- **WHEN** the user focuses the label of a worktree without terminals and holds Enter until it repeats +- **THEN** that worktree is selected, its choices are shown, and no `createTerm` is sent + +#### Scenario: Picker chooses a preset +- **WHEN** two presets are configured and the user presses Ctrl+Shift+T and then 2 +- **THEN** a terminal running the second preset's command opens as a new active tab + +#### Scenario: Single preset skips the picker +- **WHEN** only one preset is configured and the user presses Ctrl+Shift+T +- **THEN** a terminal with that preset opens without a picker + +#### Scenario: Escape cancels +- **WHEN** the picker is open and the user presses Escape +- **THEN** the picker closes and no `createTerm` is sent + +#### Scenario: Worktree switch cancels +- **WHEN** the picker is open and the user selects another worktree +- **THEN** the picker closes and no `createTerm` is sent + +### Requirement: Editing presets +The preset picker and a worktree's preset choices SHALL offer "+ Add preset", opening a form for a name and a command; submitting SHALL trim both, treat an empty command as the login shell (`command` null) and send `addPreset`, closing the form on `done` and showing the refusal in the form otherwise. A blank name, a name of more than 64 characters, a name already taken, or a command of more than 4096 characters SHALL be refused in the form without sending anything; Escape SHALL close the form without sending anything and without closing the picker. While more than one preset exists, each SHALL offer a remove control sending `removePreset` for it; a refusal SHALL be shown on the page. While more than one preset exists, each SHALL be draggable to another position, the gap it would be dropped into marked while dragging, and dropping it elsewhere SHALL send `movePreset` with its new position; in the picker, Alt+Up and Alt+Down SHALL move the highlighted preset one position, which stays highlighted and focused; until the new order arrives, or the move fails, further keyboard moves SHALL be ignored, so each moves the preset that is highlighted. In a worktree's choices, Alt+Up and Alt+Down SHALL act as the worktree shortcuts. Every list SHALL show the presets the hub last sent, and the picker SHALL stay open while presets are edited. A change to the presets SHALL NOT move the keyboard focus out of the add form, and SHALL keep it on the list's highlighted preset when the list had it; closing the add form SHALL return the keyboard focus to the list's highlighted preset. + +#### Scenario: Alt+Down in the choices selects the next worktree +- **WHEN** the choices of a worktree without terminals have the keyboard focus and the user presses Alt+Down once +- **THEN** the next listed worktree is selected, exactly one worktree further, and the presets keep their order with no `movePreset` sent + +#### Scenario: Add form keeps the focus while presets change +- **WHEN** the add form is open in a worktree's choices with the keyboard focus in its name field and another page moves a preset +- **THEN** the list shows the new order and the name field keeps the keyboard focus + +#### Scenario: Escape returns the focus to the list +- **WHEN** the user opens the add form in a worktree's choices, presses Escape and then Enter +- **THEN** the form closes and the first preset starts as a new terminal of that worktree + +#### Scenario: Preset added from the choices +- **WHEN** the user adds a preset `echo` with a command in a worktree's preset choices while another page is open +- **THEN** `addPreset` is sent once, both pages list `echo` last, `config.json` lists it, and choosing it runs its command + +#### Scenario: Preset added in the picker +- **WHEN** the user adds a preset in the new-tab picker +- **THEN** the picker stays open, lists the new preset, and choosing it opens a terminal running it + +#### Scenario: Preset removed +- **WHEN** the user removes one of two presets +- **THEN** `removePreset` is sent, every page lists only the other preset, `config.json` lists only it, and no remove control is offered any more + +#### Scenario: Taken name refused in the form +- **WHEN** the user submits a name that a preset already has, or a blank name +- **THEN** the form says why, nothing is sent, and Escape then closes the form + +#### Scenario: Preset dragged to the front +- **WHEN** the user drags the second of two presets onto the upper half of the first in a worktree's choices while another page is open +- **THEN** `movePreset` is sent with position 0, and both pages and `config.json` list the dragged preset first + +#### Scenario: Quick keyboard moves +- **WHEN** the first of three presets is highlighted and the user presses Alt+Down twice in quick succession +- **THEN** only that preset moves, by one or two positions + +#### Scenario: Preset moved with the keyboard +- **WHEN** the second preset is highlighted in the new-tab picker and the user presses Alt+Up and then Enter +- **THEN** it is listed first, still highlighted and focused, and a terminal running it opens + diff --git a/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/tasks.md b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/tasks.md new file mode 100644 index 0000000..b614b20 --- /dev/null +++ b/openspec/changes/archive/2026-11-13-dev-2278-worktree-term-the-start-a-terminal-preset/tasks.md @@ -0,0 +1,15 @@ +## 1. Tests (pr-tests) + +- [x] 1.1 `src/web/ui/picker.test.ts`: align the existing `pickerKey` calls to the new `repeat` argument (design.md decision 13); add the held-key matrix (repeated digit or Enter → null; repeated ArrowUp/ArrowDown → move; first presses unchanged); verify they fail before 2.1. +- [x] 1.2 `src/web/ui/picker.test.ts`: unit tests for the focus-spot classifier (decision 5: each text input type, non-text inputs such as checkbox and button, textarea, editable ancestor, terminal-owned textarea → terminal, nothing → none) and for `choicesTakeFocus` (decisions 3, 8, 9: on show from none/terminal/other but not textField; after a modal closes only from none; never while a modal is open); verify they fail before 2.1. +- [x] 1.3 `test/e2e/terminals.spec.ts`: one test per new "Terminal tabs" scenario — the acceptance flow asserting focus and `aria-selected` at each step and exactly one `createTerm` (decision 14), Alt+Down from a terminal, repo-tab switch, each showing starts at the first preset, focus back after the picker's Escape, close dialog ending by itself, reconnect with the search focused (decision 15); keep the existing three choices-focus tests passing. +- [x] 1.4 `test/e2e/picker.spec.ts`: "Held Enter starts nothing" (hold via repeated `keyboard.down('Enter')` with repeat), "Alt+Down in the choices selects the next worktree" (exactly one step, no `movePreset`), "Add form keeps the focus while presets change", "Escape returns the focus to the list"; existing picker keyboard-reorder tests stay as they are. + +## 2. Implementation (pr-implement) + +- [x] 2.1 `src/web/ui/picker.ts`: `pickerKey` with `repeat`; the focus-spot classifier over a plain element description; `choicesTakeFocus`; verify 1.1 and 1.2 pass. +- [x] 2.2 `src/web/ui/app.tsx`: `PresetList` — reorder keys only when enabled (picker), Alt+Up/Down untouched otherwise (decision 12); refocus after an index/order change only when the list held the focus at render (decision 10); focus on mount when told to. `PresetAdder` reports closing; the parent's layout effect refocuses the highlighted option after the form left the DOM (decision 11). `PresetChoices` decides at mount and on the falling edge of `view.modal` via `choicesTakeFocus` (decisions 8, 9). `TerminalArea` keys `PresetChoices` per host/repo/worktree (decision 6) and drops `last`/`emptied`. Verify 1.3 and 1.4 pass. + +## 3. Verification + +- [x] 3.1 Run `pnpm test` (all default tiers), `pnpm lint`, `tsc -b`, `la-arch-check` and the LikeC4 validation; all green. diff --git a/openspec/specs/web/spec.md b/openspec/specs/web/spec.md index 001804c..2d24c6c 100644 --- a/openspec/specs/web/spec.md +++ b/openspec/specs/web/spec.md @@ -131,7 +131,7 @@ The selected repo tab and each repo's selected worktree SHALL be stored per brow - **THEN** the second repo tab and that worktree are selected ### Requirement: Terminal tabs -The terminal area SHALL show the selected worktree's layout tabs, each labelled by its name, or without a name by its first terminal, with the layout's active tab shown and its tab shown in the accent colour; live terminals of the worktree missing from its layout SHALL be shown as further single-pane tabs. Choosing a tab SHALL show it at once and then store it as active with `setLayout`. The tab bar SHALL offer controls to create a new tab, split the focused pane right and split it down, each naming its keyboard shortcut on hover and each starting a new terminal through the preset picker; the new-tab control SHALL sit directly after the last tab, or at the left end of the tab bar when there are no tabs, and the split controls at the tab bar's right end; when the tabs overflow the tab bar they SHALL scroll horizontally while all three controls stay fully visible and usable, without making the tab bar taller; the split controls SHALL be disabled when the focused pane's tab cannot be split further, the new-tab control when the layout holds 64 tabs, and all of them while the host is not `connected`, the worktree is prunable or gone, or no presets have been received. Double-clicking a tab, outside its close button, SHALL replace its label with a text field holding the label's text without its exit note and marks, selected and focused; keys typed in the field SHALL reach only the field. Enter or the field losing focus SHALL close the field and, unless the trimmed text equals the text it started with, store it, at most 64 characters, as the tab's name with exactly one `setLayout`, an empty text removing the name; Escape SHALL close the field and store nothing. Each edit SHALL end exactly once, however Enter, Escape and the loss of focus follow one another. Renaming a tab missing from the layout SHALL add it to the layout as choosing it does; such a tab SHALL NOT be renamable while the layout holds 64 tabs. A new tab SHALL send `createTerm` with the chosen preset's name and command and the size of the terminal area, then add the terminal as a new active tab with `setLayout`. A terminal SHALL never be created again because a request failed or the session closed. The tab of a terminal whose process failed, and its pane header in a split, SHALL show that it exited and keep its screen readable until closed; a terminal whose process exited cleanly SHALL leave the tabs of every page, as any closed terminal does. A worktree without terminals SHALL show the presets as choices in the terminal area; no terminal SHALL be created without the user choosing one. When the selected worktree's last terminal closes and the keyboard focus is left on the page body, the choices SHALL take the keyboard focus on their first preset; otherwise showing them SHALL NOT move the keyboard focus. +The terminal area SHALL show the selected worktree's layout tabs, each labelled by its name, or without a name by its first terminal, with the layout's active tab shown and its tab shown in the accent colour; live terminals of the worktree missing from its layout SHALL be shown as further single-pane tabs. Choosing a tab SHALL show it at once and then store it as active with `setLayout`. The tab bar SHALL offer controls to create a new tab, split the focused pane right and split it down, each naming its keyboard shortcut on hover and each starting a new terminal through the preset picker; the new-tab control SHALL sit directly after the last tab, or at the left end of the tab bar when there are no tabs, and the split controls at the tab bar's right end; when the tabs overflow the tab bar they SHALL scroll horizontally while all three controls stay fully visible and usable, without making the tab bar taller; the split controls SHALL be disabled when the focused pane's tab cannot be split further, the new-tab control when the layout holds 64 tabs, and all of them while the host is not `connected`, the worktree is prunable or gone, or no presets have been received. Double-clicking a tab, outside its close button, SHALL replace its label with a text field holding the label's text without its exit note and marks, selected and focused; keys typed in the field SHALL reach only the field. Enter or the field losing focus SHALL close the field and, unless the trimmed text equals the text it started with, store it, at most 64 characters, as the tab's name with exactly one `setLayout`, an empty text removing the name; Escape SHALL close the field and store nothing. Each edit SHALL end exactly once, however Enter, Escape and the loss of focus follow one another. Renaming a tab missing from the layout SHALL add it to the layout as choosing it does; such a tab SHALL NOT be renamable while the layout holds 64 tabs. A new tab SHALL send `createTerm` with the chosen preset's name and command and the size of the terminal area, then add the terminal as a new active tab with `setLayout`. A terminal SHALL never be created again because a request failed or the session closed. The tab of a terminal whose process failed, and its pane header in a split, SHALL show that it exited and keep its screen readable until closed; a terminal whose process exited cleanly SHALL leave the tabs of every page, as any closed terminal does. A worktree without terminals SHALL show the presets as choices in the terminal area; no terminal SHALL be created without the user choosing one. Each time a worktree's choices are shown, their first preset SHALL be highlighted. When the choices are shown they SHALL take the keyboard focus, on their highlighted preset, unless the keyboard focus is in a text field of the page other than a terminal or in an open menu; when a picker or dialog over them closes and leaves the keyboard focus on the page body, they SHALL take it again. Showing the choices SHALL NOT otherwise move the keyboard focus. #### Scenario: New terminal - **WHEN** the user picks a preset in a worktree without terminals @@ -165,6 +165,38 @@ The terminal area SHALL show the selected worktree's layout tabs, each labelled - **WHEN** the only terminal of the selected worktree exits cleanly while the keyboard focus is in the worktree search - **THEN** the preset choices are shown and the search keeps the keyboard focus +#### Scenario: Choices leave an open menu its focus +- **WHEN** the user opens the Hubs menu on a page whose selected worktree has no terminals, before its preset choices are shown +- **THEN** the preset choices are shown, the Hubs button keeps the keyboard focus, and Escape closes the menu + +#### Scenario: Choices focused on selection +- **WHEN** the user clicks a worktree without terminals in the sidebar, then presses ArrowDown and Enter +- **THEN** the first preset is highlighted and focused once the choices are shown, then the second, and exactly one `createTerm` is sent, for the second preset in that worktree + +#### Scenario: Choices focused after worktree navigation +- **WHEN** a terminal has the keyboard focus, the user presses Alt+Down onto a worktree without terminals and then presses Enter +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Choices focused after a repo switch +- **WHEN** the user selects a repo tab whose selected worktree has no terminals and then presses Enter +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Each showing starts at the first preset +- **WHEN** the user highlights the second preset in the choices of one worktree without terminals and then selects another worktree without terminals +- **THEN** the other worktree's choices show the first preset highlighted and focused + +#### Scenario: Choices focused again after the picker +- **WHEN** the selected worktree has no terminals and the user presses Ctrl+Shift+T, then Escape, then Enter +- **THEN** the first preset starts as a new terminal of that worktree + +#### Scenario: Choices focused after a close dialog ends by itself +- **WHEN** the close dialog for the only, running, terminal of the selected worktree is open and another page closes that terminal +- **THEN** the dialog closes, the preset choices are shown with their first preset focused, and Enter starts it in that worktree + +#### Scenario: Presets arriving after a reconnect leave the search focused +- **WHEN** the selected worktree has no terminals, the keyboard focus is in the worktree search, and the session closes and reconnects +- **THEN** the preset choices are shown again and the search keeps the keyboard focus + #### Scenario: New-tab control follows the last tab - **WHEN** the selected worktree shows two tabs and the user opens a third, then closes it - **THEN** the new-tab control sits directly after the last tab each time, and the split controls stay at the tab bar's right end @@ -345,7 +377,11 @@ Each tab SHALL have one focused pane, kept per page and not stored: the first pa - **THEN** the remaining pane is focused and receives typed input ### 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. +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. + +#### Scenario: Held Enter starts nothing +- **WHEN** the user focuses the label of a worktree without terminals and holds Enter until it repeats +- **THEN** that worktree is selected, its choices are shown, and no `createTerm` is sent #### Scenario: Picker chooses a preset - **WHEN** two presets are configured and the user presses Ctrl+Shift+T and then 2 @@ -539,7 +575,23 @@ The sidebar's right edge SHALL be a separator that the user can drag, and move b - **THEN** the sidebar is 384 px wide ### Requirement: Editing presets -The preset picker and a worktree's preset choices SHALL offer "+ Add preset", opening a form for a name and a command; submitting SHALL trim both, treat an empty command as the login shell (`command` null) and send `addPreset`, closing the form on `done` and showing the refusal in the form otherwise. A blank name, a name of more than 64 characters, a name already taken, or a command of more than 4096 characters SHALL be refused in the form without sending anything; Escape SHALL close the form without sending anything and without closing the picker. While more than one preset exists, each SHALL offer a remove control sending `removePreset` for it; a refusal SHALL be shown on the page. While more than one preset exists, each SHALL be draggable to another position, the gap it would be dropped into marked while dragging, and dropping it elsewhere SHALL send `movePreset` with its new position; Alt+Up and Alt+Down SHALL move the highlighted preset one position, which stays highlighted and focused; until the new order arrives, or the move fails, further keyboard moves SHALL be ignored, so each moves the preset that is highlighted. Every list SHALL show the presets the hub last sent, and the picker SHALL stay open while presets are edited. +The preset picker and a worktree's preset choices SHALL offer "+ Add preset", opening a form for a name and a command; submitting SHALL trim both, treat an empty command as the login shell (`command` null) and send `addPreset`, closing the form on `done` and showing the refusal in the form otherwise. A blank name, a name of more than 64 characters, a name already taken, or a command of more than 4096 characters SHALL be refused in the form without sending anything; Escape SHALL close the form without sending anything and without closing the picker. While more than one preset exists, each SHALL offer a remove control sending `removePreset` for it; a refusal SHALL be shown on the page. While more than one preset exists, each SHALL be draggable to another position, the gap it would be dropped into marked while dragging, and dropping it elsewhere SHALL send `movePreset` with its new position; in the picker, Alt+Up and Alt+Down SHALL move the highlighted preset one position, which stays highlighted and focused; until the new order arrives, or the move fails, further keyboard moves SHALL be ignored, so each moves the preset that is highlighted. In a worktree's choices, Alt+Up and Alt+Down SHALL act as the worktree shortcuts. Every list SHALL show the presets the hub last sent, and the picker SHALL stay open while presets are edited. A change to the presets SHALL NOT move the keyboard focus out of the add form, and SHALL keep it on the list's highlighted preset when the list had it; closing the add form SHALL return the keyboard focus to the list's highlighted preset while the keyboard focus is in the form or on the page body. + +#### Scenario: Alt+Down in the choices selects the next worktree +- **WHEN** the choices of a worktree without terminals have the keyboard focus and the user presses Alt+Down once +- **THEN** the next listed worktree is selected, exactly one worktree further, and the presets keep their order with no `movePreset` sent + +#### Scenario: Add form keeps the focus while presets change +- **WHEN** the add form is open in a worktree's choices with the keyboard focus in its name field and another page moves a preset +- **THEN** the list shows the new order and the name field keeps the keyboard focus + +#### Scenario: Escape returns the focus to the list +- **WHEN** the user opens the add form in a worktree's choices, presses Escape and then Enter +- **THEN** the form closes and the first preset starts as a new terminal of that worktree + +#### Scenario: A completed add leaves a dialog its focus +- **WHEN** an add is pending in a worktree's choices and the editor failure dialog takes the keyboard focus before the add is done +- **THEN** the form closes and the dialog keeps the keyboard focus #### Scenario: Preset added from the choices - **WHEN** the user adds a preset `echo` with a command in a worktree's preset choices while another page is open diff --git a/src/platform/scopes/scopes.test.ts b/src/platform/scopes/scopes.test.ts index 3e8994d..305dbfe 100644 --- a/src/platform/scopes/scopes.test.ts +++ b/src/platform/scopes/scopes.test.ts @@ -523,8 +523,8 @@ describe.skipIf(NO_USER_MANAGER !== null)(withUserManager('scopes of the real us it('resets the failed units with a prefix, and only those', async () => { const ours = `${unitPrefix(dir)}term-old-1.scope`; const theirs = `${unitPrefix(`${dir}/other`)}term-old-1.scope`; - failUnit(ours); - failUnit(theirs); + await failUnit(ours); + await failUnit(theirs); try { await resetFailedScopes(`${unitPrefix(dir)}term-`, report); expect(isFailed(ours)).toBe(false); diff --git a/src/web/ui/app.tsx b/src/web/ui/app.tsx index 9e748b4..904fcc7 100644 --- a/src/web/ui/app.tsx +++ b/src/web/ui/app.tsx @@ -8,7 +8,7 @@ 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 { dropPosition, pickerKey, presetFromForm } from './picker.js'; +import { choicesTakeFocus, dropPosition, focusSpot, pickerKey, presetFromForm, type FocusSpot } from './picker.js'; import { SIDEBAR_WIDTH, type SidebarEntry } from './sidebar.js'; import type { RepoTab } from './repo-tabs.js'; import { @@ -711,7 +711,7 @@ const messageOf = (error: unknown): string => (error instanceof Error ? error.me /** "Open in editor": opens the selected local worktree; a right-click, enabled or not, edits the command. */ const EditorControl = ({ client, view }: { client: HubClient; view: View }) => { const [pending, setPending] = useState(false); - const [failure, setFailure] = useState(null); + const failure = view.editorFailure.value; const [editing, setEditing] = useState(false); const worktree = view.worktree.value; const command = client.store.editor.value; @@ -734,7 +734,7 @@ const EditorControl = ({ client, view }: { client: HubClient; view: View }) => { .openEditor(worktree) .catch((error: unknown) => { const code = error instanceof RequestError ? error.code : null; - setFailure(editorFailure(code, messageOf(error), sent)); + view.editorFailure.value = editorFailure(code, messageOf(error), sent); }) .finally(() => { setPending(false); @@ -773,7 +773,7 @@ const EditorControl = ({ client, view }: { client: HubClient; view: View }) => { { - setFailure(null); + view.editorFailure.value = null; }} /> )} @@ -993,7 +993,8 @@ const PresetList = ({ cancel, remove, reorder, - focusFirst, + keyboardReorder, + focusRequest, }: { presets: readonly Preset[]; index: number; @@ -1002,22 +1003,30 @@ const PresetList = ({ cancel: () => void; /** Removes the named preset; offered while more than one is left. */ remove: (name: string) => void; - /** Moves the named preset to position `to`, by dragging or Alt+Up/Down; resolves with whether the hub did. */ + /** Moves the named preset to position `to`, by dragging or, with `keyboardReorder`, Alt+Up/Down; resolves with whether the hub did. */ reorder: (name: string, to: number) => Promise; - /** Whether the list takes the keyboard focus when shown; it follows the highlighted option once it has it. */ - focusFirst: boolean; + /** Whether Alt+Up/Down move the highlighted preset; otherwise they pass through untouched. */ + keyboardReorder: boolean; + /** While positive, focuses the highlighted option at mount and on each change. */ + focusRequest: number; }) => { const list = useRef(null); - const shown = useRef(false); /** The dragged preset's position and the gap it would be dropped into (0 = before the first). */ const [drag, setDrag] = useState<{ from: number; slot: number | null } | null>(null); const order = presets.map((p) => p.name).join('\n'); - // Before the browser handles the next key, so no key meant for the list reaches a terminal; again after a reorder. + const focusHighlighted = (): void => { + list.current?.querySelectorAll('[data-testid="preset-option"]')[index]?.focus(); + }; + // Read before this render changes the DOM: a keyed reorder or a removed option may blur the focused one. + const held = useRef(false); + held.current = list.current?.contains(document.activeElement) ?? false; + // Before the browser handles the next key, so no key meant for the list reaches a terminal. + useLayoutEffect(() => { + if (focusRequest > 0) focusHighlighted(); + }, [focusRequest]); useLayoutEffect(() => { - const options = list.current?.querySelectorAll('[data-testid="preset-option"]'); - if (focusFirst || shown.current) options?.[index]?.focus(); - shown.current = true; - }, [index, focusFirst, order]); + if (held.current) focusHighlighted(); + }, [index, order]); /** The order a keyboard move was sent from; further moves wait until the new order arrives or the move fails. */ const movingFrom = useRef(null); const moveBy = (step: number): void => { @@ -1042,13 +1051,18 @@ const PresetList = ({ ref={list} onKeyDown={(event) => { if (event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) { + if (!keyboardReorder) return; event.preventDefault(); event.stopPropagation(); moveBy(event.key === 'ArrowUp' ? -1 : 1); return; } - const key = pickerKey(event.key, index, presets.length); - if (key === null) return; + const key = pickerKey(event.key, index, presets.length, event.repeat); + if (key === null) { + // Else a held Enter's repeats click the focused option. + if (event.key === 'Enter') event.preventDefault(); + return; + } event.preventDefault(); event.stopPropagation(); if (key.t === 'choose') choose(key.index); @@ -1128,21 +1142,30 @@ const PresetList = ({ }; /** "+ Add preset", which opens a form for a new preset's name and command; Escape closes the form. */ -const PresetAdder = ({ view, presets }: { view: View; presets: readonly Preset[] }) => { +const PresetAdder = ({ view, presets, onClose }: { view: View; presets: readonly Preset[]; onClose: () => void }) => { const [open, setOpen] = useState(false); const [name, setName] = useState(''); const [command, setCommand] = useState(''); const [error, setError] = useState(null); const [sending, setSending] = useState(false); const nameInput = useRef(null); + const form = useRef(null); + /** Bumped on each close, so a submission completing later leaves the form alone. */ + const generation = useRef(0); useLayoutEffect(() => { if (open) nameInput.current?.focus(); }, [open]); + /** Closes the form; `onClose` returns the focus only from the form or the page body. */ const close = (): void => { + const active = document.activeElement; + const focusHere = active === null || active === document.body || form.current?.contains(active) === true; + generation.current++; setOpen(false); setName(''); setCommand(''); setError(null); + setSending(false); + if (focusHere) onClose(); }; if (!open) { return ( @@ -1160,6 +1183,7 @@ const PresetAdder = ({ view, presets }: { view: View; presets: readonly Preset[] } return (
{ @@ -1170,14 +1194,17 @@ const PresetAdder = ({ view, presets }: { view: View; presets: readonly Preset[] return; } setSending(true); - view - .addPreset(result.preset) - .then(close, (error_: unknown) => { + const mine = generation.current; + view.addPreset(result.preset).then( + () => { + if (generation.current === mine) close(); + }, + (error_: unknown) => { + if (generation.current !== mine) return; setError(error_ instanceof Error ? error_.message : String(error_)); - }) - .finally(() => { setSending(false); - }); + }, + ); }} onKeyDown={(event) => { if (event.key !== 'Escape') return; @@ -1225,6 +1252,7 @@ const PresetAdder = ({ view, presets }: { view: View; presets: readonly Preset[] /** The picker for a new terminal; any pointer press outside it cancels it. */ const PresetPicker = ({ view, presets }: { view: View; presets: readonly Preset[] }) => { const box = useRef(null); + const [focusRequest, setFocusRequest] = useState(1); const picker = view.picker.value; const open = picker !== null; useLayoutEffect(() => { @@ -1244,7 +1272,8 @@ const PresetPicker = ({ view, presets }: { view: View; presets: readonly Preset[ { view.movePicker(i); }} @@ -1259,23 +1288,56 @@ const PresetPicker = ({ view, presets }: { view: View; presets: readonly Preset[ }} reorder={(name, to) => view.movePreset(name, to)} /> - + { + setFocusRequest((n) => n + 1); + }} + /> ); }; -/** The presets a worktree without terminals offers; with `emptied`, they take a keyboard focus left on the page body. */ -const PresetChoices = ({ view, presets, emptied }: { view: View; presets: readonly Preset[]; emptied: boolean }) => { +/** 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); - // Decided at mount, after the closed terminal's xterm left the document. - const [focus] = useState(() => emptied && (document.activeElement === null || document.activeElement === document.body)); + const [focusRequest, setFocusRequest] = useState(() => (choicesTakeFocus('shown', activeSpot(manager), view.modal.peek()) ? 1 : 0)); + const modal = view.modal.value; + const wasModal = useRef(modal); + useLayoutEffect(() => { + if (wasModal.current && !modal) { + // After this render flush, once the closed picker or dialog has left the DOM. + queueMicrotask(() => { + if (choicesTakeFocus('modalClosed', activeSpot(manager), view.modal.peek())) setFocusRequest((n) => n + 1); + }); + } + wasModal.current = modal; + }, [manager, view, modal]); return (
Start a terminal
{ const preset = presets[i]; @@ -1287,7 +1349,13 @@ const PresetChoices = ({ view, presets, emptied }: { view: View; presets: readon }} reorder={(name, to) => view.movePreset(name, to)} /> - + { + setFocusRequest((n) => n + 1); + }} + />
); }; @@ -1363,13 +1431,8 @@ const TerminalArea = ({ client, manager, view }: AppProps) => { const presets = client.store.presets.value; const focused = view.focused.value; const empty = view.termTabs.value.tabs.length === 0; - const worktree = view.worktree.value; - /** The worktree and whether it was empty at the last render. */ - const last = useRef<{ worktree: string | null; empty: boolean }>({ worktree, empty }); - const emptied = empty && last.current.worktree === worktree && !last.current.empty; - useLayoutEffect(() => { - last.current = { worktree, empty }; - }); + const tab = view.tab.value; + const choicesKey = `${String(tab?.host)}\n${String(tab?.repo)}\n${String(view.worktree.value)}`; return (
{view.panes.value.map((pane) => ( @@ -1384,7 +1447,9 @@ const TerminalArea = ({ client, manager, view }: AppProps) => { {view.dividers.value.map((divider) => ( ))} - {empty && view.canCreate.value && presets !== null && } + {empty && view.canCreate.value && presets !== null && ( + + )} {presets !== null && }
); diff --git a/src/web/ui/picker.test.ts b/src/web/ui/picker.test.ts index 58f68f9..47f3421 100644 --- a/src/web/ui/picker.test.ts +++ b/src/web/ui/picker.test.ts @@ -1,6 +1,18 @@ import { describe, expect, it } from 'vitest'; import type { Layout } from '../../protocol/index.js'; -import { dropPosition, pickerKey, pickerValid, presetFromForm, type PickerContext, type PickerWorld } from './picker.js'; +import { + choicesTakeFocus, + dropPosition, + focusSpot, + pickerKey, + pickerValid, + presetFromForm, + type ChoicesTrigger, + type FocusedElement, + type FocusSpot, + type PickerContext, + type PickerWorld, +} from './picker.js'; type Pane = Layout['tabs'][number]['root']; @@ -81,31 +93,118 @@ describe('pickerValid', () => { describe('pickerKey', () => { it('chooses the preset at a digit’s position', () => { - expect(pickerKey('1', 0, 3)).toEqual({ t: 'choose', index: 0 }); - expect(pickerKey('3', 0, 3)).toEqual({ t: 'choose', index: 2 }); - expect(pickerKey('9', 4, 9)).toEqual({ t: 'choose', index: 8 }); + expect(pickerKey('1', 0, 3, false)).toEqual({ t: 'choose', index: 0 }); + expect(pickerKey('3', 0, 3, false)).toEqual({ t: 'choose', index: 2 }); + expect(pickerKey('9', 4, 9, false)).toEqual({ t: 'choose', index: 8 }); }); it('ignores a digit beyond the list and zero', () => { - expect(pickerKey('4', 0, 3)).toBeNull(); - expect(pickerKey('9', 0, 8)).toBeNull(); - expect(pickerKey('0', 0, 3)).toBeNull(); + expect(pickerKey('4', 0, 3, false)).toBeNull(); + expect(pickerKey('9', 0, 8, false)).toBeNull(); + expect(pickerKey('0', 0, 3, false)).toBeNull(); }); it('moves with the arrow keys within the list', () => { - expect(pickerKey('ArrowDown', 0, 3)).toEqual({ t: 'move', index: 1 }); - expect(pickerKey('ArrowDown', 2, 3)).toEqual({ t: 'move', index: 2 }); - expect(pickerKey('ArrowUp', 2, 3)).toEqual({ t: 'move', index: 1 }); - expect(pickerKey('ArrowUp', 0, 3)).toEqual({ t: 'move', index: 0 }); + expect(pickerKey('ArrowDown', 0, 3, false)).toEqual({ t: 'move', index: 1 }); + expect(pickerKey('ArrowDown', 2, 3, false)).toEqual({ t: 'move', index: 2 }); + expect(pickerKey('ArrowUp', 2, 3, false)).toEqual({ t: 'move', index: 1 }); + expect(pickerKey('ArrowUp', 0, 3, false)).toEqual({ t: 'move', index: 0 }); }); it('chooses the current preset with Enter and cancels with Escape', () => { - expect(pickerKey('Enter', 1, 3)).toEqual({ t: 'choose', index: 1 }); - expect(pickerKey('Escape', 1, 3)).toEqual({ t: 'cancel' }); + expect(pickerKey('Enter', 1, 3, false)).toEqual({ t: 'choose', index: 1 }); + expect(pickerKey('Escape', 1, 3, false)).toEqual({ t: 'cancel' }); }); it.each(['a', 'Tab', ' ', 'ArrowLeft', 'ArrowRight', 'Shift'])('ignores %j', (key) => { - expect(pickerKey(key, 0, 3)).toBeNull(); + expect(pickerKey(key, 0, 3, false)).toBeNull(); + }); + + it.each(['1', '2', '3', 'Enter'])('chooses nothing on a repeated %j', (key) => { + expect(pickerKey(key, 1, 3, true)).toBeNull(); + }); + + it('keeps moving on repeated arrow keys', () => { + expect(pickerKey('ArrowDown', 0, 3, true)).toEqual({ t: 'move', index: 1 }); + expect(pickerKey('ArrowDown', 2, 3, true)).toEqual({ t: 'move', index: 2 }); + expect(pickerKey('ArrowUp', 2, 3, true)).toEqual({ t: 'move', index: 1 }); + expect(pickerKey('ArrowUp', 0, 3, true)).toEqual({ t: 'move', index: 0 }); + }); +}); + +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); }); }); diff --git a/src/web/ui/picker.ts b/src/web/ui/picker.ts index 485f0b1..3d22b5b 100644 --- a/src/web/ui/picker.ts +++ b/src/web/ui/picker.ts @@ -33,11 +33,11 @@ export const pickerValid = (context: PickerContext, world: PickerWorld): boolean export type PickerKey = { t: 'choose'; index: number } | { t: 'move'; index: number } | { t: 'cancel' }; -/** What `key` does in a list of `count` presets whose highlighted one is `index`. */ -export const pickerKey = (key: string, index: number, count: number): PickerKey | null => { +/** What `key` does in a list of `count` presets whose highlighted one is `index`; a held key's repeats choose nothing. */ +export const pickerKey = (key: string, index: number, count: number, repeat: boolean): PickerKey | null => { if (/^[1-9]$/.test(key)) { const chosen = Number(key) - 1; - return chosen < count ? { t: 'choose', index: chosen } : null; + return chosen < count && !repeat ? { t: 'choose', index: chosen } : null; } switch (key) { case 'ArrowDown': @@ -45,7 +45,7 @@ export const pickerKey = (key: string, index: number, count: number): PickerKey case 'ArrowUp': return { t: 'move', index: Math.max(0, index - 1) }; case 'Enter': - return { t: 'choose', index }; + return repeat ? null : { t: 'choose', index }; case 'Escape': return { t: 'cancel' }; default: @@ -53,6 +53,43 @@ export const pickerKey = (key: string, index: number, count: number): PickerKey } }; +/** 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.ts b/src/web/ui/view.ts index 9aadb21..a330b9b 100644 --- a/src/web/ui/view.ts +++ b/src/web/ui/view.ts @@ -25,6 +25,7 @@ import { } from '../layout/index.js'; import type { Box, TerminalManager } from '../terminals/index.js'; import { closeTargets, needsConfirm } from './closing.js'; +import type { EditorFailure } from './editor.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'; @@ -209,6 +210,8 @@ export class View { readonly confirmation = signal(null); readonly worktreeMenu = signal(null); readonly addRepo = signal(null); + /** The failed editor launch the editor dialog shows. */ + readonly editorFailure = signal(null); private readonly drag = signal(null); /** The focused pane per tab key, with the tab's panes when it was last resolved; replaced when the user chooses a pane. */ private readonly focusRecords = signal(new Map()); @@ -355,7 +358,8 @@ export class View { this.closing.value !== null || this.confirmation.value !== null || this.addRepo.value !== null || - this.worktreeMenu.value !== null, + this.worktreeMenu.value !== null || + this.editorFailure.value !== null, ); private shownKey = ''; diff --git a/test/e2e/contract.ts b/test/e2e/contract.ts index a543d81..ca7a767 100644 --- a/test/e2e/contract.ts +++ b/test/e2e/contract.ts @@ -118,7 +118,7 @@ export const TID = { divider: 'divider', /** The preset picker over the terminal area. */ presetPicker: 'preset-picker', - /** The preset list a worktree without terminals shows in its terminal area; its first option takes the keyboard focus when the shown worktree's last terminal closed with the focus left on the page body. */ + /** The preset list a worktree without terminals shows in its terminal area; each showing highlights its first option and focuses it unless a text field other than a terminal has the focus. */ presetChoices: 'preset-choices', /** One preset in a picker or in the choices, in configured order; text = preset name; `aria-selected="true"` on the highlighted one. */ presetOption: 'preset-option', diff --git a/test/e2e/editor.spec.ts b/test/e2e/editor.spec.ts index 065802f..46fac86 100644 --- a/test/e2e/editor.spec.ts +++ b/test/e2e/editor.spec.ts @@ -6,9 +6,10 @@ import { addWorktree, fakeWorktrees, git, makeRepo } from '../support/daemon-hos import { installRemote } from '../support/fake-ssh.js'; import { freePort, type HubHost } from '../support/hub-host.js'; import { remoteHub } from '../support/remote-hub.js'; -import { byTestId, hubsEntry, repoTab, TID, worktreeEntry } from './contract.js'; +import { byTestId, hubsEntry, repoTab, terminalBox, TID, worktreeEntry } from './contract.js'; import { expect, + LOCAL, makeRepoWith, newTerminal, nodeRemote, @@ -20,8 +21,12 @@ import { selectWorktree, stopHub, test, + waitScreen, + watcher, writeHubConfig, } from './fixture.js'; +import { holdAddReplies } from './held-presets.js'; +import { pickerSeen, watchPicker } from './panes.js'; import type { BrowserMessage, HubMessage, WireRecorder } from './wire.js'; const ENABLED_TITLE = 'Open in editor (right-click to change the command)'; @@ -225,6 +230,74 @@ test.describe('open in editor', () => { await expect(control(page)).toBeEnabled(); }); + test('while the failure dialog is open shortcuts act not; once it closes, the terminal takes typed input', async ({ hub, page }) => { + const route = await routeEditor(page); + const { repo } = makeRepoWith(hub, 'app', []); + configure(hub, [repo], null); + await openUi(hub, page); + const term = await newTerminal(page); + await ready(page, term); + await control(page).click(); + route.answer({ t: 'error', req: await heldReq(route), host: null, code: 'editor-missing', message: 'kate' }); + await expect(dialog(page)).toBeFocused(); + + await watchPicker(page); + await page.keyboard.press('Control+Shift+KeyT'); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + expect(await pickerSeen(page)).toBe(false); + await expect(dialog(page)).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(dialog(page)).toHaveCount(0); + await page.keyboard.type("echo EDITOR''-CLOSED"); + await page.keyboard.press('Enter'); + await waitScreen(page, term, 'EDITOR-CLOSED'); + }); + + test('preset choices shown while the failure dialog is open leave it the focus, and take it once it closes', async ({ hub, page }) => { + const route = await routeEditor(page); + const { repo } = makeRepoWith(hub, 'app', []); + configure(hub, [repo], null); + await openUi(hub, page); + const daemon = await watcher(hub, repo); + const term = await daemon.create(repo, { command: 'read -r _; exit 0' }); + await expect(page.locator(terminalBox(LOCAL, term.termId))).toBeVisible(); + await control(page).click(); + route.answer({ t: 'error', req: await heldReq(route), host: null, code: 'editor-missing', message: 'kate' }); + await expect(dialog(page)).toBeFocused(); + + daemon.sendInput(term.termId, '\r'); + const options = page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetOption)); + await expect(options.nth(0)).toBeVisible(); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(dialog(page)).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(dialog(page)).toHaveCount(0); + await expect(options.nth(0)).toBeFocused(); + }); + + test('an add in the choices completing while the failure dialog is open closes its form and leaves the dialog the focus', async ({ + hub, + page, + }) => { + const adds = await holdAddReplies(page); + const { repo } = makeRepoWith(hub, 'app', []); + configure(hub, [repo]); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + await choices.locator(byTestId(TID.presetAdd)).click(); + await choices.locator(byTestId(TID.presetName)).fill('added'); + await choices.locator(byTestId(TID.presetCommand)).press('Enter'); + await expect.poll(() => adds.held()).toBe(1); + await control(page).click(); + await expect(dialog(page)).toBeFocused(); + + adds.release(); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(choices.locator(byTestId(TID.presetOption))).toHaveText([...PRESETS.map((p) => p.name), 'added']); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(dialog(page)).toBeFocused(); + }); + test('names the first word of the shown command as the missing program', async ({ hub, page }) => { const route = await routeEditor(page); const { repo } = makeRepoWith(hub, 'app', []); diff --git a/test/e2e/held-presets.ts b/test/e2e/held-presets.ts new file mode 100644 index 0000000..649aa79 --- /dev/null +++ b/test/e2e/held-presets.ts @@ -0,0 +1,161 @@ +import type { Page } from '@playwright/test'; +import { decodeMessage } from '../../src/protocol/index.js'; + +export interface Session { + /** Closes both sides of the session. */ + cut: () => void; + /** Whether the session holds back the hub's messages. */ + holding: () => boolean; + /** Delivers the held messages in order and passes later ones through. */ + release: () => void; +} + +export interface HeldPresets { + /** WebSocket sessions the page opened. */ + sessions: () => number; + /** The latest session. */ + current: () => Session; + /** `createTerm` requests the page sent over every session. */ + creates: () => number; +} + +export interface HeldMessage { + /** Whether the message is held back. */ + holding: () => boolean; + /** Delivers the held message. */ + release: () => void; +} + +/** Routes the page's WebSockets through the test, holding back only the hub's first `presets` message until released. */ +export const holdFirstPresets = async (page: Page): Promise => { + let held: string | null = null; + let seen = false; + let release = (): void => undefined; + await page.routeWebSocket( + (url) => url.pathname === '/ws', + (ws) => { + const server = ws.connectToServer(); + ws.onMessage((message) => { + server.send(message); + }); + server.onMessage((message) => { + if (!seen && typeof message === 'string' && decodeMessage('hubToBrowser', message).t === 'presets') { + seen = true; + held = message; + return; + } + ws.send(message); + }); + release = () => { + if (held !== null) ws.send(held); + held = null; + }; + }, + ); + return { + holding: () => held !== null, + release: () => { + release(); + }, + }; +}; + +export interface HeldAdds { + /** Hub replies to `addPreset` held back so far. */ + held: () => number; + /** Delivers the held replies and passes later ones through. */ + release: () => void; +} + +/** Routes the page's WebSockets through the test, holding back the hub's reply to every `addPreset` until released. */ +export const holdAddReplies = async (page: Page): Promise => { + const adds = new Set(); + const held: (string | Buffer)[] = []; + let release = (): void => undefined; + await page.routeWebSocket( + (url) => url.pathname === '/ws', + (ws) => { + const server = ws.connectToServer(); + let released = false; + ws.onMessage((message) => { + if (typeof message === 'string') { + const m = decodeMessage('browserToHub', message); + if (m.t === 'addPreset') adds.add(m.req); + } + server.send(message); + }); + server.onMessage((message) => { + if (!released && typeof message === 'string') { + const m = decodeMessage('hubToBrowser', message); + if (m.t === 'done' && adds.has(m.req)) { + held.push(message); + return; + } + } + ws.send(message); + }); + release = () => { + released = true; + for (const message of held.splice(0)) ws.send(message); + }; + }, + ); + return { + held: () => held.length, + release: () => { + release(); + }, + }; +}; + +/** Routes the page's WebSockets through the test; every session after the first holds back `presets` and every later hub message. */ +export const holdPresets = async (page: Page): Promise => { + let sessions = 0; + let creates = 0; + let current: Session | null = null; + await page.routeWebSocket( + (url) => url.pathname === '/ws', + (ws) => { + sessions++; + const later = sessions > 1; + const server = ws.connectToServer(); + let held: (string | Buffer)[] | null = null; + let released = false; + current = { + cut: () => { + void ws.close(); + void server.close(); + }, + holding: () => held !== null, + release: () => { + released = true; + for (const message of held ?? []) ws.send(message); + held = null; + }, + }; + ws.onMessage((message) => { + if (typeof message === 'string') { + const m = decodeMessage('browserToHub', message); + if (m.t === 'host' && m.m.t === 'createTerm') creates++; + } + server.send(message); + }); + server.onMessage((message) => { + // `presets` precedes `hosts`: holding it and everything after keeps the hub's order. + if (later && !released && held === null && typeof message === 'string' && decodeMessage('hubToBrowser', message).t === 'presets') { + held = []; + } + if (held === null) ws.send(message); + else held.push(message); + }); + }, + ); + return { + sessions: () => sessions, + current: () => { + if (current === null) throw new Error('no WebSocket session'); + return current; + }, + creates: () => creates, + }; +}; diff --git a/test/e2e/hubs.spec.ts b/test/e2e/hubs.spec.ts index 0ad0bf3..2b79efe 100644 --- a/test/e2e/hubs.spec.ts +++ b/test/e2e/hubs.spec.ts @@ -16,6 +16,7 @@ import { writeHubConfig, type HostConfig, } from './fixture.js'; +import { holdFirstPresets } from './held-presets.js'; const RESOLVE_ERROR = 'ssh: Could not resolve hostname box: Name or service not known'; @@ -120,6 +121,23 @@ test.describe('Hubs menu', () => { await expect.poll(() => colours(button)).toEqual(tab); }); + test('preset choices shown while the menu is open leave it the focus, and Escape closes it', async ({ hub, page, ssh }) => { + ssh.failHost('box', RESOLVE_ERROR); + const presets = await holdFirstPresets(page); + await home(hub, page, [{ name: 'box', ssh: 'box' }]); + await expect.poll(() => presets.holding()).toBe(true); + const button = page.locator(byTestId(TID.hubsMenu)); + await button.click(); + await expect(button).toBeFocused(); + + presets.release(); + await expect(page.locator(byTestId(TID.presetChoices))).toBeVisible(); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(button).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(page.locator(byTestId(TID.hubsList))).toHaveCount(0); + }); + test('is absent without remote hosts', async ({ hub, page }) => { await home(hub, page, []); await expect(page.locator(byTestId(TID.hubsMenu))).toHaveCount(0); diff --git a/test/e2e/picker.spec.ts b/test/e2e/picker.spec.ts index 5628674..4a258e8 100644 --- a/test/e2e/picker.spec.ts +++ b/test/e2e/picker.spec.ts @@ -1,10 +1,10 @@ import { readFileSync } from 'node:fs'; -import type { Locator, Page } from '@playwright/test'; -import { decodeMessage } from '../../src/protocol/index.js'; +import type { Locator } from '@playwright/test'; import { byTestId, terminalBox, termTab, TID, worktreeEntry } from './contract.js'; import { activeTerm, expect, + listedWorktrees, LOCAL, makeRepoWith, newTerminal, @@ -18,80 +18,11 @@ import { waitScreen, watcher, } from './fixture.js'; +import { holdAddReplies, holdPresets } from './held-presets.js'; import { boxOf, createsSent, pickerSeen, watchPicker } from './panes.js'; const [SHELL, CAT] = PRESETS; -interface Session { - /** Closes both sides of the session. */ - cut: () => void; - /** Whether the session holds back the hub's messages. */ - holding: () => boolean; - /** Delivers the held messages in order and passes later ones through. */ - release: () => void; -} - -interface HeldPresets { - /** WebSocket sessions the page opened. */ - sessions: () => number; - /** The latest session. */ - current: () => Session; - /** `createTerm` requests the page sent over every session. */ - creates: () => number; -} - -/** Routes the page's WebSockets through the test; every session after the first holds back `presets` and every later hub message. */ -const holdPresets = async (page: Page): Promise => { - let sessions = 0; - let creates = 0; - let current: Session | null = null; - await page.routeWebSocket( - (url) => url.pathname === '/ws', - (ws) => { - sessions++; - const later = sessions > 1; - const server = ws.connectToServer(); - let held: (string | Buffer)[] | null = null; - let released = false; - current = { - cut: () => { - void ws.close(); - void server.close(); - }, - holding: () => held !== null, - release: () => { - released = true; - for (const message of held ?? []) ws.send(message); - held = null; - }, - }; - ws.onMessage((message) => { - if (typeof message === 'string') { - const m = decodeMessage('browserToHub', message); - if (m.t === 'host' && m.m.t === 'createTerm') creates++; - } - server.send(message); - }); - server.onMessage((message) => { - // `presets` precedes `hosts`: holding it and everything after keeps the hub's order. - if (later && !released && held === null && typeof message === 'string' && decodeMessage('hubToBrowser', message).t === 'presets') { - held = []; - } - if (held === null) ws.send(message); - else held.push(message); - }); - }, - ); - return { - sessions: () => sessions, - current: () => { - if (current === null) throw new Error('no WebSocket session'); - return current; - }, - creates: () => creates, - }; -}; - test.describe('preset picker', () => { test('the tab-bar controls name their shortcuts', async ({ hub, page }) => { const { repo } = makeRepoWith(hub, 'app', []); @@ -310,6 +241,64 @@ test.describe('preset choices of a worktree without terminals', () => { await page.keyboard.press('Enter'); await expect.poll(() => createsSent(wire, mark).map((m) => [m.preset, m.command])).toEqual([[SHELL.name, SHELL.command]]); }); + + test('Enter held on the label of a worktree without terminals selects it and starts nothing', async ({ hub, page, wire }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['feat']); + const feat = worktrees[0] ?? ''; + hub.writeRepos([repo]); + await openUi(hub, page); + await expect(page.locator(byTestId(TID.presetChoices))).toBeVisible(); + const mark = wire.markSent(); + + await page.locator(worktreeEntry(feat)).locator(byTestId(TID.worktreeLabel)).focus(); + // Every `down` after the first is a repeat of the held key. + for (let i = 0; i < 6; i++) await page.keyboard.down('Enter'); + await page.keyboard.up('Enter'); + await expect(page.locator(worktreeEntry(feat))).toHaveAttribute('aria-selected', 'true'); + await expect(page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetOption)).nth(0)).toBeFocused(); + await page.waitForTimeout(500); // NOSONAR(S2925) — absence check: nothing to synchronise on + expect(createsSent(wire, mark)).toEqual([]); + await expect(page.locator(byTestId(TID.termTab))).toHaveCount(0); + }); + + test('Alt+Down in the choices selects the next worktree, one step, without moving a preset', async ({ hub, page, wire }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['a', 'b', 'c']); + const [a = '', b = '', c = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + await expect(page.locator(worktreeEntry(c))).toBeVisible(); + const listed = await listedWorktrees(page); + expect([listed.indexOf(b), listed.indexOf(c)]).toEqual([listed.indexOf(a) + 1, listed.indexOf(a) + 2]); + await selectWorktree(page, a); + const options = page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetOption)); + await options.nth(0).focus(); + const mark = wire.markSent(); + + await page.keyboard.press('Alt+ArrowDown'); + await expect(page.locator(worktreeEntry(b))).toHaveAttribute('aria-selected', 'true'); + await page.waitForTimeout(500); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(page.locator(worktreeEntry(b))).toHaveAttribute('aria-selected', 'true'); + await expect(options).toHaveText(PRESETS.map((p) => p.name)); + expect(presetRequests(wire, mark)).toEqual([]); + expect(createsSent(wire, mark)).toEqual([]); + }); + + test('a held arrow key keeps moving through the choices', async ({ hub, page, wire }) => { + hub.presets = [...PRESETS, { name: 'third', command: 'echo THIRD' }]; + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const options = page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetOption)); + await options.nth(0).focus(); + const mark = wire.markSent(); + + // Every `down` after the first is a repeat of the held key. + for (let i = 0; i < 3; i++) await page.keyboard.down('ArrowDown'); + await page.keyboard.up('ArrowDown'); + await expect(options.nth(2)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(2)).toBeFocused(); + expect(createsSent(wire, mark)).toEqual([]); + }); }); test.describe('editing presets', () => { @@ -466,4 +455,213 @@ test.describe('editing presets', () => { ]).toContainEqual(order); expect(configured(hub.configPath)).toEqual(order.map((name) => [...PRESETS, third].find((p) => p.name === name))); }); + + test('the add form in the choices keeps the focus while another page moves a preset', async ({ hub, page, context }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const other = await openPage(hub, context); + const choices = page.locator(byTestId(TID.presetChoices)); + await choices.locator(byTestId(TID.presetAdd)).click(); + const name = choices.locator(byTestId(TID.presetName)); + await expect(name).toBeFocused(); + await page.keyboard.type('ab'); + + const otherRow = (preset: string): Locator => + other.page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetRow), { hasText: preset }); + await otherRow(CAT.name).dragTo(otherRow(SHELL.name), { targetPosition: { x: 20, y: 2 } }); + await expect(choices.locator(byTestId(TID.presetOption))).toHaveText([CAT.name, SHELL.name]); + await expect(name).toBeFocused(); + await page.keyboard.type('c'); + await expect(name).toHaveValue('abc'); + }); + + test('Escape in the add form of the choices returns the focus to the list, and Enter starts the first preset', async ({ + hub, + page, + wire, + }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + await choices.locator(byTestId(TID.presetAdd)).click(); + await expect(choices.locator(byTestId(TID.presetName))).toBeFocused(); + const mark = wire.markSent(); + + await page.keyboard.press('Escape'); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(choices.locator(byTestId(TID.presetOption)).nth(0)).toBeFocused(); + await page.keyboard.press('Enter'); + await expect.poll(() => createsSent(wire, mark)).toEqual([expect.objectContaining({ worktree: repo, preset: SHELL.name })]); + }); + + test('in the choices, Cancel and a resolved add return the focus to the highlighted preset', async ({ hub, page }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + const options = choices.locator(byTestId(TID.presetOption)); + await options.nth(0).focus(); + await page.keyboard.press('ArrowDown'); + await expect(options.nth(1)).toBeFocused(); + + await choices.locator(byTestId(TID.presetAdd)).click(); + await expect(choices.locator(byTestId(TID.presetName))).toBeFocused(); + await choices.locator(byTestId(TID.presetForm)).getByRole('button', { name: 'Cancel' }).click(); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(1)).toBeFocused(); + + await addPreset(choices, NEW.name, NEW.command); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(options).toHaveText([...PRESETS.map((p) => p.name), NEW.name]); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(1)).toBeFocused(); + }); + + test('an add that completes after Escape leaves the focus in the worktree search', async ({ hub, page }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + const adds = await holdAddReplies(page); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + await choices.locator(byTestId(TID.presetAdd)).click(); + await choices.locator(byTestId(TID.presetName)).fill(NEW.name); + await choices.locator(byTestId(TID.presetCommand)).fill(NEW.command); + await choices.locator(byTestId(TID.presetCommand)).press('Enter'); + await expect.poll(() => adds.held()).toBe(1); + await page.keyboard.press('Escape'); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(0); + const search = page.locator(byTestId(TID.worktreeSearch)); + await search.focus(); + + adds.release(); + await expect(choices.locator(byTestId(TID.presetOption))).toHaveText([...PRESETS.map((p) => p.name), NEW.name]); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(search).toBeFocused(); + }); + + test('an add that completes after its form was cancelled and reopened leaves the new form open', async ({ hub, page }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + const adds = await holdAddReplies(page); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + await addPreset(choices, NEW.name, NEW.command); + await expect.poll(() => adds.held()).toBe(1); + await choices.locator(byTestId(TID.presetForm)).getByRole('button', { name: 'Cancel' }).click(); + await choices.locator(byTestId(TID.presetAdd)).click(); + const name = choices.locator(byTestId(TID.presetName)); + await expect(name).toBeFocused(); + await page.keyboard.type('ab'); + + adds.release(); + await expect(choices.locator(byTestId(TID.presetOption))).toHaveText([...PRESETS.map((p) => p.name), NEW.name]); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(name).toBeFocused(); + await expect(name).toHaveValue('ab'); + await expect(choices.locator(byTestId(TID.presetSubmit))).toBeEnabled(); + }); + + test('an add the hub refuses keeps the form open with the focus in its name field', async ({ hub, page, wire }) => { + // At the hub's limit the form's own checks pass and the hub refuses. + hub.presets = Array.from({ length: 64 }, (_, i) => ({ name: `p${String(i)}`, command: null })); + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + await choices.locator(byTestId(TID.presetAdd)).click(); + const name = choices.locator(byTestId(TID.presetName)); + await name.fill(NEW.name); + const mark = wire.markSent(); + + await name.press('Enter'); + await expect.poll(() => presetRequests(wire, mark)).toEqual([{ t: 'addPreset', preset: { name: NEW.name, command: null } }]); + await expect(choices.locator(byTestId(TID.presetError))).toContainText('more than 64 presets'); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(1); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(name).toBeFocused(); + }); + + test('a preset change from another page leaves the focus on a control outside the choices', async ({ hub, page, context }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const other = await openPage(hub, context); + const choices = page.locator(byTestId(TID.presetChoices)); + await expect(choices).toBeVisible(); + const filter = page.locator(byTestId(TID.filterChecked)); + await filter.focus(); + + const otherRow = (preset: string): Locator => + other.page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetRow), { hasText: preset }); + await otherRow(CAT.name).dragTo(otherRow(SHELL.name), { targetPosition: { x: 20, y: 2 } }); + await expect(choices.locator(byTestId(TID.presetOption))).toHaveText([CAT.name, SHELL.name]); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(filter).toBeFocused(); + }); + + test('in the picker, Cancel and a resolved add return the focus to the highlighted preset; a refused add keeps it in the form', async ({ + hub, + page, + }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + await newTerminal(page); + await page.locator(byTestId(TID.newTab)).click(); + const picker = page.locator(byTestId(TID.presetPicker)); + const options = picker.locator(byTestId(TID.presetOption)); + await page.keyboard.press('ArrowDown'); + await expect(options.nth(1)).toBeFocused(); + + await picker.locator(byTestId(TID.presetAdd)).click(); + await expect(picker.locator(byTestId(TID.presetName))).toBeFocused(); + await picker.locator(byTestId(TID.presetForm)).getByRole('button', { name: 'Cancel' }).click(); + await expect(picker.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(1)).toBeFocused(); + + await picker.locator(byTestId(TID.presetAdd)).click(); + const name = picker.locator(byTestId(TID.presetName)); + await name.fill(CAT.name); + await name.press('Enter'); + await expect(picker.locator(byTestId(TID.presetError))).toHaveText(`A preset named ${CAT.name} exists`); + await page.waitForTimeout(300); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(name).toBeFocused(); + await name.press('Escape'); + await expect(options.nth(1)).toBeFocused(); + + await addPreset(picker, NEW.name, NEW.command); + await expect(picker.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(options).toHaveText([...PRESETS.map((p) => p.name), NEW.name]); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(1)).toBeFocused(); + await expect(picker).toBeVisible(); + }); + + test('removing the highlighted preset on another page leaves the focus on the surviving one in the picker', async ({ + hub, + page, + context, + }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['feat']); + const feat = worktrees[0] ?? ''; + hub.writeRepos([repo]); + await openUi(hub, page); + await newTerminal(page); + const other = await openPage(hub, context); + await selectWorktree(other.page, feat); + await page.locator(byTestId(TID.newTab)).click(); + const options = page.locator(byTestId(TID.presetPicker)).locator(byTestId(TID.presetOption)); + await page.keyboard.press('ArrowDown'); + await expect(options.nth(1)).toBeFocused(); + + const otherChoices = other.page.locator(byTestId(TID.presetChoices)); + await otherChoices.locator(byTestId(TID.presetOption), { hasText: CAT.name }).locator('..').locator(byTestId(TID.presetRemove)).click(); + await expect(options).toHaveText([SHELL.name]); + await expect(options.nth(0)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(0)).toBeFocused(); + }); }); diff --git a/test/e2e/terminals.spec.ts b/test/e2e/terminals.spec.ts index 2afbac0..8d947e0 100644 --- a/test/e2e/terminals.spec.ts +++ b/test/e2e/terminals.spec.ts @@ -1,11 +1,12 @@ -import type { Page } from '@playwright/test'; +import type { Locator, Page } from '@playwright/test'; import { decodeMessage } from '../../src/protocol/index.js'; -import { byTestId, pane, terminalBox, termTab, TID } from './contract.js'; +import { byTestId, pane, terminalBox, termTab, TID, worktreeEntry } from './contract.js'; import { activeTerm, confirmClose, expect, isCurrent, + listedWorktrees, LOCAL, makeRepoWith, markOf, @@ -15,6 +16,7 @@ import { PRESETS, ready, screenOf, + selectRepo, selectWorktree, test, typeLine, @@ -22,9 +24,15 @@ import { watcher, xtermOf, } from './fixture.js'; +import { holdPresets } from './held-presets.js'; import { createsSent, createTerms, leaf, split, storeTabs } from './panes.js'; import { installStreamCheck } from './stream.js'; +const [SHELL, CAT] = PRESETS; + +/** The options of the preset choices of a worktree without terminals. */ +const choiceOptions = (page: Page): Locator => page.locator(byTestId(TID.presetChoices)).locator(byTestId(TID.presetOption)); + /** Where the page's first session is cut: when the hub answers its `createTerm`, or when it sends the `setLayout` that follows. */ type Cut = 'termCreated' | 'setLayout'; @@ -228,6 +236,174 @@ test.describe('terminal tabs', () => { await expect(search).toBeFocused(); }); + test('a worktree without terminals clicked in the sidebar takes ArrowDown and Enter in its choices', async ({ hub, page, wire }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['feat']); + const feat = worktrees[0] ?? ''; + hub.writeRepos([repo]); + await openUi(hub, page); + const options = choiceOptions(page); + await expect(options).toHaveText(PRESETS.map((p) => p.name)); + const mark = wire.markSent(); + + await selectWorktree(page, feat); + await expect(options.nth(0)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(0)).toBeFocused(); + await page.keyboard.press('ArrowDown'); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(1)).toBeFocused(); + await page.keyboard.press('Enter'); + await expect.poll(() => createsSent(wire, mark).length).toBe(1); + await page.waitForTimeout(500); // NOSONAR(S2925) — absence check: nothing to synchronise on + expect(createsSent(wire, mark)).toEqual([expect.objectContaining({ worktree: feat, preset: CAT.name, command: CAT.command })]); + }); + + test('Alt+Down from a terminal onto a worktree without terminals focuses its choices, and Enter starts the first preset', async ({ + hub, + page, + wire, + }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['a', 'b']); + const [a = '', b = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + await selectWorktree(page, a); + const term = await newTerminal(page); + await ready(page, term); + const listed = await listedWorktrees(page); + expect(listed.indexOf(b)).toBe(listed.indexOf(a) + 1); + const mark = wire.markSent(); + + await page.keyboard.press('Alt+ArrowDown'); + await expect(page.locator(worktreeEntry(b))).toHaveAttribute('aria-selected', 'true'); + await expect(choiceOptions(page).nth(0)).toBeFocused(); + await page.keyboard.press('Enter'); + await expect.poll(() => createsSent(wire, mark)).toEqual([expect.objectContaining({ worktree: b, preset: SHELL.name })]); + }); + + test('a repo tab whose selected worktree has no terminals focuses its choices, and Enter starts the first preset', async ({ + hub, + page, + wire, + }) => { + const app = makeRepoWith(hub, 'app', []); + const second = makeRepoWith(hub, 'second', []); + hub.writeRepos([app.repo, second.repo]); + await openUi(hub, page); + await selectRepo(page, app.repo); + await newTerminal(page); + const mark = wire.markSent(); + + await selectRepo(page, second.repo); + await expect(choiceOptions(page).nth(0)).toBeFocused(); + await page.keyboard.press('Enter'); + await expect.poll(() => createsSent(wire, mark)).toEqual([expect.objectContaining({ worktree: second.repo, preset: SHELL.name })]); + }); + + test('each showing of a worktree’s choices starts at the first preset', async ({ hub, page }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['a', 'b']); + const [a = '', b = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + await selectWorktree(page, a); + const options = choiceOptions(page); + await options.nth(0).focus(); + await page.keyboard.press('ArrowDown'); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'true'); + + await selectWorktree(page, b); + await expect(options.nth(0)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(1)).toHaveAttribute('aria-selected', 'false'); + await expect(options.nth(0)).toBeFocused(); + }); + + test('selecting another worktree without terminals closes an open add form and shows its choices at the first preset', async ({ + hub, + page, + }) => { + const { repo, worktrees } = makeRepoWith(hub, 'app', ['a', 'b']); + const [a = '', b = ''] = worktrees; + hub.writeRepos([repo]); + await openUi(hub, page); + await selectWorktree(page, a); + const choices = page.locator(byTestId(TID.presetChoices)); + const options = choices.locator(byTestId(TID.presetOption)); + await options.nth(0).focus(); + await page.keyboard.press('ArrowDown'); + await choices.locator(byTestId(TID.presetAdd)).click(); + await expect(choices.locator(byTestId(TID.presetName))).toBeFocused(); + + await selectWorktree(page, b); + await expect(choices.locator(byTestId(TID.presetForm))).toHaveCount(0); + await expect(choices.locator(byTestId(TID.presetAdd))).toBeVisible(); + await expect(options.nth(0)).toHaveAttribute('aria-selected', 'true'); + await expect(options.nth(0)).toBeFocused(); + }); + + test('the choices take the focus again when the picker over them is cancelled, and Enter starts the first preset', async ({ + hub, + page, + wire, + }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const options = choiceOptions(page); + await options.nth(0).focus(); + const mark = wire.markSent(); + + await page.keyboard.press('Control+Shift+KeyT'); + await expect(page.locator(byTestId(TID.presetPicker))).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.locator(byTestId(TID.presetPicker))).toHaveCount(0); + await expect(options.nth(0)).toBeFocused(); + await page.keyboard.press('Enter'); + await expect.poll(() => createsSent(wire, mark)).toEqual([expect.objectContaining({ worktree: repo, preset: SHELL.name })]); + }); + + test('when another page closes the only terminal while its close dialog is open, the choices take the focus', async ({ + hub, + page, + wire, + }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + await openUi(hub, page); + const client = await watcher(hub, repo); + const term = await newTerminal(page); + await ready(page, term); + await page.locator(termTab(term)).locator(byTestId(TID.termTabClose)).click(); + await expect(page.locator(byTestId(TID.closeDialog))).toBeVisible(); + + await client.ok({ t: 'closeTerm', termId: term }); + await expect(page.locator(byTestId(TID.closeDialog))).toHaveCount(0); + const options = choiceOptions(page); + await expect(options).toHaveText(PRESETS.map((p) => p.name)); + await expect(options.nth(0)).toBeFocused(); + const mark = wire.markSent(); + await page.keyboard.press('Enter'); + await expect.poll(() => createsSent(wire, mark)).toEqual([expect.objectContaining({ worktree: repo, preset: SHELL.name })]); + }); + + test('choices shown again after a reconnect leave the keyboard focus in the worktree search', async ({ hub, page }) => { + const { repo } = makeRepoWith(hub, 'app', []); + hub.writeRepos([repo]); + const route = await holdPresets(page); + await openUi(hub, page); + const choices = page.locator(byTestId(TID.presetChoices)); + await expect(choices).toBeVisible(); + const search = page.locator(byTestId(TID.worktreeSearch)); + await search.focus(); + + route.current().cut(); + await expect.poll(() => route.sessions(), { timeout: 15_000 }).toBe(2); + await expect.poll(() => route.current().holding(), { timeout: 15_000 }).toBe(true); + await expect(choices).toHaveCount(0); + route.current().release(); + await expect(choices).toBeVisible(); + await page.waitForTimeout(500); // NOSONAR(S2925) — absence check: nothing to synchronise on + await expect(search).toBeFocused(); + }); + for (const at of ['setLayout', 'termCreated'] as const) { test(`a terminal created before the session closes at its ${at} is shown as a tab after reconnecting and created once`, async ({ hub, diff --git a/test/process/daemon-terminals-scopes.test.ts b/test/process/daemon-terminals-scopes.test.ts index 28fba6c..bc7430b 100644 --- a/test/process/daemon-terminals-scopes.test.ts +++ b/test/process/daemon-terminals-scopes.test.ts @@ -205,8 +205,8 @@ describe.skipIf(NO_USER_MANAGER !== null)(withUserManager('terminal scopes on, b it('resets the failed terminal units of its state directory at start, and only those', async () => { const ours = terminalUnit(host.stateDir, 'oldinstance', 1); const theirs = terminalUnit(`${host.stateDir}-other`, 'oldinstance', 1); - failUnit(ours); - failUnit(theirs); + await failUnit(ours); + await failUnit(theirs); try { await startDaemon(userManagerEnv()); await waitUntil(() => !isFailed(ours), `${ours} to be reset`, 10_000); diff --git a/test/support/scopes.ts b/test/support/scopes.ts index 56e1c14..e35bf7d 100644 --- a/test/support/scopes.ts +++ b/test/support/scopes.ts @@ -3,6 +3,7 @@ import { createHash } from 'node:crypto'; import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; import { userInfo } from 'node:os'; import { join } from 'node:path'; +import { waitUntil } from './daemon-host.js'; /** The slice every scope lives in. */ export const SLICE = 'app-wtd.slice'; @@ -93,8 +94,8 @@ export const resetFailed = (unit: string): void => { spawnSync('systemctl', ['--user', 'reset-failed', unit], { stdio: 'ignore' }); // NOSONAR(S4036) — the host's own systemctl, as the product uses }; -/** Leaves `unit` failed, its process killed for lack of memory. */ -export const failUnit = (unit: string): void => { +/** Leaves `unit` failed, its process killed for lack of memory; the manager marks it failed after systemd-run returns. */ +export const failUnit = async (unit: string): Promise => { spawnSync( 'systemd-run', // NOSONAR(S4036) — the host's own systemd-run, as the product uses [ @@ -116,7 +117,9 @@ export const failUnit = (unit: string): void => { ], { stdio: 'ignore' }, ); - if (!isFailed(unit)) throw new Error(`${unit} did not fail: ${JSON.stringify(unitState(unit))}`); + await waitUntil(() => isFailed(unit), `${unit} to fail`).catch((error: unknown) => { + throw new Error(`${unit} did not fail: ${JSON.stringify(unitState(unit))}`, { cause: error }); + }); }; /** A stand-in program at `path` that appends its arguments, one call per line, to `.calls`, then runs `body`. */