Merge pull request #712: feat(tabs): start a session beside any tab from an opt-in + in its actions

This commit is contained in:
Codeman maintainer committed 2026-10-27 02:24:17 +01:00
commit 0f1fca6ea0
18 files changed
+1266 -46

No files matched your search

+4 -2
View File
@@ -345,8 +345,8 @@ So: `_confirmIdle()` (session.ts) requires the pane to go quiet, and then asks t
- **Lineage arcs to a collapse-hidden session anchor to its group header** (`lineage-line--proxied`); two endpoints proxied to one header draw nothing.
- **The upstream HTML5 drag stays off in the grouped rail**: a flat-order drop cannot express a group move, and the server re-ranks within the old group. The grouped rail has its OWN pointer drag instead (`_bindTabLayoutPointerDrag`, mouse/pen only, bound once on the container): rows move before/after a row or into a group, a header drag reorders groups, and the drop maps to ONE operation through the pure `dropOperation()`. Escape cancels a drag, and the click that ends one is swallowed. ⚠️ A press is only captured once it moves 6 px, so its release can land outside the rail: `pointerup`/`pointercancel` are heard on `window` while a press is pending, a move with the primary button up cancels it, and a new press cancels any previous one. Without that a stale press became a phantom drag on the next hover, and a replaced drag left its capture-phase Escape listener behind, swallowing every Escape before the terminal saw it. The flat rail and the header strip keep the HTML5 drag untouched. For the same reason Ctrl+Shift+{ / } only swaps with a neighbour in the active session's own section (`_canSwapActiveTabWith`, reading the projection's `sectionByRef`): a cross-group swap moves nothing on the server, gets no `session:orderChanged` back, and would leave this client's `sessionOrder` and Alt+N targets out of step with every other device.
- **Edits are named operations, saved serially.** `createEditCoordinator` applies `createGroup` / `renameGroup` / `deleteGroup` / `reorderGroup` / `moveRef` to the rail at once, then sends ONE `PUT /api/tab-layout {baseVersion, layout}` at a time; edits made meanwhile wait and go out on the version that write returns. A 409 carries the server's layout: the in-flight operations are replayed onto it (an operation that no longer applies is dropped and reported) and re-sent, at most `maxAttempts` times; a 400 re-reads once (a second 400 is reported as a failed save, not as a race); anything else reports and re-reads. A `moveRef` moves the session together with the sessions that still follow it and marks a hand-moved child `placement: 'manual'`, mirroring the server's `moveRef`, and `normalizeLayout` keeps `placement` because whole layouts are written back. `_onTabLayoutChanged` / `_applyTabLayout` defer a read while a write is in flight and rebase unsaved edits onto a read otherwise. ⚠️ A FAILED read (`_applyTabLayout(null)`) while edits are pending keeps the held layout and the editor and re-reads after the write settles: disposing there would orphan the in-flight write, whose 409 then never gets its rebase. Any path that does drop unsaved work says so in a toast. On `pagehide`, unconfirmed operations go out in a `keepalive` PUT AND into sessionStorage as `{ owner, baseVersion, savedAt, operations }`; after reload they replay onto the fresh layout (a no-op when the keepalive landed), but only for the same owner, within `TAB_LAYOUT_PENDING_MAX_AGE_MS` (60 s), and never onto a layout older than the copy's base. A "Move to <group>" with no anchor carries no `index`, so a replay still puts the row last.
- **Every way in has a keyboard path.** The session row menu (Shift+F10 in the tree, the rail's overflow button) gains Move up/down, Move to <group>, Move to Ungrouped and Move to new group in the vertical rail (only "new group" before the first group exists; nothing on the strip). A group header opens its menu with Shift+F10 / ContextMenu, right-click or its hover glyph (a non-focusable, `aria-hidden` span: a treeitem holds no interactive children), and F2 renames it inline (Enter commits and refocuses the header; a commit by BLUR leaves focus where it went, since refocusing from inside the blur handler overrides the user's click). The glyph stays visible under `@media (hover: none)`: a touch tablet has no hover and no long-press `contextmenu`. Group names in "Move to" labels are quoted, so a group named "New group" or "ungrouped" cannot read (or translate, case-insensitively) like the fixed entries. The menu closes on Escape (which it consumes before the global Escape handler), a pointer outside, Tab, focus leaving it, a resize, a second open and any full re-render. It borrows the `.tab-rail-action-menu` class for its look only: `closeTabRailActionMenu()` excludes `.tab-layout-group-action-menu`, so closing the row menu (every `session:deleted` does) cannot strand the group menu's listeners. The inline group editor shares `_activeRename` with the session rename, so only the CURRENT editor may release `_inlineRenameActive`.
- **New, child and web tabs land in groups.** A group menu's "New session" (`createSessionInTabGroup`) runs ONE launch with `run({ count: 1, tabGroupId })`; every launch path puts `tabGroupId` on its create request (`POST /api/sessions` or `/api/quick-start`), and `TabLayoutService.sessionCreated(owner, id, { tabGroupId }, register)` places the session at the end of that group in the SAME versioned write that first records it. The session enters the live map inside the owner lock (`register`, rolled back if the write fails), so no queued layout edit can commit it first. The group is looked up in the creating owner's own layout, so an unknown, deleted or foreign id is ignored rather than failing the spawn, and an explicit group is a hand placement (a child placed this way is `manual`). The create response carries the committed `tabLayout`, adopted before the tab is drawn. A session spawned by another one (`parentSessionId`) and placed by nobody lands after its parent: the server's normalization puts it after the parent's rows in the parent's container, and `project({ parents })` draws a not-yet-stored child there at once. Whether it then FOLLOWS its parent is the synced `spawnedTabsFollowParent` setting (default OFF), which `sessionCreated()` reads fresh through the `childrenFollowParent` dep: off, the child is marked `manual` in that same creating write; on, it follows until moved by hand. Deciding at creation is enough, so flipping the setting leaves existing tabs alone. A hand move makes a following child `manual`; with the setting on, the row menu notes where a child sits (following, placed by hand, parent closed, parent loop; plain text, never a focusable menu item) and offers "Follow parent again" only to a `manual` child, which clears `placement` and is re-derived by the server on save. With the setting off the row menu says nothing about placement. A legacy `PUT /api/session-order` (strip or phone drag, a same-section Ctrl+Shift+{/}, a device without a layout, an admin's cross-owner order) marks a child `manual` ONLY when the requested order splits it from its parent's block (`applyLegacySessionRank`, `childrenSplitFromParent`); a PUT of the current order, or one that moves a family together, leaves every stored placement alone. The browser never echoes a create or delete through that PUT, with or without groups: the service already re-projects the order and broadcasts it (`session:orderChanged`), and `syncSessionOrder` adopts it. A child whose parent is gone stands on its own and is never re-adopted. Saved web tabs are layout refs like sessions, but OPENNESS stays per device: a grouped web tab renders (and takes an Alt+N slot) only while it is open on this device, and reopens where the layout keeps it.
- **Every way in has a keyboard path.** The session row menu (Shift+F10 in the tree, the rail's overflow button) gains Move up/down, Move to <group>, Move to Ungrouped and Move to new group in the vertical rail (only "new group" before the first group exists; nothing on the strip). With **New Session Button on Tabs** on (`showTabNewButton`, per device, `html.tabs-show-new`), every session row menu (the rail, compact or full, the expanded sidebar, the tree; never a tile's, which shares the function) also offers "New session here…", which opens the row's "+" picker, and the compact rail hides it. The "+" itself opens its picker on Enter or Space through its own inline `onkeydown` (the strip's key handler acts only on a focused tab), which is the keyboard path on the header strip, where no row menu exists. The menu cancels a REPEATED Enter or Space, so a held key that opened it cannot also pick the entry it focuses. A group header opens its menu with Shift+F10 / ContextMenu, right-click or its hover glyph (a non-focusable, `aria-hidden` span: a treeitem holds no interactive children), and F2 renames it inline (Enter commits and refocuses the header; a commit by BLUR leaves focus where it went, since refocusing from inside the blur handler overrides the user's click). The glyph stays visible under `@media (hover: none)`: a touch tablet has no hover and no long-press `contextmenu`. Group names in "Move to" labels are quoted, so a group named "New group" or "ungrouped" cannot read (or translate, case-insensitively) like the fixed entries. The menu closes on Escape (which it consumes before the global Escape handler), a pointer outside, Tab, focus moving to an element outside it, a resize, a second open and any full re-render. ⚠️ A `focusout` with no `relatedTarget` is not a departure: Safari never focuses a clicked button, so pressing an item blurs the focused one with focus going nowhere, and closing on that dropped the item's click (the tile count menu's rule). The tab "+" picker is this same menu (`_openTabLayoutMenu` with `anyLayout`, so it opens on every layout, not only the editable grouped rail). It borrows the `.tab-rail-action-menu` class for its look only: `closeTabRailActionMenu()` excludes `.tab-layout-group-action-menu`, so closing the row menu (every `session:deleted` does) cannot strand the group menu's listeners. The inline group editor shares `_activeRename` with the session rename, so only the CURRENT editor may release `_inlineRenameActive`.
- **New, child and web tabs land in groups.** A group menu's "New session" (`createSessionInTabGroup`) runs ONE launch with `run({ count: 1, tabGroupId })`; a tab's "+" (`openTabNewSessionMenu`) runs ONE launch in that tab's case or managed worktree through `_launchOnce` (the Git worktrees modal's launcher too), `run({ count: 1, mode, caseName | worktree, tabGroupId? })`, carrying the tab's named group if it has one. ⚠️ The mode rides the call and is never swapped into the Run button's `_runMode`, so a mode picked while the launch is pending is kept, and the case-list reload after every launch keeps the toolbar's own case (`_reloadCasesAfterRun`): the no-argument reload would re-select the server's `lastUsedCase`, which a "+" launching through quick-start moves to the tab's case while the toolbar stays put, so a later worktree launch, plain Run or group "New session" would carry the toolbar there. ⚠️ The tab's case is found by what the session runs on (`_tabCaseOf`), never by path alone: `GET /api/cases` gives remote and Docker cases a DISPLAY path with the raw values under `remote`/`docker`, so a Docker session belongs to its container's case on its own engine host, a remote one to the case on its own host whose path encloses its own, and a local one to the deepest case enclosing its folder (a display path never encloses one). A Docker tab's picker starts that container's probe (`_probeDockerCaseModes`) when nothing is cached for its case, since the toolbar probes only its own selected case: that open lists what is already known, the next one the container's answer. From an ungrouped tab the "+" sends no `tabGroupId` on purpose (the create schema cannot say "Ungrouped"), so the case default group below applies, as for a toolbar Run. Every launch path puts `tabGroupId` on its create request (`POST /api/sessions` or `/api/quick-start`), and `TabLayoutService.sessionCreated(owner, id, { tabGroupId }, register)` places the session at the end of that group in the SAME versioned write that first records it. The session enters the live map inside the owner lock (`register`, rolled back if the write fails), so no queued layout edit can commit it first. The group is looked up in the creating owner's own layout, so an unknown, deleted or foreign id is ignored rather than failing the spawn, and an explicit group is a hand placement (a child placed this way is `manual`). The create response carries the committed `tabLayout`, adopted before the tab is drawn. A session spawned by another one (`parentSessionId`) and placed by nobody lands after its parent: the server's normalization puts it after the parent's rows in the parent's container, and `project({ parents })` draws a not-yet-stored child there at once. Whether it then FOLLOWS its parent is the synced `spawnedTabsFollowParent` setting (default OFF), which `sessionCreated()` reads fresh through the `childrenFollowParent` dep: off, the child is marked `manual` in that same creating write; on, it follows until moved by hand. Deciding at creation is enough, so flipping the setting leaves existing tabs alone. A hand move makes a following child `manual`; with the setting on, the row menu notes where a child sits (following, placed by hand, parent closed, parent loop; plain text, never a focusable menu item) and offers "Follow parent again" only to a `manual` child, which clears `placement` and is re-derived by the server on save. With the setting off the row menu says nothing about placement. A legacy `PUT /api/session-order` (strip or phone drag, a same-section Ctrl+Shift+{/}, a device without a layout, an admin's cross-owner order) marks a child `manual` ONLY when the requested order splits it from its parent's block (`applyLegacySessionRank`, `childrenSplitFromParent`); a PUT of the current order, or one that moves a family together, leaves every stored placement alone. The browser never echoes a create or delete through that PUT, with or without groups: the service already re-projects the order and broadcasts it (`session:orderChanged`), and `syncSessionOrder` adopts it. A child whose parent is gone stands on its own and is never re-adopted. Saved web tabs are layout refs like sessions, but OPENNESS stays per device: a grouped web tab renders (and takes an Alt+N slot) only while it is open on this device, and reopens where the layout keeps it.
- **A case's default session group** (`caseDefaultGroups` in state.json, keyed by the layout owner key then case name; a group id or `null` for Ungrouped) is the fallback placement for a new session of that case. It is read and written ONLY through `TabLayoutService` (`caseDefaultGroup`, `setCaseDefaultGroup`, `forgetCaseDefaultGroup`, and `sessionCreated`'s `caseName` hint), under the owner lock, never by a route or the store directly. Precedence inside `sessionCreated`'s single write: an explicit `tabGroupId` found in the owner's layout, then a parent that places the child (`hasPlacingParent`, the same conditions as `pinCreatedChild`), then the case default, else normal placement. The id is looked up in the creating owner's own layout, so a deleted or foreign id never fails a spawn; a stale id is forgotten only AFTER the creating write lands (a failed write rolls back and changes nothing). `POST /api/quick-start` and `POST /api/ralph-loop/start` pass their `caseName`; `POST /api/sessions` infers it LEXICALLY from `workingDir` (`inferLocalCaseName`: a direct child of the caller's case space, or an exact linked-case path for an admin or single-user, or a Claude worktree of either, `<case>/.claude/worktrees/<name>`, which is how the Git worktrees modal launches Claude while every other CLI goes through quick-start), only for a named `workingDir` (never the server's own cwd), never for a remote attach and never touching the filesystem. Cron jobs, the one-shot run route and reboot restore keep normal placement. The Case settings selector (`onCaseDefaultGroupChanged`, session-ui.js) reads it on popover open and is redrawn from an adopted layout whose groups changed (`_refreshCaseDefaultGroupOptions` in `_applyTabLayout`; an unchanged group list is skipped, since every create, delete and reorder broadcasts a layout and a rebuild would reset an open dropdown).
- **Only the grouped rail is a tree.** `#sessionTabs` ships as `role=tablist` with `role=tab` rows, and the header strip, sidebar and flat rail keep exactly that. While grouped, `_applyTabListRole` makes it `role=tree` (and restores `tablist` + its label when grouping ends), named-group headers are level-1 `treeitem`s that `aria-owns` their rows' `role=group` (rows sit beside the header, not inside it), and ungrouped rows plus a collapsed group's kept selection are level-1 items. A collapsed header owns nothing, a group with no open rows is a leaf (no `aria-expanded`, no owned group), and the "Ungrouped" heading is `aria-hidden`. Rows are re-roled in the DOM by `_applyTabTreeSemantics` after render, never by rewriting their markup, so a grouped row's content stays the flat row's.
- **One tab stop in the tree.** Exactly one treeitem carries `tabindex=0` (the focused or selected item); every control inside a row drops to `-1`, which is why Shift+F10 / ContextMenu open a row's actions from the keyboard. Focus survives a full re-render by identity (`group:`/`session:`/`webview:`; a row a collapse just hid hands focus to its header), but only when focus was already inside the rail. The tree walk (`_tabTreeItems`) follows painted order WITHIN each group when the rail is sorted; the flat list keeps its own whole-list computed-order walk. `aria-posinset`/`aria-setsize` follow painted order too, so the incremental render path re-runs `_applyTabTreePositions` after it re-sorts rows in place. ⚠️ `_handleTabTreeKeydown` acts only when the key lands on the treeitem ITSELF: a key on a focused in-row control (close, overflow, the rename input) is that control's, or Enter on the overflow button re-selects the row instead of reopening its menu. ⚠️ The roving `tabindex=-1` also hides every item but the stop from the keyboard-dismiss selector's `[tabindex]` arm, which is why `MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR` lists `[role="treeitem"]` (see Dismissing the on-screen keyboard).
@@ -1029,6 +1029,8 @@ Tests: `test/terminal-touch-tap.test.ts`, `test/session-swipe-gesture.test.ts` (
⚠️ **The floor is set by the 10th tab onward, not by the tabs you can see**: `.tab-number` renders only for `_tabIdx < 9`, so tab 10 loses 16px + a gap off its left and its centre sits 10px further right. The centre clears the icons when `reserved > icons + rightEdge - leftRunUp - gap` (= 50 + 9 - 17 - 4 = **38px**), hit-testing snaps to whole pixels so 39px still lands on the gear, and the practical floor is 40px — a NUMBERED tab clears it at 20px, which is exactly why reasoning from the tabs on screen would put the centre back on the gear. `test/mobile-tab-tap-zones.test.ts` recomputes that inequality from the stylesheet, so widening the gear or the padding fails there rather than on a phone. The guarantee is centre-off-the-ICONS, not centre-inside-the-label (on a numberless tab it lands in the gap between them, which still switches). Non-active tabs keep their icons hidden and stay tappable end to end.
⚠️ **The opt-in tab "+" is a third icon in that cluster**: with **New Session Button on Tabs** on (`showTabNewButton`, per device, off by default; `html.tabs-show-new`) the active phone tab shows a 28px "+" between the gear and close, and `html.tabs-show-new .session-tab.active .tab-name` grows the reserve to 68px (gear 32 + "+" 28 + close 20 less close's 2px margin needs a 64px label, 66 with the test's rounding allowance), still under the 80px `max-width`. Growing the reserve while the setting is on is fine; shrinking the base one never is. The same test recomputes it with the "+" counted.
⚠️ Mobile no longer hoists the active session to the front of the strip: that reordering ran on full renders only, so tab order flipped depending on which render path fired, and it renumbered the Alt+N badges. Scroll-into-view replaces it; do not reintroduce it.
### Tab layouts (by state, by case, ledger)
+1
View File
@@ -148,6 +148,7 @@ experimental and may change in any release. See
| Tall Tabs | Taller tab strip. |
| CLI Logos on Tabs | Each agent tab, and its row on the desktop home rail, shows the CLI's logo before the name. Off hides those logos on this device; the status dot and the shell's SH badge stay, and tiles, split headers and the Run menus keep their logos. On by default. |
| Pop-out Button on Tabs | Adds the detach control to tabs, with a per-tab override. |
| New Session Button on Tabs | Adds a **+** beside each tab's gear: pick a CLI the tab's case can start and one session starts in that case (or worktree) and named group, leaving the Run button alone. The row menu offers it as *New session here…*. Per device, off by default. See [The Dashboard](The-Dashboard#session-tabs). |
| Spawn Lineage Lines | Lines from each tab to the sessions it spawned; the selected tab's family is drawn thicker. Desktop only, on by default. |
| Auto-name Sessions | Titles a new tab after its first prompt, keeping the case prefix (`w3-myapp: fix the login redirect`). Synced, off by default. See [The Dashboard](The-Dashboard#automatic-session-names). |
| Spawned Tabs Follow Their Parent | A session started by another one (an agent's worker, a `parentSessionId` spawn) follows its parent's tab into its group and moves with it until you move it by hand; the row menu then says where it sits and offers *Follow parent again*. Off, it starts right after its parent and stays put. Decided when the tab is created, so flipping it leaves existing tabs alone. Synced, off by default. |
+8
View File
@@ -77,6 +77,14 @@ An agent tab shows its CLI's logo before the name, and a shell tab an `SH` badge
on Tabs** (App Settings → Appearance → Tabs) hides the logos on that device; the tile and split
headers and the Run menus keep theirs.
**New Session Button on Tabs** (same place, per device, off by default) adds a **+** beside
the tab's gear. It lists the CLIs that tab's case can start, each with its logo and name (a
Docker case lists what its container has), and a pick starts one session in that tab's case,
or the worktree it runs in, and in its named group. The Run button keeps its own mode and case.
Wherever a tab has a row menu (the vertical rail, the sidebar, `Shift+F10` on a grouped row),
the same list is its **New session here…** entry. From a tab outside any named group, the new
session lands in the case's default group if the case has one, as a Run from the toolbar does.
**Status is carried by the dot and the tab's own styling:**
| Look | Meaning |
+1 -1
View File
@@ -34,7 +34,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Entrance animations** (`entrance-animations.js`, all OFF by default): opt-in animations for tabs, terminal, windows, connection lines and tile-grid tiles, chosen via `data-tab-anim` / `data-term-anim` / `data-win-anim` / `data-line-anim` / `data-tile-anim` on `<html>`; the default `legacy` theme short-circuits every hook (tiles keep the grid's own `settle`). ⚠️ Tabs and lines are destroyed mid-animation on re-render, so re-apply to the fresh element by id with a negative `animation-delay` (resume, never restart). ⚠️ Terminal-pane styles may animate only transform / opacity / clip-path (anything else resizes the PTY via FitAddon); `blur` is the ONE sanctioned `filter` exception, do not generalise it. ⚠️ Line glow lives in `--line-glow` so blur keyframes interpolate. Every animation setting lives in App Settings → **Animations** (`#settings-animations`); put new ones there. ⚠️ Tiles are OFF by default (Animations → Tile Animations, default `settle` = the grid's own fade, no screen beat); a theme only presets it. A tile's FRAME animates transform/opacity only (six at once, no filter) with `tile-enter*`/`tile-leave*` keyframe names (what the mount and the still copy listen for); its SCREEN replays the pane style on `.tile-body.term-enter`; a reload's restore always settles. Persisted per-device in `codeman:*Anim` localStorage keys, never in `SettingsUpdateSchema`; lab at `?animlab=1`. Test: `test/entrance-animations.test.ts`. → [architecture-invariants#entrance-animations](../../docs/architecture-invariants.md#entrance-animations)
**Mobile tab strip scrolling** (issue #257): under 768px the tab strip scrolls horizontally, so the active tab must be kept reachable. `_updateActiveTabImmediate()` reveals it via `computeTabScrollLeft()` (constants.js, rect math on the strip's own `scrollLeft`, never `scrollIntoView()`, which scrolls the document under the fixed header); `_fullRenderSessionTabs()` must restore `scrollLeft` across rebuilds and re-reveal only when the active tab changed (`_lastRenderedActiveTabId`) or, grouped by state, the ACTIVE tab moved to another state band (`_noteActiveTabBand()`, both render paths, scrolling row only; another tab's move never scrolls). ⚠️ The phone-block `min-width` on `.session-tab.active .tab-name` keeps the tab's centre off the gear/close icons, sized for numberless tabs 10+ (floor 40px); do not shrink it. ⚠️ Never reintroduce hoisting the active session to the front of the strip. Tests: `test/mobile-tab-tap-zones.test.ts`, `test/tab-triage.test.ts`. → [architecture-invariants#mobile-tab-strip-scrolling](../../docs/architecture-invariants.md#mobile-tab-strip-scrolling)
**Mobile tab strip scrolling** (issue #257): under 768px the tab strip scrolls horizontally, so the active tab must be kept reachable. `_updateActiveTabImmediate()` reveals it via `computeTabScrollLeft()` (constants.js, rect math on the strip's own `scrollLeft`, never `scrollIntoView()`, which scrolls the document under the fixed header); `_fullRenderSessionTabs()` must restore `scrollLeft` across rebuilds and re-reveal only when the active tab changed (`_lastRenderedActiveTabId`) or, grouped by state, the ACTIVE tab moved to another state band (`_noteActiveTabBand()`, both render paths, scrolling row only; another tab's move never scrolls). ⚠️ The phone-block `min-width` on `.session-tab.active .tab-name` keeps the tab's centre off the gear/close icons, sized for numberless tabs 10+ (floor 40px); do not shrink it. With the opt-in tab "+" on (`showTabNewButton`, `html.tabs-show-new`) a third icon joins them and the reserve grows to 68px, still under the 80px `max-width`. ⚠️ Never reintroduce hoisting the active session to the front of the strip. Tests: `test/mobile-tab-tap-zones.test.ts`, `test/tab-triage.test.ts`. → [architecture-invariants#mobile-tab-strip-scrolling](../../docs/architecture-invariants.md#mobile-tab-strip-scrolling)
**Session list layout: header strip or left sidebar** (`sessionListLayout`, default `header`; per-device via `displayKeys`, also in `SettingsUpdateSchema`): the list can move into a collapsible `<aside>` (Alt+B, `toggleSessionSidebar`) or, via `tabOrientation`, a resizable vertical `#tabRail` (desktop/tablet only). ⚠️ There is ONE `#sessionTabs`, MOVED between hosts, never a second list: `applySessionListLayout()` runs first, then `applyTabOrientation()`, both BEFORE `applyTabWrapSettings()`, and both arm/disarm `_startSidebarRichClock()`. ⚠️ Axis decisions use `_isVerticalTabList()`, never `isSessionSidebarActive()` alone. ⚠️ Rich rows share one gate, `isRichTabRows()`; rich CSS pairs sidebar+rail with comma-grouped selectors, never `:is()`, and card rules stay rail-scoped. ⚠️ Rail sort (`tabRailSort`, default `activity`) is the flex `order` property only, never a DOM reorder; the arrow-key walk and the phone swipe follow computed `order`. ⚠️ Leaving sidebar mode clears `_sidebarFilter`; the handheld overlay drawer is `inert` when closed, the docked rail never. ⚠️ The rail's **Search sessions** box (`setTabRailSearch`, in memory only) and the sidebar filter share ONE row filter, `_applyTabListFilter()` over the pure `CodemanTabSearch` (constants.js): classes only, never a reorder or layout write; the rail matches the name, the sidebar name + folder. ⚠️ A session row with a tab alert (`tabAlerts`, red or yellow) is never hidden by either box: it goes in as `keep: true`, counts toward its group (which stays on screen) but not toward `matchCount`. ⚠️ Escape in the rail box is claimed by the global capture-phase Escape branch (the box's own `onkeydown` runs after it, too late to stop `closeAllPanels()`), and a filter change that shows or hides anything redraws the connector lines, since a keystroke re-renders nothing; a floating window finds its parent tab only through `_paintedSessionTab()` (a hidden row's rect is all zero but truthy, which drew connectors from the viewport's corner). While it runs `_projectTabGroups()` projects every group open (a collapsed group's rows are not in the DOM) and `toggleTabGroupCollapsed()` refuses, leaving the stored collapse untouched; drag stays on during a search (owner decision), a drop landing between the visible neighbours; `applyTabOrientation()` clears it off the rail. Tests: `test/tab-rail-search.test.ts`, `test/tab-rail-search.browser.test.ts`. → [architecture-invariants#session-list-layout-header-strip-vs-left-sidebar](../../docs/architecture-invariants.md#session-list-layout-header-strip-vs-left-sidebar)
+123 -11
View File
@@ -7169,7 +7169,9 @@ class CodemanApp {
: `<span class="tab-harness run-mode-dot ${escapeHtml(mode)}" aria-hidden="true"></span>`;
const inlineSessionActions = this.shouldInlineSessionActions();
const tabActionsHtml = `<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">&#x2699;</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">&#x29C9;</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">&times;</span><button type="button" class="tab-more" onclick="event.stopPropagation(); app.openTabRailActionMenu(event, ${escapeHtml(JSON.stringify(id))})" title="Session actions" aria-label="Session actions">&#x22EF;</button></span>`;
// The "+" announces a menu, so Enter and Space open it: the strip's own key
// handler acts only on a focused tab, and the header strip has no row menu.
const tabActionsHtml = `<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">&#x2699;</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">&#x29C9;</span><span class="tab-new" onclick="event.stopPropagation(); app.openTabNewSessionMenu(event, ${escapeHtml(JSON.stringify(id))})" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); event.stopPropagation(); app.openTabNewSessionMenu(event, ${escapeHtml(JSON.stringify(id))}); }" title="New session here" aria-label="New session in this tab's case" aria-haspopup="menu" tabindex="0">+</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">&times;</span><button type="button" class="tab-more" onclick="event.stopPropagation(); app.openTabRailActionMenu(event, ${escapeHtml(JSON.stringify(id))})" title="Session actions" aria-label="Session actions">&#x22EF;</button></span>`;
rowHtml.set(id, `<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${paneExitBadge ? ' tab-agent-exited' : ''}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}${this._tileGrid?.has(id) ? ' in-tiles' : ''}"${richData}${railOrderStyle} data-id="${id}" data-color="${color}" ${loadState ? `data-load-phase="${escapeHtml(loadState.phase)}"` : ''} onclick="app.handleSessionTabClick(event, ${escapeHtml(JSON.stringify(id))})" oncontextmenu="event.preventDefault(); app.startInlineRename(${escapeHtml(JSON.stringify(id))})" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-busy="${loadState ? 'true' : 'false'}" aria-label="${escapeHtml(paneExitAriaLabel(name, paneExitBadge))}" data-aria-source="${escapeHtml(paneExitAriaLabel(name, paneExitBadge))}" ${tabTooltip ? `title="${escapeHtml(tabTooltip)}"` : ''}>
${_tabIdx < 9 ? '<span class="tab-number">' + (_tabIdx + 1) + '</span>' : ''}
@@ -8398,12 +8400,100 @@ class CodemanApp {
return true;
}
/**
* A tab's "+" (and the row menu's "New session here…"): the CLIs that tab's
* case can start, each as its logo and name like the Run menus. A pick starts
* ONE session beside that tab: its case (or the managed worktree it runs in)
* and its named group, if it has one, through `_launchOnce`, so the Run
* button's mode and case are untouched.
*/
openTabNewSessionMenu(event, sessionId) {
const session = this.sessions.get(sessionId);
const worktree = this._managedWorktreeOfSession?.(session) || null;
const caseEntry = worktree ? null : this._tabCaseOf(session);
if (!worktree && !caseEntry) {
event?.stopPropagation?.();
this.showToast?.("This tab's folder is not a case, so there is nothing to start beside it.", 'info');
return false;
}
const caseName = worktree ? worktree.caseName : caseEntry.name;
// An ungrouped tab sends no group, so the server's case default group (if the
// case has one) places the new session, as it does for a toolbar Run.
const tabGroupId = this._tabRefLocation({ kind: 'session', id: sessionId })?.groupId || null;
// The toolbar probes only the case it has selected, so ask this tab's container
// now: this open reads what is already known, the next one the container's answer.
if (caseEntry?.location === 'docker' && !this._dockerCaseModes?.[caseName]) {
void this._probeDockerCaseModes(caseEntry, null);
}
// The phone overview's list, gated by the Run menu's own rule for this case
// (_runModeAvailableForCase: the container's CLIs for a Docker case; shell is
// never gated), in the Run menu's order: agents in catalog order, the shell last.
const isShell = (entry) => registryCliById(entry.mode)?.kind === 'shell';
const available = mobileOverviewRunModes().filter(
(entry) => isShell(entry) || this._runModeAvailableForCase(entry.mode, caseName)
);
const modes = [...available.filter((entry) => !isShell(entry)), ...available.filter(isShell)];
const current = this.runMode;
const actions = modes.map((entry) => ({
label: entry.label,
icon: entry.mode,
className: 'run-mode-option',
selected: entry.mode === current,
run: () =>
this._launchOnce(entry.mode, {
...(worktree ? { worktree } : { caseName }),
...(tabGroupId ? { tabGroupId } : {}),
}),
}));
return this._openTabLayoutMenu(event, `new:${sessionId}`, 'New session here', actions, { anyLayout: true });
}
/**
* The case a session tab belongs to, by what the session runs on. GET /api/cases
* gives a remote or Docker case a DISPLAY path (`user@host:/path`,
* `container:/path`) with the raw values under `remote` / `docker`, while a
* session carries its raw folder, so a path match alone misses those cases or
* lands on a local case at the same folder. A Docker session belongs to its
* container's case on its own engine host, a remote one to the case on its own
* host whose path encloses its own, a local one to the deepest case enclosing
* its folder (a display path never encloses one). Null when none fits.
*/
_tabCaseOf(session) {
if (!session) return null;
const cases = this.cases || [];
const deepestEnclosing = (dir, candidates, rootOf) => {
let best = null;
let bestLength = -1;
for (const c of candidates) {
const root = (rootOf(c) || '').replace(/\/+$/, '');
if (!root || (dir !== root && !dir.startsWith(`${root}/`)) || root.length <= bestLength) continue;
best = c;
bestLength = root.length;
}
return best;
};
if (session.docker) {
const { hostId, containerName } = session.docker;
return (
cases.find((c) => c.location === 'docker' && c.docker?.hostId === hostId && c.docker?.container === containerName) ||
null
);
}
if (session.remote) {
const { hostId, remotePath } = session.remote;
const onHost = cases.filter((c) => c.location === 'remote' && c.remote?.hostId === hostId);
return deepestEnclosing((remotePath || '').replace(/\/+$/, ''), onHost, (c) => c.remote.path);
}
return deepestEnclosing((session.workingDir || '').replace(/\/+$/, ''), cases, (c) => c.path);
}
// ─── Group and web-tab menus (right-click, the header's ⋯, Shift+F10) ──
/**
* Close the open group / web-tab menu. Every dismissal path lands here:
* Escape, a pointer outside it, focus leaving it, Tab, a viewport resize, an
* action, and any full re-render of the rail (which would orphan its trigger).
* Close the open group / web-tab / tab "+" menu. Every dismissal path lands
* here: Escape, a pointer outside it, focus moving to an element outside it,
* Tab, a viewport resize, an action, and any full re-render of the rail (which
* would orphan its trigger).
*/
closeTabGroupMenu({ restoreFocus = false } = {}) {
const menu = this._tabGroupMenu;
@@ -8463,7 +8553,7 @@ class CodemanApp {
]);
}
_openTabLayoutMenu(event, identity, ariaLabel, actions) {
_openTabLayoutMenu(event, identity, ariaLabel, actions, { anyLayout = false } = {}) {
event?.preventDefault?.();
event?.stopPropagation?.();
const trigger = event?.currentTarget || null;
@@ -8474,7 +8564,7 @@ class CodemanApp {
}
this.closeTabGroupMenu();
this.closeTabRailActionMenu?.();
if (!this._tabLayoutEditable()) return false;
if (!anyLayout && !this._tabLayoutEditable()) return false;
const menu = document.createElement('div');
menu.className = 'tab-rail-action-menu tab-layout-group-action-menu';
menu.setAttribute('role', 'menu');
@@ -8483,8 +8573,17 @@ class CodemanApp {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('role', 'menuitem');
button.textContent = action.label;
if (action.icon) {
// A Run menu entry's markup (renderRegistryRunOptions): the CLI's logo, then its name.
const dot = document.createElement('span');
dot.className = `run-mode-dot ${action.icon}`;
dot.setAttribute('aria-hidden', 'true');
button.append(dot, action.label);
} else {
button.textContent = action.label;
}
if (action.className) button.className = action.className;
if (action.selected) button.classList.add('selected');
button.addEventListener('click', () => {
this.closeTabGroupMenu();
action.run();
@@ -8519,6 +8618,12 @@ class CodemanApp {
document.addEventListener('keydown', this._tabGroupMenuKeydown, true);
window.addEventListener('resize', this._tabGroupMenuResize);
menu.addEventListener('keydown', (keyEvent) => {
// A held Enter or Space that opened the menu repeats onto the entry it
// focuses; cancelling the repeat keeps it from also picking that entry.
if (keyEvent.repeat && (keyEvent.key === 'Enter' || keyEvent.key === ' ')) {
keyEvent.preventDefault();
return;
}
const buttons = [...menu.querySelectorAll('button')];
const at = buttons.indexOf(document.activeElement);
if (keyEvent.key === 'ArrowDown' || keyEvent.key === 'ArrowUp') {
@@ -8533,13 +8638,20 @@ class CodemanApp {
this.closeTabGroupMenu({ restoreFocus: true });
}
});
// Focus leaving by any other route (a click elsewhere, a programmatic move).
// Hops between the menu's own items are not a departure.
// Focus moving to another element outside the menu (a programmatic move;
// a click elsewhere is the pointerdown listener's). Hops between the
// menu's own items are not a departure, and neither is focus going nowhere:
// Safari never focuses a clicked button, so a press on an item blurs the
// focused one with no relatedTarget, and closing then dropped its click
// (the tile count menu's rule, tile-grid.js). Nor is focus landing on the
// trigger: a press on a focusable one (a tab's "+") focuses it before its
// click, and closing there let that click open the menu again.
menu.addEventListener('focusout', (focusEvent) => {
if (focusEvent.relatedTarget && menu.contains(focusEvent.relatedTarget)) return;
const to = focusEvent.relatedTarget;
if (!to || menu.contains(to) || trigger?.contains?.(to)) return;
if (this._tabGroupMenu === menu) this.closeTabGroupMenu();
});
menu.querySelector('button')?.focus();
(menu.querySelector('button.selected') || menu.querySelector('button'))?.focus();
return true;
}
+8
View File
@@ -107,6 +107,11 @@
'New session': '新建会话',
// The Cmd+K palette's new-session agent switch (panels-ui.js, its title tooltip).
'Agent for the new session (Left/Right to change)': '新会话使用的智能体(按左/右方向键切换)',
'New session here': '在此新建会话',
'New session here…': '在此新建会话…',
"New session in this tab's case": '在此标签页的案例中新建会话',
"This tab's folder is not a case, so there is nothing to start beside it.":
'此标签页的文件夹不是案例,无法在其旁边新建会话。',
'A session is already starting.': '已有会话正在启动。',
'Follow parent again': '重新跟随父会话',
'Parent closed; placed on its own': '父会话已关闭;单独放置',
@@ -484,6 +489,9 @@
'会话列表显示为顶栏横向标签条,或左侧可折叠侧边栏(Alt+B)。完整侧边栏为每个会话显示与主界面相同的详细信息。',
'Tall Tabs (Name + Folder)': '双行标签(名称 + 文件夹)',
'Pop-out Button on Tabs': '标签页弹出窗口按钮',
'New Session Button on Tabs': '标签页新建会话按钮',
'A + on the tab that starts a session in the same case and group, in any installed CLI.':
'标签页上的 + 按钮,可在同一案例和分组中,用任一已安装的 CLI 启动新会话。',
'CLI Logos on Tabs': '标签页上的 CLI 图标',
"Show each agent's CLI logo before the session name on tabs and the home screen's tab list. Off leaves the status dot and the shell's SH badge. Tiles, split headers and the Run menus keep their logos.":
'在标签页和主界面的标签列表中,于会话名称前显示每个智能体的 CLI 图标。关闭后仍保留状态圆点和 Shell 的 SH 标记。平铺、分屏标题栏和运行菜单中的图标不受影响。',
+7
View File
@@ -2497,6 +2497,13 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowTabDetachButton"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="new session plus add tab same case group cli">
<div class="set-row-text">
<span class="set-row-label">New Session Button on Tabs</span>
<span class="set-row-desc">A + on the tab that starts a session in the same case and group, in any installed CLI.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowTabNewButton"><span class="slider"></span></label>
</div>
<div class="set-row" id="appSettingsTileDetachItem" data-search="detach tiles tile pop out window drag move another window">
<div class="set-row-text">
<span class="set-row-label">Detach Tiles <span class="set-tag">desktop</span> <span class="set-tag set-tag-beta">beta</span></span>
+26 -1
View File
@@ -949,6 +949,29 @@ html.mobile-init .file-browser-panel {
display: none !important;
}
/* The "+" is opt-in (showTabNewButton, per-device; html.tabs-show-new).
Switched on it joins gear + close on the active tab only, and the label
reserve above grows to clear all three (test/mobile-tab-tap-zones). */
.session-tab .tab-new {
display: none;
}
html.tabs-show-new .session-tab.active .tab-new {
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 1rem;
line-height: 1;
width: 28px;
height: 32px;
padding: 0;
opacity: 0.8;
}
html.tabs-show-new .session-tab.active .tab-name {
min-width: 68px;
}
/* Gear icon on active tab - tiny, subtle */
.session-tab.active .tab-gear {
display: inline-flex;
@@ -3427,7 +3450,8 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
@media (hover: none) and (pointer: coarse) {
/* Remove hover-dependent UI patterns */
.session-tab .tab-close,
.session-tab .tab-gear {
.session-tab .tab-gear,
.session-tab .tab-new {
opacity: 1;
width: auto;
padding: 0.15rem 0.25rem;
@@ -4127,6 +4151,7 @@ html[data-session-list="sidebar"] .session-sidebar .session-tab {
Matches the (hover: none) block above, but has to be repeated here because
the phone block hides them on non-active tabs with (0,2,0). */
html[data-session-list="sidebar"] .session-sidebar .session-tab .tab-gear,
html[data-session-list="sidebar"] .session-sidebar .session-tab .tab-new,
html[data-session-list="sidebar"] .session-sidebar .session-tab .tab-close {
display: inline-flex;
align-items: center;
+40 -23
View File
@@ -684,9 +684,12 @@ Object.assign(CodemanApp.prototype, {
/**
* Run using the selected mode (Claude Code, OpenCode, Codex, Gemini, or Antigravity).
* `options` comes from the tab group menu's "New session": `count` overrides
* the instance steppers for this launch only, `tabGroupId` rides every create
* request so the server places the session in that group.
* `options` comes from the tab group menu's "New session", `_launchOnce` (a
* worktree, a tab's "+"): `count` overrides the instance steppers for this
* launch only, `tabGroupId` rides every create request so the server places the
* session in that group, `caseName` launches in that case instead of the
* toolbar's selected one, and `mode` starts that CLI instead of the Run
* button's mode, which is never touched.
*/
async run(options = {}) {
if (this._runInFlight) return;
@@ -701,7 +704,7 @@ Object.assign(CodemanApp.prototype, {
}
try {
const mode = this._runMode || 'claude';
const mode = options.mode || this._runMode || 'claude';
if (mode === 'shell') {
return await this.runShell(options);
}
@@ -820,7 +823,8 @@ Object.assign(CodemanApp.prototype, {
* never gated; both callers skip it before asking.
*
* Reads only what is already known and never starts a container probe: the
* Run menu starts one (_probeDockerCaseModes), and its answer lands in
* Run menu and a tab's "+" (openTabNewSessionMenu, app.js) start one
* (_probeDockerCaseModes), and its answer lands in
* _dockerCaseModes, which this reads. Until then (a probe still in flight)
* the stored availableModes decide, else nothing is gated.
*/
@@ -2014,11 +2018,28 @@ Object.assign(CodemanApp.prototype, {
}
},
/** The case a launch runs in: its worktree's, the one it names (a tab's "+"), else the toolbar's. */
_runCaseName(options) {
if (options.worktree) return options.worktree.caseName;
return options.caseName || document.getElementById('quickStartCase').value || 'testcase';
},
/**
* Re-reads the case list after a launch, keeping the toolbar on its own case.
* The no-argument reload would re-select the server's `lastUsedCase`, and a
* tab's "+" launching through quick-start sets that to the tab's case while the
* toolbar stays where it was, so every later launch (a worktree's, a plain Run,
* a group's "New session") would otherwise move the toolbar there.
*/
_reloadCasesAfterRun() {
this.loadQuickStartCases(document.getElementById('quickStartCase').value || null);
},
async runClaude(options = {}) {
// `options.worktree` ({ caseName, name, path }, from the worktree modal): the session runs in
// that git worktree of the case and its tab is named after the worktree.
const wt = options.worktree || null;
const caseName = wt ? wt.caseName : document.getElementById('quickStartCase').value || 'testcase';
const caseName = this._runCaseName(options);
const nameBase = wt ? wt.name : caseName;
const tabCount = this._readTabCount(options.count);
const group = options.tabGroupId ? { tabGroupId: options.tabGroupId } : {};
@@ -2123,7 +2144,7 @@ Object.assign(CodemanApp.prototype, {
this._appendSessionLaunchStatus(ownsLaunchTerminal, `All ${tabCount} remote session(s) ready`);
if (remoteIds[0]) {
await this.selectSession(remoteIds[0]);
this.loadQuickStartCases();
this._reloadCasesAfterRun();
}
this.terminal.focus();
return;
@@ -2202,7 +2223,7 @@ Object.assign(CodemanApp.prototype, {
// Auto-switch to the new session using selectSession (does proper refresh)
if (firstSessionId) {
await this.selectSession(firstSessionId);
this.loadQuickStartCases();
this._reloadCasesAfterRun();
}
this.terminal.focus();
@@ -2249,7 +2270,7 @@ Object.assign(CodemanApp.prototype, {
async runShell(options = {}) {
// `options.worktree`: see runClaude.
const wt = options.worktree || null;
const caseName = wt ? wt.caseName : document.getElementById('quickStartCase').value || 'testcase';
const caseName = this._runCaseName(options);
const nameBase = wt ? wt.name : caseName;
// Run Shell reads the toolbar's one instance stepper, like every other run*();
// its own second `− 1 +` group (#shellCount) was removed (#428).
@@ -2450,7 +2471,7 @@ Object.assign(CodemanApp.prototype, {
// `options.worktree`: see runClaude. Quick-start resolves it server-side (`worktree`), so the
// session starts through the same path as any other, only in the worktree's folder.
const wt = options.worktree || null;
const caseName = wt ? wt.caseName : document.getElementById('quickStartCase').value || 'testcase';
const caseName = this._runCaseName(options);
// Remote/docker cases run the CLI on the OTHER side — the local status
// probe and the local-only config/env below don't apply (quick-start
// rejects them for remote cases).
@@ -5859,7 +5880,7 @@ Object.assign(CodemanApp.prototype, {
const created = r.data.worktree;
this.showToast?.(`Worktree ${created.name} created on branch ${created.branch}`, 'success');
this.closeWorktreeModal();
await this._launchInWorktree({ caseName, name: created.name, path: created.path }, mode);
await this._launchOnce(mode, { worktree: { caseName, name: created.name, path: created.path } });
} finally {
if (btn) btn.disabled = false;
}
@@ -5871,26 +5892,22 @@ Object.assign(CodemanApp.prototype, {
if (!caseName || !wt) return;
const mode = this._selectedWorktreeMode();
this.closeWorktreeModal();
await this._launchInWorktree({ caseName, name, path: wt.path }, mode);
await this._launchOnce(mode, { worktree: { caseName, name, path: wt.path } });
},
/**
* Start ONE session of `mode` in a worktree through run(), the Run button's own entry (its
* launch lock, its per-mode paths), with the same temporary `_runMode` swap the custom-model
* entries use, so the Run button's chosen mode is untouched afterwards.
* Start ONE session of `mode` through run(), the Run button's own entry (its launch lock, its
* per-mode paths), outside the toolbar's choices: `runOptions` names a worktree, or a case and
* tab group (a tab's "+"). The mode rides the call (`run({ mode })`) rather than a swap of the
* Run button's mode, so a mode the user picks while the launch is pending is never overwritten.
*/
async _launchInWorktree(worktree, mode) {
async _launchOnce(mode, runOptions) {
if (this._runInFlight) {
this.showToast?.('A launch is already in progress', 'info');
return;
}
const previous = this._runMode;
this._runMode = mode || previous;
try {
await this.run({ count: 1, worktree });
} finally {
this._runMode = previous;
}
if (runOptions.tabGroupId) this.toggleTabGroupCollapsed?.(runOptions.tabGroupId, false);
await this.run({ count: 1, ...runOptions, ...(mode ? { mode } : {}) });
},
/** The Codeman-managed worktree a session runs in, or null (see managedWorktreeOfDir). */
+8
View File
@@ -667,6 +667,8 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsShowTabDetachButton').checked =
this.tabDetachButtonEnabled?.(settings, defaults)
?? (settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false);
// The tab's "+" (applyHeaderVisibilitySettings): per-device, OFF unless switched on.
document.getElementById('appSettingsShowTabNewButton').checked = settings.showTabNewButton === true;
// Detach Tiles (tile-grid.js): per-device, OFF unless switched on. The tile
// grid is desktop-only, so the row is hidden elsewhere, like the lineage lines.
document.getElementById('appSettingsTileDetach').checked = settings.tileDetachEnabled === true;
@@ -3056,6 +3058,7 @@ Object.assign(CodemanApp.prototype, {
tabArrangement: document.getElementById('appSettingsTabArrangement').value,
tabStateOrder: document.getElementById('appSettingsTabStateOrder').value,
showTabDetachButton: document.getElementById('appSettingsShowTabDetachButton').checked,
showTabNewButton: document.getElementById('appSettingsShowTabNewButton').checked,
tileDetachEnabled: document.getElementById('appSettingsTileDetach').checked,
sessionListLayout: document.getElementById('appSettingsSessionListLayout').value,
sessionSidebarFontSize: this.resolveSessionSidebarFontSize(
@@ -3332,6 +3335,7 @@ Object.assign(CodemanApp.prototype, {
gitStatusMaxRepos: _gsm,
gitStatusTimeoutSeconds: _gst2,
showTabDetachButton: _tdb,
showTabNewButton: _tnb,
// Detach Tiles: what a tile drag does is a property of this device's
// windows, and the key is absent from the .strict() SettingsUpdateSchema.
tileDetachEnabled: _tde,
@@ -4475,6 +4479,9 @@ Object.assign(CodemanApp.prototype, {
this.tabDetachButtonEnabled?.(settings, defaults)
?? (settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false);
document.documentElement.classList.toggle('tabs-show-detach', showTabDetach);
// The tab's "+" (new session beside it): per-device and opt-in everywhere,
// like the pop-out button. On a phone it also widens the active tab (mobile.css).
document.documentElement.classList.toggle('tabs-show-new', settings.showTabNewButton === true);
const compactHeader = MobileDetection.getDeviceType() !== 'desktop';
const showFontControls = compactHeader ? false : (settings.showFontControls ?? defaults.showFontControls ?? false);
const showSystemStats = compactHeader ? false : (settings.showSystemStats ?? defaults.showSystemStats ?? true);
@@ -4992,6 +4999,7 @@ Object.assign(CodemanApp.prototype, {
'autoCopySelection', 'copyStripMargin',
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds',
'showTabDetachButton',
'showTabNewButton',
'mobileOverviewEnabled',
'sessionLineageLines',
'showSplitButton',
+30 -1
View File
@@ -2992,6 +2992,33 @@ html[data-header-stats] .header-system-stats .stat-item[hidden] {
transform: rotate(45deg);
}
/* "+" (new session beside this tab, app.openTabNewSessionMenu): same reveal as the gear. */
.session-tab .tab-new {
opacity: 0;
width: 0;
padding: 0;
font-size: 1rem;
line-height: 1;
color: var(--text-muted);
cursor: pointer;
overflow: hidden;
transition: opacity 0.15s, width 0.15s, padding 0.15s;
}
.session-tab.active .tab-new {
opacity: 1;
width: auto;
padding: 0 0.3rem;
}
.session-tab .tab-new:hover {
color: var(--accent-hover);
}
/* Per-device toggle (App Settings → Tab Bar), mirrored as tabs-show-new on <html>
by settings-ui.js. !important so no layout's reveal rule (sidebar, touch) wins. */
html:not(.tabs-show-new) .session-tab .tab-new {
display: none !important;
}
/* ===== Session detach / undock (beta/session-detach) ===================== */
/* Pop-out (detach) icon on each tab — mirrors .tab-gear reveal-on-hover. */
@@ -3145,7 +3172,7 @@ html[data-tab-orientation='vertical']:not(.tab-rail-compact) .tab-rail
pointer-events: auto;
}
html[data-tab-orientation='vertical'].tab-rail-compact .session-tab .tab-actions > :is(.tab-gear, .tab-detach, .tab-close) {
html[data-tab-orientation='vertical'].tab-rail-compact .session-tab .tab-actions > :is(.tab-gear, .tab-new, .tab-detach, .tab-close) {
display: none;
}
@@ -19865,6 +19892,7 @@ html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name-row > .ta
actions permanently visible on the active session — no layout jitter when
the pointer crosses the list. */
html[data-session-list="sidebar"] .session-sidebar .session-tab.active .tab-gear,
html[data-session-list="sidebar"] .session-sidebar .session-tab.active .tab-new,
html[data-session-list="sidebar"] .session-sidebar .session-tab.active .tab-detach,
html[data-session-list="sidebar"] .session-sidebar .session-tab.active .tab-close {
opacity: 1;
@@ -20379,6 +20407,7 @@ html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .se
html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .tab-info,
html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .tab-number,
html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .tab-gear,
html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .tab-new,
html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .tab-detach,
html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .tab-close {
display: none;
+7
View File
@@ -319,6 +319,7 @@ Object.assign(CodemanApp.prototype, {
event.preventDefault();
event.stopPropagation();
this.closeTabRailActionMenu();
this.closeTabGroupMenu?.();
const trigger = event.currentTarget;
const menu = document.createElement('div');
menu.className = 'tab-rail-action-menu';
@@ -327,6 +328,12 @@ Object.assign(CodemanApp.prototype, {
const settings = this.loadAppSettingsFromStorage();
const actions = [
{ label: 'Session options', run: () => this.openSessionOptions(sessionId) },
// The row's "+" (showTabNewButton on) as a menu item: a keyboard route beside
// Enter or Space on the "+" itself, and its only route in the compact rail,
// which hides it. Session rows only: tiles share this menu and carry no "+".
...(document.documentElement.classList.contains('tabs-show-new') && trigger.closest('.session-tab')
? [{ label: 'New session here…', run: () => this.openTabNewSessionMenu({ currentTarget: trigger }, sessionId) }]
: []),
// Focus and group placement (vertical rail with a tab layout only; [] elsewhere).
...(this._tabRefFocusActions?.({ kind: 'session', id: sessionId }) || []),
...(this._tabRefMoveActions?.({ kind: 'session', id: sessionId }) || []),
+11
View File
@@ -162,6 +162,17 @@ describe('phone tab tap zones', () => {
expect(phoneDeclarations('.session-tab .tab-gear').display).toBe('none');
});
it('with the opt-in "+" switched on, the wider reserve clears all three icons', () => {
// showTabNewButton adds a third icon to the active phone tab (html.tabs-show-new)
// and a larger reserve to go with it; the same arithmetic must still hold.
const plus = phoneDeclarations('html.tabs-show-new .session-tab.active .tab-new');
const wide = len(phoneDeclarations('html.tabs-show-new .session-tab.active .tab-name')['min-width']);
expect(len(plus.width)).toBeGreaterThanOrEqual(28);
expect(wide).toBeGreaterThanOrEqual(requiredReserve() + len(plus.width) + ROUNDING_ALLOWANCE);
expect(wide).toBeLessThanOrEqual(len(nameShared['max-width']));
expect(phoneDeclarations('.session-tab .tab-new').display).toBe('none');
});
it('the pop-out icon stays out of the cluster on handhelds', () => {
// `icons` above counts gear + close only. If detach ever became visible on a
// phone the reserve would be ~30px short and the centre would walk back.
+111 -1
View File
@@ -3,13 +3,16 @@
* read and write it, and the create routes that carry the case into the real
* TabLayoutService so a new session lands in its case's group in the creating
* write (POST /api/sessions, and POST /api/quick-start for local, remote and
* Docker cases).
* Docker cases). The tab "+" picker (app.js) is driven end to end against the
* same routes, since an ungrouped tab relies on this fallback by design.
*
* Uses app.inject(), so no real HTTP port is needed.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { JSDOM } from 'jsdom';
import { homedir } from 'node:os';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
@@ -101,6 +104,56 @@ const unwrap = (raw: string) => {
return parsed.data ?? parsed;
};
/**
* The shipping frontend in JSDOM, with fetch answered by the route harnesses, so
* a click in the tab "+" picker reaches the real create route and layout service.
*/
async function bootTabApp(route: (url: string, init?: { method?: string; body?: string }) => Promise<unknown>) {
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
url: 'https://localhost/',
runScripts: 'outside-only',
});
if (dom.window.document.readyState !== 'complete') {
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const win = dom.window as any;
win.setInterval = () => 0;
win.requestAnimationFrame = () => 0;
win.__codemanCliCatalog = [{ id: 'shell', kind: 'shell', label: 'Shell', enabled: true }];
const publicDir = join(process.cwd(), 'src/web/public');
win.eval(
'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' +
'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
['constants.js', 'app.js', 'mobile-overview.js', 'session-ui.js']
.map((file) => readFileSync(join(publicDir, file), 'utf8'))
.join('\n;\n') +
'\n;window.__CdgCodemanApp = CodemanApp;'
);
win.fetch = async (url: string, init?: { method?: string; body?: string }) => {
const body = await route(url, init);
return { ok: true, status: 200, json: async () => body };
};
win.document.body.innerHTML = '<div id="sessionTabs"></div><select id="quickStartCase"></select>';
const app = Object.create(win.__CdgCodemanApp.prototype);
Object.assign(app, {
$: (id: string) => win.document.getElementById(id),
sessions: new Map(),
activeSessionId: 'tab-1',
terminal: { clear: () => {}, writeln: () => {}, focus: () => {}, cols: 80, rows: 24 },
_runMinLockMs: 0,
_runMode: 'claude',
getTerminalDimensions: () => null,
selectSession: async () => {},
loadQuickStartCases: () => {},
showToast: vi.fn(),
_applyTabLayout: () => {},
_onSessionCreated: () => {},
_renderSessionTabsImmediate: () => {},
});
return { app, win };
}
describe('case default group: create routes', () => {
let harness: RouteTestHarness;
let world: World;
@@ -280,6 +333,63 @@ describe('case default group: create routes', () => {
// The route's own error path ran cleanupSession for the registered id.
expect(harness.ctx.cleanupSession).toHaveBeenCalledTimes(1);
});
describe('from a tab "+" in the browser', () => {
/** Opens the tab's "+" picker, picks Shell, and returns the create request and the new session's group. */
async function launchBeside(tabGroupId: string | null) {
const cases = await createRouteTestHarness(registerCaseRoutes);
const creates: Array<Record<string, unknown>> = [];
try {
const { app, win } = await bootTabApp(async (url, init) => {
const payload = init?.body ? JSON.parse(init.body) : undefined;
if (url === '/api/sessions' && init?.method === 'POST') creates.push(payload);
const target = url.startsWith('/api/cases/') ? cases : harness;
const res = await target.app.inject({ method: (init?.method ?? 'GET') as 'GET', url, payload });
// The envelope server.ts's preSerialization hook adds, which the harness does not install.
const body = res.body ? JSON.parse(res.body) : {};
return typeof body.success === 'boolean' ? body : { success: true, data: body };
});
app.cases = [{ name: CASE, path: caseDir }];
app.sessions.set('tab-1', { id: 'tab-1', name: 'w1-cdg', workingDir: caseDir });
app.tabLayout = {
...world.layouts[OWNER],
groups: world.layouts[OWNER].groups.map((g) => ({
...g,
refs: g.id === tabGroupId ? [{ kind: 'session', id: 'tab-1' }] : [],
})),
};
app.collapsedTabGroupIds = new Set();
app.toggleTabGroupCollapsed = () => {};
const plus = win.document.createElement('span');
win.document.body.appendChild(plus);
app.openTabNewSessionMenu({ preventDefault() {}, stopPropagation() {}, currentTarget: plus }, 'tab-1');
const shell = [...win.document.querySelectorAll('[aria-label="New session here"] button')].find(
(button: Element) => button.textContent === 'Terminal / Shell'
) as HTMLElement;
shell.click();
await vi.waitFor(() => expect(creates).toHaveLength(1));
await vi.waitFor(() => expect(harness.ctx.sessions.size).toBe(1));
const [id] = [...harness.ctx.sessions.keys()];
return { create: creates[0], group: groupOf(world.layouts[OWNER], id), toasts: app.showToast.mock.calls };
} finally {
await cases.app.close();
}
}
it('an ungrouped tab sends no group, so the case default group places the session (chosen on purpose)', async () => {
const { create, group, toasts } = await launchBeside(null);
expect(create).toEqual({ workingDir: caseDir, mode: 'shell', name: `s1-${CASE}` });
expect(group).toBe('g-ops');
// The launch went through: no error reported along the way.
expect(toasts.filter(([, kind]: [string, string]) => kind === 'error')).toEqual([]);
});
it('a grouped tab sends its own group, which wins over the case default', async () => {
const { create, group } = await launchBeside('g-core');
expect(create).toEqual({ workingDir: caseDir, mode: 'shell', name: `s1-${CASE}`, tabGroupId: 'g-core' });
expect(group).toBe('g-core');
});
});
});
describe('case default group: GET/PUT /api/cases/:name/default-group', () => {
+22 -2
View File
@@ -6,7 +6,8 @@
* /api/sessions, remote/docker and external-CLI /api/quick-start), that the
* one-session count overrides the toolbar steppers without touching them, that
* the layout returned by the create response is adopted BEFORE the new tab is
* drawn (so it is drawn inside its group), and that an ordinary Run sends no
* drawn (so it is drawn inside its group), that a tab's "+" (`caseName`) starts
* in that case rather than the toolbar's, and that an ordinary Run sends no
* group at all.
*
* Port: none (vm sandbox, stubbed fetch).
@@ -36,7 +37,7 @@ function harness(caseData: Record<string, unknown>, extra: { mode?: string } = {
const body = init?.body ? JSON.parse(init.body) : undefined;
requests.push({ url, body });
const json = (value: unknown) => ({ json: async () => value });
if (url === '/api/cases/proj') return json({ success: true, data: caseData });
if (url.startsWith('/api/cases/')) return json({ success: true, data: caseData });
if (url.endsWith('/status')) return json({ success: true, data: { available: true, runnable: true } });
if (url === '/api/sessions') {
const id = `sess-${++counter}`;
@@ -124,6 +125,25 @@ describe('launching into a tab group', () => {
expect(app._applyTabLayout).toHaveBeenCalledWith(LAYOUT);
});
// A tab's "+" launches beside that tab: its case, never the toolbar's selected one.
it.each([
// Claude's create body names no mode: it is the server's default.
['local Claude', 'claude', '/api/sessions', { workingDir: '/tmp/other' }],
['local Shell', 'shell', '/api/sessions', { mode: 'shell', workingDir: '/tmp/other' }],
['an external CLI', 'gemini', '/api/quick-start', { mode: 'gemini', caseName: 'other' }],
])('%s launches in `caseName` instead of the toolbar case', async (_label, mode, url, where) => {
const { app, elements, requests } = harness({ name: 'other', path: '/tmp/other' }, { mode });
await app.run({ count: 1, caseName: 'other' });
const made = creates(requests);
expect(made).toHaveLength(1);
expect(made[0].url).toBe(url);
expect(made[0].body).toMatchObject(where);
expect(JSON.stringify(made[0].body)).not.toContain('proj');
// The local paths look the case up by the given name, never the toolbar's.
if (url === '/api/sessions') expect(requests[0].url).toBe('/api/cases/other');
expect(elements.quickStartCase.value).toBe('proj');
});
it('an ordinary Run sends no group and keeps the stepper count', async () => {
const { app, requests } = harness({ name: 'proj', path: '/tmp/proj' });
await app.run();
+16
View File
@@ -910,6 +910,22 @@ describe('group menu', () => {
expect(app._tabGroupMenuKeydown).toBeNull();
});
it("Safari's item click (a blur with nowhere to go) keeps the menu open, so the item still runs", () => {
// Safari never focuses a clicked button: the press blurs the focused item
// with relatedTarget null, and closing on that dropped the click.
installFetch();
const app = makeApp();
open(app);
app.startTabGroupRename = vi.fn();
const buttons = document.querySelectorAll<HTMLElement>('.tab-layout-group-action-menu button');
const rename = [...buttons].find((button) => button.textContent === 'Rename group')!;
buttons[0].dispatchEvent(new win.FocusEvent('focusout', { bubbles: true, relatedTarget: null }));
expect(isOpen()).toBe(true);
rename.click();
expect(app.startTabGroupRename).toHaveBeenCalledWith('gx');
expect(isOpen()).toBe(false);
});
it('a pointer outside, Tab, focus leaving, a resize, a second open and a re-render all close it', () => {
installFetch();
const app = makeApp();
+839
View File
@@ -0,0 +1,839 @@
/**
* @fileoverview A session tab's "+" (`showTabNewButton`, per device, off by
* default) and the row menu's "New session here…": the picker of CLIs the
* tab's case can start, and the one-off launch beside that tab.
*
* Driven through the shipping CodemanApp inside JSDOM (app.js, tab-rail-resize.js,
* mobile-overview.js and session-ui.js loaded as the page loads them). Pins:
* - each entry is a Run menu entry (the CLI's logo, then its name), agents in
* catalog order and the shell last, the Run button's mode preselected;
* - the tab's case is found by what the session runs on: a Docker session's
* container, a remote session's host and path, a local session's folder among
* LOCAL cases only (the case records are shaped as GET /api/cases sends them:
* display paths for remote and Docker cases, the raw values nested);
* - which CLIs are offered follows the Run menu's own rule for that case
* (_runModeAvailableForCase): the host's CLIs for a local case, the
* container's for a Docker case (live probe, then the stored list, nothing
* gated for an owned container), only the shell for an unreadable one; the
* picker starts that probe when nothing is cached for a Docker case;
* - a pick runs ONE launch in the tab's case or managed worktree with the tab's
* named group, and an ungrouped tab sends no group (the server's case default
* group then applies, pinned end to end in case-default-group-routes.test.ts);
* - the Run button's mode and the toolbar case are left as they were, also when
* the mode is changed while the launch is pending and when the server has
* moved lastUsedCase to the tab's case, and a later launch that names no case
* (a worktree tab's "+", the toolbar Run, a group's "New session") keeps the
* toolbar's case too;
* - a failed launch reports the server's own error;
* - Enter and Space on the "+" open the picker (the header strip's only
* keyboard path) and stop there; every other key passes on to the strip; a
* held key's repeat cannot also pick the entry the picker focuses;
* - the row menu offers the picker on session rows only while the setting is on;
* - the picker closes on a re-render and gives focus back to the tab on Escape;
* - the setting stays per device and OFF until switched on, and every new
* string has its zh-CN entry.
*
* Port: none (stubbed fetch).
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { JSDOM } from 'jsdom';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { SettingsUpdateSchema } from '../src/web/schemas.js';
const PUBLIC = join(process.cwd(), 'src/web/public');
const read = (name: string) => readFileSync(join(PUBLIC, name), 'utf8');
const CATALOG = [
{ id: 'claude', kind: 'agent', label: 'Claude Code', enabled: true },
{ id: 'shell', kind: 'shell', label: 'Shell', enabled: true },
{ id: 'codex', kind: 'agent', label: 'Codex', enabled: true },
{ id: 'gemini', kind: 'agent', label: 'Gemini CLI', enabled: true },
{ id: 'pi', kind: 'agent', label: 'Pi', enabled: false },
];
/** What this host has installed: no gemini. */
const HOST = new Set(['claude', 'codex']);
/** As GET /api/cases sends them: remote and Docker cases carry a DISPLAY path, the raw values nested. */
const CASES = [
{ name: 'toolbar-case', path: '/tmp/toolbar-case', location: 'local' },
// Same container name and same remote path on ANOTHER host, listed first: only the host tells them apart.
{
name: 'box-h2',
path: 'box:/srv/box',
location: 'docker',
docker: { hostId: 'h2', container: 'box', path: '/srv/box', containerWorkdir: '/srv/box' },
},
{
name: 'rem2',
path: 'dev@host2:/home/dev/work',
location: 'remote',
remote: { hostId: 'r2', host: 'host2', username: 'dev', path: '/home/dev/work' },
},
// Inside proj and listed before it: the deepest enclosing case wins, whatever the order.
{ name: 'nested', path: '/tmp/proj/nested', location: 'local' },
{ name: 'proj', path: '/tmp/proj', location: 'local' },
{
name: 'box',
path: 'box:/srv/box',
location: 'docker',
docker: {
hostId: 'h1',
container: 'box',
path: '/srv/box',
containerWorkdir: '/srv/box',
owned: false,
availableModes: ['gemini', 'shell'],
},
},
{
name: 'own',
path: 'own:/srv/own',
location: 'docker',
docker: { hostId: 'h1', container: 'own', path: '/srv/own', containerWorkdir: '/srv/own' },
},
// A local case whose folder is the Docker case's workspace: only a LOCAL session belongs to it.
{ name: 'clash', path: '/srv/box', location: 'linked-local' },
{
name: 'rem',
path: 'dev@host1:/home/dev/work',
location: 'remote',
remote: { hostId: 'r1', host: 'host1', username: 'dev', path: '/home/dev/work' },
},
];
const DOCKER_BOX = { hostId: 'h1', containerName: 'box', hostWorkspacePath: '/srv/box', containerWorkdir: '/srv/box' };
const DOCKER_OWN = { hostId: 'h1', containerName: 'own', hostWorkspacePath: '/srv/own', containerWorkdir: '/srv/own' };
const REMOTE_R1 = { hostId: 'r1', host: 'host1', username: 'dev', remotePath: '/home/dev/work/api' };
const SESSIONS: Array<[string, string, Record<string, unknown>?]> = [
['a', '/tmp/proj/sub'],
['b', '/tmp/proj'],
['c', '/srv/box', { docker: DOCKER_BOX }],
['d', '/srv/own', { docker: DOCKER_OWN }],
['e', '/home/u/scratch'],
['f', '/tmp/proj/.claude/worktrees/feat'],
['g', '/srv/box'],
['r', '/home/dev/work/api', { remote: REMOTE_R1 }],
['n', '/tmp/proj/nested/src'],
];
const LAYOUT = {
version: 4,
updatedAt: '2026-10-01T00:00:00.000Z',
groups: [{ id: 'gx', name: 'Core', refs: [{ kind: 'session', id: 'b' }] }],
ungrouped: ['a', 'c', 'd', 'e', 'f', 'g', 'r', 'n'].map((id) => ({ kind: 'session', id })),
};
let CodemanApp: { prototype: Record<string, any> };
/** The test's app, so afterEach can close its menus: their document listeners would outlive the DOM. */
let current: Record<string, any> | null = null;
let win: any;
let document: Document;
beforeAll(async () => {
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
url: 'https://localhost/',
runScripts: 'outside-only',
});
if (dom.window.document.readyState !== 'complete') {
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
}
win = dom.window;
document = win.document;
win.setInterval = () => 0;
win.requestAnimationFrame = () => 0;
win.CSS = { escape: (value: string) => value };
win.eval(
'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' +
'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
[
'constants.js',
'tab-layout-browser.js',
'app.js',
'tab-rail-resize.js',
'api-client.js',
'webview-tabs.js',
'mobile-overview.js',
'session-ui.js',
]
.map(read)
.join('\n;\n') +
'\n;window.__TabNewCodemanApp = CodemanApp;'
);
CodemanApp = win.__TabNewCodemanApp;
});
function makeApp({ orientation = 'horizontal' } = {}) {
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
document.documentElement.setAttribute('data-tab-orientation', orientation);
document.documentElement.dataset.tabRailSort = 'manual';
document.body.innerHTML =
'<div id="sessionTabs" role="tablist" aria-label="Session tabs"></div>' +
'<select id="quickStartCase"><option value="toolbar-case" selected>toolbar-case</option></select>' +
'<input id="tabCount" value="3"><button id="runBtn"></button>';
app.$ = (id: string) => document.getElementById(id);
app.sessions = new Map(
SESSIONS.map(([id, workingDir, extra]) => [id, { id, name: id, status: 'idle', workingDir, ...extra }])
);
app.sessionOrder = SESSIONS.map(([id]) => id);
app.webviews = new Map();
app.webviewOrder = [];
app.activeSessionId = 'a';
app.activeWebviewId = null;
app.tabLayout = null;
app.collapsedTabGroupIds = new Set();
app._hiddenTabGroupByRef = new Map();
app._lastTabGroupStructureKey = null;
app._tabCollapseStorageFailed = false;
app._inlineRenameActive = false;
app.tabAlerts = new Map();
app.terminalLoadStates = new Map();
app.minimizedSubagents = new Map();
app.hasTabDetachOverride = () => false;
app.renderSubagentTabBadge = () => '';
app.cancelHideSubagentDropdown = () => {};
app.updateTabOverflowMode = () => {};
app.updateConnectionLines = () => {};
app._applyTabEntrances = () => {};
app._scrollActiveTabIntoView = () => {};
app.applySidebarFilter = () => {};
app.isSessionSidebarActive = () => false;
app._startSidebarRichClock = () => {};
app._stopSidebarRichClock = () => {};
app.loadAppSettingsFromStorage = () => ({});
app.openSessionOptions = vi.fn();
app.requestCloseSession = vi.fn();
app.selectSession = vi.fn(async () => {});
app.showToast = vi.fn();
app.closeAllPanels = vi.fn();
// What the real run() reads beyond the DOM (the same stubs as tab-group-launch.test.ts).
app._runMinLockMs = 0;
app._runMode = 'codex';
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {}, cols: 80, rows: 24 };
app.cases = CASES;
app.isCliAvailable = (id: string) => HOST.has(id);
app.getCaseSettings = () => ({});
app.buildEnvOverrides = () => ({});
app.getEffortSetting = () => undefined;
app.isRalphTrackerEnabledByDefault = () => false;
app.getTerminalDimensions = () => null;
app.loadQuickStartCases = () => {};
app._fullRenderSessionTabs();
app._applyTabLayout(LAYOUT);
current = app;
return app;
}
const tab = (id: string) => document.querySelector<HTMLElement>(`.session-tab[data-id="${id}"]`)!;
const plus = (id: string) => tab(id).querySelector<HTMLElement>('.tab-new')!;
const picker = () => document.querySelector<HTMLElement>('[role="menu"][aria-label="New session here"]');
/** Each entry as [logo slot classes, visible text, button classes]. */
const entries = () =>
[...(picker()?.querySelectorAll('button') || [])].map((button) => [
button.querySelector('.run-mode-dot')?.className,
button.textContent,
button.className,
]);
const openFrom = (app: Record<string, any>, id: string) =>
app.openTabNewSessionMenu({ preventDefault() {}, stopPropagation() {}, currentTarget: plus(id) }, id);
const pick = (label: string) =>
[...picker()!.querySelectorAll<HTMLElement>('button')].find((button) => button.textContent === label)!.click();
const rowMenuLabels = () =>
[...document.querySelectorAll('.tab-rail-action-menu:not(.tab-layout-group-action-menu) button')].map(
(button) => button.textContent
);
const flush = async () => {
for (let i = 0; i < 6; i++) await new Promise((resolve) => setTimeout(resolve, 0));
};
beforeEach(() => {
win.localStorage.clear();
document.body.innerHTML = '';
document.documentElement.className = '';
win.__codemanCliCatalog = CATALOG;
win.__codemanUser = { username: 'admin', role: 'admin', multiUser: false };
});
afterEach(() => {
current?.closeTabGroupMenu();
current?.closeTabRailActionMenu();
current = null;
});
describe('the tab "+" picker', () => {
it('lists the CLIs the case can start as logo + name, agents in catalog order, the shell last', () => {
const app = makeApp();
// The markup wires the "+" to this picker for its own tab.
expect(plus('a').getAttribute('onclick')).toBe('event.stopPropagation(); app.openTabNewSessionMenu(event, "a")');
expect(openFrom(app, 'a')).toBe(true);
// gemini is not on this host and pi is disabled in the catalog.
expect(entries()).toEqual([
['run-mode-dot claude', 'Claude Code', 'run-mode-option'],
['run-mode-dot codex', 'Codex', 'run-mode-option selected'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
for (const dot of picker()!.querySelectorAll('.run-mode-dot')) expect(dot.getAttribute('aria-hidden')).toBe('true');
// The Run button's mode is the one preselected for the keyboard.
expect(document.activeElement?.textContent).toBe('Codex');
});
it("a Docker case offers the container's CLIs through the Run menu's rule, never the host's", () => {
const app = makeApp();
// Adopted, not probed yet: the list stored at adoption (gemini, which the host lacks; no claude, which it has).
openFrom(app, 'c');
expect(entries()).toEqual([
['run-mode-dot gemini', 'Gemini CLI', 'run-mode-option'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
app.closeTabGroupMenu();
// A live probe wins over the stored list.
app._dockerCaseModes = { box: ['claude', 'shell'] };
openFrom(app, 'c');
expect(entries()).toEqual([
['run-mode-dot claude', 'Claude Code', 'run-mode-option'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
app.closeTabGroupMenu();
// An unreadable adopted container offers no agent at all.
app._dockerCaseProbeError = { box: 'Could not read container "box".' };
openFrom(app, 'c');
expect(entries()).toEqual([['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option']]);
app.closeTabGroupMenu();
// An owned container with nothing probed is not gated: its image ships every CLI.
openFrom(app, 'd');
expect(entries()).toEqual([
['run-mode-dot claude', 'Claude Code', 'run-mode-option'],
['run-mode-dot codex', 'Codex', 'run-mode-option selected'],
['run-mode-dot gemini', 'Gemini CLI', 'run-mode-option'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
});
it("opening on a Docker tab whose container is not probed yet probes it, so the next open lists the container's CLIs", async () => {
const app = makeApp();
const probe = vi.spyOn(app, '_probeDockerCaseModes');
const previousFetch = win.fetch;
// The network boundary: what POST /api/docker-cases/adopt-preflight answers for this container.
win.fetch = vi.fn(async () => ({
ok: true,
json: async () => ({ success: true, data: { ok: true, availableModes: ['codex', 'shell'] } }),
}));
try {
probe.mockClear();
win.fetch.mockClear();
openFrom(app, 'c');
// This open reads what is already known (the list stored at adoption) and starts the probe.
expect(entries()).toEqual([
['run-mode-dot gemini', 'Gemini CLI', 'run-mode-option'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
expect(probe).toHaveBeenCalledTimes(1);
expect(probe.mock.calls[0][0]).toBe(CASES.find((c) => c.name === 'box'));
expect(probe.mock.calls[0][1]).toBeNull();
expect(win.fetch).toHaveBeenCalledTimes(1);
const [url, init] = win.fetch.mock.calls[0];
expect(url).toBe('/api/docker-cases/adopt-preflight');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toStrictEqual({ hostId: 'h1', container: 'box' });
await flush();
app.closeTabGroupMenu();
// The next open lists what the container answered, and probes no more.
probe.mockClear();
win.fetch.mockClear();
openFrom(app, 'c');
expect(entries()).toEqual([
['run-mode-dot codex', 'Codex', 'run-mode-option selected'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
expect(probe).not.toHaveBeenCalled();
expect(win.fetch).not.toHaveBeenCalled();
app.closeTabGroupMenu();
// An owned container with nothing probed is probed as well.
probe.mockClear();
openFrom(app, 'd');
expect(probe).toHaveBeenCalledTimes(1);
expect(probe.mock.calls[0][0]).toBe(CASES.find((c) => c.name === 'own'));
expect(probe.mock.calls[0][1]).toBeNull();
await flush();
app.closeTabGroupMenu();
// Local, remote and worktree tabs have no container to ask.
for (const id of ['a', 'g', 'r', 'f']) {
probe.mockClear();
win.fetch.mockClear();
openFrom(app, id);
expect(probe).not.toHaveBeenCalled();
expect(win.fetch).not.toHaveBeenCalled();
app.closeTabGroupMenu();
}
} finally {
win.fetch = previousFetch;
}
});
it('finds the case by what the session runs on, never a same-path case elsewhere', async () => {
const app = makeApp();
const runs: unknown[] = [];
app.run = vi.fn(async (options: unknown) => {
runs.push(structuredClone(options));
});
// A Docker session belongs to its container's case, not to the local case at the same path.
openFrom(app, 'c');
pick('Terminal / Shell');
// A local session at that path belongs to the local case, never the Docker one.
openFrom(app, 'g');
expect(entries().map(([, text]) => text)).toEqual(['Claude Code', 'Codex', 'Terminal / Shell']);
pick('Terminal / Shell');
// A remote session belongs to the case on its own host, by path prefix.
openFrom(app, 'r');
pick('Terminal / Shell');
// A local session in a case inside another case belongs to the inner one.
openFrom(app, 'n');
pick('Terminal / Shell');
await flush();
expect(runs).toStrictEqual([
{ count: 1, caseName: 'box', mode: 'shell' },
{ count: 1, caseName: 'clash', mode: 'shell' },
{ count: 1, caseName: 'rem', mode: 'shell' },
{ count: 1, caseName: 'nested', mode: 'shell' },
]);
});
it('a tab whose folder is no case says so and opens nothing', () => {
const app = makeApp();
expect(openFrom(app, 'e')).toBe(false);
expect(picker()).toBeNull();
expect(app.showToast).toHaveBeenCalledWith(
"This tab's folder is not a case, so there is nothing to start beside it.",
'info'
);
});
});
describe('the "+" from the keyboard', () => {
/**
* Wire the "+"'s inline keydown handler the way a browser wires an on* attribute
* (the attribute's text as the body of a function of `event`, `this` the
* element, `app` the page's global), since this JSDOM does not run inline handlers.
*/
function wireInlineKeydown(app: Record<string, any>, el: HTMLElement) {
win.app = app;
const body = el.getAttribute('onkeydown');
expect(body).not.toBeNull();
const handler = new win.Function('event', body);
el.addEventListener('keydown', function (this: HTMLElement, event: Event) {
handler.call(this, event);
});
}
const press = (el: HTMLElement, key: string) => {
const event = new win.KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
el.dispatchEvent(event);
return event;
};
it('Enter and Space on the header strip\'s "+" open its picker, and the key goes no further', () => {
const app = makeApp({ orientation: 'horizontal' });
const strip = document.getElementById('sessionTabs')!;
// The header strip: a flat tablist, no row menu to fall back on.
expect(strip.getAttribute('role')).toBe('tablist');
const open = vi.spyOn(app, 'openTabNewSessionMenu');
const reachedStrip = vi.fn();
strip.addEventListener('keydown', reachedStrip);
wireInlineKeydown(app, plus('a'));
for (const key of ['Enter', ' ']) {
open.mockClear();
reachedStrip.mockClear();
const event = press(plus('a'), key);
expect(open).toHaveBeenCalledTimes(1);
expect(open.mock.calls[0][0]).toBe(event);
expect(open.mock.calls[0][1]).toBe('a');
expect(event.defaultPrevented).toBe(true);
expect(reachedStrip).not.toHaveBeenCalled();
expect(entries()).toEqual([
['run-mode-dot claude', 'Claude Code', 'run-mode-option'],
['run-mode-dot codex', 'Codex', 'run-mode-option selected'],
['run-mode-dot shell', 'Terminal / Shell', 'run-mode-option'],
]);
// Anchored on the "+" itself; Escape gives focus back to its tab row (the shared menu's design).
expect(app._tabGroupMenuTrigger).toBe(plus('a'));
app.closeTabGroupMenu();
}
strip.removeEventListener('keydown', reachedStrip);
});
it('on a tab whose folder is no case the key still stops at the "+", so Space does not scroll the page', () => {
const app = makeApp({ orientation: 'horizontal' });
const strip = document.getElementById('sessionTabs')!;
const reachedStrip = vi.fn();
strip.addEventListener('keydown', reachedStrip);
wireInlineKeydown(app, plus('e'));
app.showToast.mockClear();
const event = press(plus('e'), ' ');
expect(event.defaultPrevented).toBe(true);
expect(reachedStrip).not.toHaveBeenCalled();
expect(picker()).toBeNull();
expect(app.showToast).toHaveBeenCalledWith(
"This tab's folder is not a case, so there is nothing to start beside it.",
'info'
);
strip.removeEventListener('keydown', reachedStrip);
});
it('every other key leaves the "+" alone and reaches the strip as before', () => {
const app = makeApp({ orientation: 'horizontal' });
const strip = document.getElementById('sessionTabs')!;
const open = vi.spyOn(app, 'openTabNewSessionMenu');
const reachedStrip = vi.fn();
strip.addEventListener('keydown', reachedStrip);
wireInlineKeydown(app, plus('a'));
for (const key of ['a', 'ArrowRight', 'ArrowDown', 'Escape', 'Tab', 'F2']) {
open.mockClear();
reachedStrip.mockClear();
const event = press(plus('a'), key);
expect(open).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
expect(reachedStrip).toHaveBeenCalledTimes(1);
expect(picker()).toBeNull();
}
strip.removeEventListener('keydown', reachedStrip);
});
it('a held Enter or Space that opened the picker cannot also pick its focused entry', async () => {
const app = makeApp({ orientation: 'horizontal' });
const runs: unknown[] = [];
app.run = vi.fn(async (options: unknown) => {
runs.push(structuredClone(options));
});
wireInlineKeydown(app, plus('a'));
for (const key of ['Enter', ' ']) {
press(plus('a'), key);
const focused = document.activeElement as HTMLElement;
expect(focused.textContent).toBe('Codex');
// The key's auto-repeat lands on the entry the picker just focused: its
// native activation is cancelled, so nothing launches and the picker stays.
const repeat = new win.KeyboardEvent('keydown', { key, repeat: true, bubbles: true, cancelable: true });
focused.dispatchEvent(repeat);
expect(repeat.defaultPrevented).toBe(true);
expect(picker()).not.toBeNull();
// A fresh press on an entry keeps its native activation.
const fresh = new win.KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
focused.dispatchEvent(fresh);
expect(fresh.defaultPrevented).toBe(false);
app.closeTabGroupMenu();
}
// Other repeated keys keep their own handling (ArrowDown still moves).
press(plus('a'), 'Enter');
const arrow = new win.KeyboardEvent('keydown', { key: 'ArrowDown', repeat: true, bubbles: true, cancelable: true });
document.activeElement!.dispatchEvent(arrow);
expect(arrow.defaultPrevented).toBe(true);
expect(document.activeElement?.textContent).toBe('Terminal / Shell');
app.closeTabGroupMenu();
await flush();
expect(runs).toStrictEqual([]);
});
});
describe('a pick from the "+"', () => {
function recordRuns(app: Record<string, any>) {
const runs: Array<{ options: unknown; runMode: string }> = [];
app.run = vi.fn(async (options: unknown) => {
// Cloned into this realm, so toStrictEqual compares keys and values, not JSDOM's prototypes.
runs.push({ options: structuredClone(options), runMode: app._runMode });
});
return runs;
}
it("starts ONE session in the tab's case and named group, then leaves the Run mode and case alone", async () => {
const app = makeApp();
const runs = recordRuns(app);
app.collapsedTabGroupIds.add('gx');
openFrom(app, 'b');
pick('Claude Code');
await flush();
// Its group is opened, so the new tab is visible when it arrives.
expect(app.collapsedTabGroupIds.has('gx')).toBe(false);
// The mode rides the launch; the Run button's own mode is never swapped.
expect(runs).toStrictEqual([
{ options: { count: 1, caseName: 'proj', tabGroupId: 'gx', mode: 'claude' }, runMode: 'codex' },
]);
expect(picker()).toBeNull();
expect(app._runMode).toBe('codex');
expect((document.getElementById('quickStartCase') as HTMLSelectElement).value).toBe('toolbar-case');
});
it('from an ungrouped tab it sends no group at all, so the case default group can place it', async () => {
const app = makeApp();
const runs = recordRuns(app);
openFrom(app, 'a');
pick('Terminal / Shell');
await flush();
expect(runs).toStrictEqual([{ options: { count: 1, caseName: 'proj', mode: 'shell' }, runMode: 'codex' }]);
});
it('from a tab in a managed worktree it starts in that worktree, not the case folder', async () => {
const app = makeApp();
const runs = recordRuns(app);
openFrom(app, 'f');
pick('Codex');
await flush();
expect(runs).toStrictEqual([
{
options: {
count: 1,
worktree: { caseName: 'proj', name: 'feat', path: '/tmp/proj/.claude/worktrees/feat' },
mode: 'codex',
},
runMode: 'codex',
},
]);
});
it('refuses while another launch is in flight, and says so', async () => {
const app = makeApp();
const runs = recordRuns(app);
openFrom(app, 'a');
app._runInFlight = true;
app.showToast.mockClear();
pick('Codex');
await flush();
expect(runs).toEqual([]);
expect(app.showToast).toHaveBeenCalledWith('A launch is already in progress', 'info');
expect(app._runMode).toBe('codex');
});
it("a launch the server refuses reports the server's own error", async () => {
const app = makeApp();
app._runMode = 'claude';
const posted: Array<{ url: string; body: unknown }> = [];
win.fetch = vi.fn(async (url: string, init?: { body?: string }) => {
const body = init?.body ? JSON.parse(init.body) : undefined;
posted.push({ url, body });
const json = (value: unknown) => ({ ok: true, status: 200, json: async () => value });
if (url === '/api/codex/status') return json({ success: true, data: { available: true, runnable: true } });
if (url === '/api/quick-start') {
return json({ success: false, error: 'Case "proj" has no free session slot', errorCode: 'CONFLICT' });
}
return json({ success: true, data: {} });
});
openFrom(app, 'a');
app.showToast.mockClear();
pick('Codex');
await flush();
expect(posted.find((req) => req.url === '/api/quick-start')?.body).toMatchObject({
caseName: 'proj',
mode: 'codex',
});
expect(app.showToast).toHaveBeenLastCalledWith('Case "proj" has no free session slot', 'error');
expect(app._runMode).toBe('claude');
});
it('a Run mode chosen while the launch is pending is kept, on screen and on disk', async () => {
const app = makeApp();
app._applyRunMode = () => {};
app._apiPut = vi.fn(async () => ({ success: true }));
let finish: () => void = () => {};
app.runShell = vi.fn(() => new Promise<void>((resolve) => (finish = resolve)));
openFrom(app, 'a');
pick('Terminal / Shell');
await flush();
expect(app.runShell).toHaveBeenCalledTimes(1);
app.setRunMode('claude');
finish();
await flush();
expect(app._runMode).toBe('claude');
expect(win.localStorage.getItem('codeman_runMode')).toBe('claude');
expect(app._apiPut).toHaveBeenCalledWith('/api/settings', { runMode: 'claude' });
});
/**
* Readies a Claude launch with the shipping case-list reload and the server's
* lastUsedCase at `lastUsedCase`; the returned wait resolves once that reload ran.
*/
function useShippingCaseReload(app: Record<string, any>, lastUsedCase: string) {
app._runMode = 'claude';
app.getAdvisorSetting = () => undefined;
app._onSessionCreated = () => {};
delete app.loadQuickStartCases; // the shipping reload, not makeApp's no-op
// The UI-only steps of the case list reload.
for (const name of ['updateDirDisplayForCase', 'updateMobileCaseLabel', 'updateCasePickerInput'])
app[name] = () => {};
for (const name of ['renderCasePickerList', 'closeCasePicker', 'setupQuickStartCasePicker']) app[name] = () => {};
win.fetch = vi.fn(async (url: string) => {
const json = (value: unknown) => ({ ok: true, status: 200, json: async () => value });
// quick-start saved the launched case as lastUsedCase (session-routes.ts).
if (url === '/api/settings') return json({ success: true, data: { lastUsedCase } });
if (url === '/api/cases') return json({ success: true, data: CASES });
if (url.startsWith('/api/cases/')) {
const record = CASES.find((c) => `/api/cases/${c.name}` === url);
return json(record ? { success: true, data: record } : { success: false, errorCode: 'NOT_FOUND' });
}
if (url === '/api/quick-start')
return json({ success: true, data: { sessionId: 'new1', session: { id: 'new1' } } });
if (url === '/api/sessions') return json({ success: true, data: { session: { id: 'new1', name: 'w1' } } });
return json({ success: true, data: {} });
});
return async () => {
await vi.waitFor(() => expect(app.selectSession).toHaveBeenCalledWith('new1'));
// The case list is reloaded after the launch (not awaited by it).
await vi.waitFor(() => expect(win.fetch.mock.calls.map((call: unknown[]) => call[0])).toContain('/api/cases'));
await flush();
};
}
it.each([
['a remote Claude launch (quick-start)', 'rem', 'r'],
['a local Claude launch', 'proj', 'a'],
])("%s leaves the toolbar on its own case, though the server's lastUsedCase moved", async (_label, tabCase, id) => {
const app = makeApp();
const reloaded = useShippingCaseReload(app, tabCase);
const select = document.getElementById('quickStartCase') as HTMLSelectElement;
openFrom(app, id);
pick('Claude Code');
await reloaded();
expect(select.value).toBe('toolbar-case');
});
// An earlier "+" launch through quick-start left lastUsedCase on the tab's case
// (proj); a later Claude launch that names no case must not follow it there.
it.each([
[
'a "+" Claude launch from a managed worktree tab',
'horizontal',
(app: Record<string, any>) => {
openFrom(app, 'f');
pick('Claude Code');
},
],
['the toolbar Run with Claude', 'horizontal', (app: Record<string, any>) => app.run()],
[
'a group\'s "New session" with Claude',
'vertical',
(app: Record<string, any>) => app.createSessionInTabGroup('gx'),
],
])('%s keeps the toolbar on its own case after a "+" moved lastUsedCase', async (_label, orientation, launch) => {
const app = makeApp({ orientation });
const reloaded = useShippingCaseReload(app, 'proj');
const select = document.getElementById('quickStartCase') as HTMLSelectElement;
(document.getElementById('tabCount') as HTMLInputElement).value = '1';
void launch(app);
await reloaded();
expect(select.value).toBe('toolbar-case');
});
});
describe('"New session here…" in the row menu', () => {
const rowMenu = (app: Record<string, any>, trigger: HTMLElement, id: string) =>
app.openTabRailActionMenu({ preventDefault() {}, stopPropagation() {}, currentTarget: trigger }, id);
it('is offered on a session row only while the "+" is switched on, and opens the same picker', () => {
const app = makeApp({ orientation: 'vertical' });
rowMenu(app, tab('a'), 'a');
expect(rowMenuLabels()).toEqual([
'Session options',
'Add to Focus',
'Move down',
'Move to "Core"',
'Move to new group',
'Close session',
]);
app.closeTabRailActionMenu();
document.documentElement.classList.add('tabs-show-new');
rowMenu(app, tab('a'), 'a');
expect(rowMenuLabels()).toEqual([
'Session options',
'New session here…',
'Add to Focus',
'Move down',
'Move to "Core"',
'Move to new group',
'Close session',
]);
[...document.querySelectorAll<HTMLElement>('.tab-rail-action-menu button')]
.find((button) => button.textContent === 'New session here…')!
.click();
expect(rowMenuLabels()).toEqual([]);
expect(entries().map(([, text]) => text)).toEqual(['Claude Code', 'Codex', 'Terminal / Shell']);
// Escape gives the keyboard back to the tab row.
document.activeElement!.dispatchEvent(
new win.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })
);
expect(picker()).toBeNull();
expect(document.activeElement).toBe(tab('a'));
});
it("is never offered on a tile's menu, which shares the function", () => {
const app = makeApp({ orientation: 'vertical' });
document.documentElement.classList.add('tabs-show-new');
const tileButton = document.createElement('button');
tileButton.className = 'tile-menu';
document.body.appendChild(tileButton);
rowMenu(app, tileButton, 'a');
expect(rowMenuLabels()).toEqual([
'Session options',
'Add to Focus',
'Move down',
'Move to "Core"',
'Move to new group',
'Close session',
]);
});
});
describe('picker lifetime', () => {
it('a full re-render closes it and drops its document listeners', () => {
const app = makeApp();
openFrom(app, 'a');
expect(picker()).not.toBeNull();
app.sessions.delete('a');
app._fullRenderSessionTabs();
expect(picker()).toBeNull();
expect(app._tabGroupMenuOutside).toBeNull();
expect(app._tabGroupMenuKeydown).toBeNull();
expect(app._tabGroupMenuResize).toBeNull();
});
it('pressing the same "+" again closes it, like the row menu', () => {
const app = makeApp();
openFrom(app, 'a');
expect(openFrom(app, 'a')).toBe(false);
expect(picker()).toBeNull();
});
});
describe('showTabNewButton stays per-device and OFF by default', () => {
const settingsUi = read('settings-ui.js');
const index = read('index.html');
it('is a display key, stripped from the settings PUT, which would refuse it', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
expect(settingsUi.slice(start, settingsUi.indexOf('])', start))).toContain("'showTabNewButton'");
expect(settingsUi).toContain('showTabNewButton: _tnb,');
expect(SettingsUpdateSchema.safeParse({ showTabNewButton: true }).success).toBe(false);
});
it('loads OFF unless switched on, saves from its switch, and drives the class the CSS reads', () => {
expect(settingsUi).toContain(
"document.getElementById('appSettingsShowTabNewButton').checked = settings.showTabNewButton === true;"
);
expect(settingsUi).toContain("showTabNewButton: document.getElementById('appSettingsShowTabNewButton').checked,");
expect(settingsUi).toContain(
"document.documentElement.classList.toggle('tabs-show-new', settings.showTabNewButton === true);"
);
expect(index).toContain('<input type="checkbox" id="appSettingsShowTabNewButton">');
});
it('translates every string it adds', () => {
const i18n = read('i18n.js');
for (const text of [
"'New session here'",
"'New session here…'",
'"New session in this tab\'s case"',
'"This tab\'s folder is not a case, so there is nothing to start beside it."',
"'New Session Button on Tabs'",
"'A + on the tab that starts a session in the same case and group, in any installed CLI.'",
]) {
expect(i18n).toContain(`${text}:`);
}
});
});
+4 -4
View File
@@ -6,7 +6,7 @@
* - a worktree launch goes through the EXISTING create paths with the worktree's folder:
* POST /api/sessions with `workingDir` for claude and shell, quick-start with `worktree` for
* every other CLI; never a case lookup or scaffold, and tabs named after the worktree;
* - `_launchInWorktree()` swaps the run mode for the one launch and puts it back.
* - `_launchOnce()` starts the one launch in the chosen mode without touching the Run button's mode.
*
* Port: N/A.
*/
@@ -138,15 +138,15 @@ describe('launching in a worktree', () => {
});
});
it('_launchInWorktree runs ONE session of the chosen mode and restores the Run button mode', async () => {
it("_launchOnce runs ONE session of the chosen mode in the worktree and leaves the Run button's mode", async () => {
const { app } = load(async () => json({}));
app._runMode = 'claude';
const seen: Array<{ mode: string; options: unknown }> = [];
app.run = vi.fn(async (options: unknown) => {
seen.push({ mode: app._runMode, options });
});
await app._launchInWorktree(WT, 'codex');
expect(seen).toEqual([{ mode: 'codex', options: { count: 1, worktree: WT } }]);
await app._launchOnce('codex', { worktree: WT });
expect(seen).toEqual([{ mode: 'claude', options: { count: 1, worktree: WT, mode: 'codex' } }]);
expect(app._runMode).toBe('claude');
});