Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): terminal tab rename + reorder, with terminal e2e suite (PRD-7243, PRD-7305) (#2496)
serafin-garcia4362b36d04e5
diff --git a/.changeset/terminal-tab-manual-rename.md b/.changeset/terminal-tab-manual-rename.mdnew file mode 100644index 000000000..287a26e48--- /dev/null+++ b/.changeset/terminal-tab-manual-rename.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": minor+---++Add manual rename to terminal tabs. Double-click a terminal tab (or press F2+while it's focused) to give it a name of your own, edited inline. The custom+name pins over whatever title the running program sets via its terminal title+escape sequence — useful for agent CLIs that constantly rewrite their title — so+the tab keeps the name you chose. Press Enter or click away to commit, Escape to+cancel; committing an empty name clears the custom label and restores the+program's title (or the positional "Terminal N" default).diff --git a/.changeset/terminal-tab-reorder.md b/.changeset/terminal-tab-reorder.mdnew file mode 100644index 000000000..53238eb98--- /dev/null+++ b/.changeset/terminal-tab-reorder.md@@ -0,0 +1,14 @@+---+"@inkeep/open-knowledge": minor+---++Reorder terminal tabs. Drag a terminal tab to a new position with the pointer, or+move the active tab with ⌘⇧← / ⌘⇧→ (keyboard reorders are announced to screen+readers). Untitled tabs now carry a sticky number that stays with the session, so+reordering them is visibly meaningful instead of silently renumbering, and ⌘1–9+still jumps to the tab at that visual position. The drag reuses the editor's tab+chrome, and in the standalone terminal window a drag across the tab strip reorders+tabs instead of moving the window. Your custom names and tab order are retained by+the main process, so a renderer reload (View → Reload) restores both names and+order; a full app quit still starts fresh, since the shells themselves don't+survive a restart.diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsxindex c515074ac..7c4430c88 100644--- a/packages/app/src/components/EditorTabs.tsx+++ b/packages/app/src/components/EditorTabs.tsx@@ -851,7 +851,7 @@ export function EditorTabs() {const forceTabCloseVisible = showTabShortcutHints;function handleDragStart() {- setTabReorderBounds(measureTabReorderBounds(tabListRef.current));+ setTabReorderBounds(measureTabReorderBounds(tabListRef.current, '[data-editor-tab-sortable]'));}function clearTabReorderBounds() {diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsxindex 164e2cb51..942774bae 100644--- a/packages/app/src/components/TerminalDock.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.dom.test.tsx@@ -489,6 +489,193 @@ describe('TerminalDock multi-session', () => {expect(screen.getByRole('tab', { name: 'Terminal 1' })).toBeDefined();});+ test('a manual rename pins the tab label over later OSC title updates', async () => {+ const user = userEvent.setup();+ renderDock(true);++ // Rename the sole tab before any program title arrives.+ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 1' }));+ const input = screen.getByRole('textbox', { name: 'Rename Terminal 1' });+ await user.clear(input);+ await user.type(input, 'my shell');+ await user.keyboard('{Enter}');+ expect(screen.getByRole('tab', { name: 'my shell' })).toBeDefined();++ // The program now sets an OSC title (the waitFor's successful emit is that+ // update). `title` changes underneath, but the custom label pins the visible+ // name — the tab must NOT relabel to the OSC title.+ await waitFor(() => expect(emitTitle('pty-1', 'claude — repo')).toBe(true));+ expect(screen.getByRole('tab', { name: 'my shell' })).toBeDefined();+ expect(screen.queryByRole('tab', { name: 'claude — repo' })).toBeNull();+ });++ test('clearing a custom label reverts the tab to the live OSC title', async () => {+ const user = userEvent.setup();+ renderDock(true);++ // A program title is live (emitted once via the readiness probe).+ await waitFor(() => expect(emitTitle('pty-1', 'claude — repo')).toBe(true));+ expect(screen.getByRole('tab', { name: 'claude — repo' })).toBeDefined();++ // Pin a custom label over it.+ await user.dblClick(screen.getByRole('tab', { name: 'claude — repo' }));+ await user.clear(screen.getByRole('textbox', { name: 'Rename claude — repo' }));+ await user.type(screen.getByRole('textbox', { name: 'Rename claude — repo' }), 'pinned');+ await user.keyboard('{Enter}');+ expect(screen.getByRole('tab', { name: 'pinned' })).toBeDefined();++ // An empty rename commit clears the custom label; the OSC title (still+ // tracked underneath) becomes the visible name again.+ await user.dblClick(screen.getByRole('tab', { name: 'pinned' }));+ await user.clear(screen.getByRole('textbox', { name: 'Rename pinned' }));+ await user.keyboard('{Enter}');+ expect(screen.getByRole('tab', { name: 'claude — repo' })).toBeDefined();+ });++ function tabLabels(): (string | null)[] {+ return within(screen.getByRole('tablist'))+ .getAllByRole('tab')+ .map((tab) => tab.textContent);+ }+ function dispatchChord(+ key: string,+ mods: { metaKey?: boolean; shiftKey?: boolean },+ ): KeyboardEvent {+ const event = new KeyboardEvent('keydown', {+ key,+ metaKey: mods.metaKey ?? false,+ shiftKey: mods.shiftKey ?? false,+ cancelable: true,+ bubbles: true,+ });+ act(() => {+ window.dispatchEvent(event);+ });+ return event;+ }++ test('⌘⇧← moves the active tab one slot left and announces the move', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ await addTerminalTab(user);+ // Three tabs; Terminal 3 is active. Put the caret in its shell.+ const panels = sessionPanels();+ act(() => panels[2]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());++ const event = dispatchChord('ArrowLeft', { metaKey: true, shiftKey: true });++ expect(event.defaultPrevented).toBe(true);+ // Terminal 3 (its sticky number rides with the session) moves to the middle.+ expect(tabLabels()).toEqual(['Terminal 1', 'Terminal 3', 'Terminal 2']);+ await waitFor(() =>+ expect(screen.getByTestId('terminal-reorder-announcer').textContent).toBe(+ 'Moved Terminal 3 to position 2 of 3',+ ),+ );+ });++ test('⌘⇧→ at the last slot is a no-op left for the shell', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ // Two tabs; Terminal 2 active (rightmost). Focus its shell.+ const panels = sessionPanels();+ act(() => panels[1]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());++ const event = dispatchChord('ArrowRight', { metaKey: true, shiftKey: true });++ // Not consumed (the shell may use it) and order unchanged.+ expect(event.defaultPrevented).toBe(false);+ expect(tabLabels()).toEqual(['Terminal 1', 'Terminal 2']);+ });++ test('sticky numbering: closing a tab does not renumber the survivors', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ await addTerminalTab(user);+ expect(tabLabels()).toEqual(['Terminal 1', 'Terminal 2', 'Terminal 3']);++ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));+ // Survivors keep their numbers (not renumbered to 1/2).+ expect(tabLabels()).toEqual(['Terminal 2', 'Terminal 3']);++ // A fresh tab takes the next ordinal, not a reused low number.+ await addTerminalTab(user);+ expect(tabLabels()).toEqual(['Terminal 2', 'Terminal 3', 'Terminal 4']);+ });++ test('⌘N targets the visual position after a keyboard reorder', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ // Two tabs; Terminal 2 active. Move it left → [Terminal 2, Terminal 1].+ const panels = sessionPanels();+ act(() => panels[1]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());+ dispatchChord('ArrowLeft', { metaKey: true, shiftKey: true });+ expect(tabLabels()).toEqual(['Terminal 2', 'Terminal 1']);++ // ⌘1 now activates the leftmost tab, which is Terminal 2.+ act(() =>+ document+ .querySelector<HTMLElement>(+ `[data-terminal-session="${activePanelId()}"] .xterm-helper-textarea`,+ )+ ?.focus(),+ );+ const jump = dispatchChord('1', { metaKey: true });+ expect(jump.defaultPrevented).toBe(true);+ expect(screen.getByRole('tab', { name: 'Terminal 2' }).getAttribute('aria-selected')).toBe(+ 'true',+ );+ });++ test('the reorder chord is left for native editing while a rename input is focused', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ // Enter rename on Terminal 1; its input holds focus.+ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 1' }));+ const input = screen.getByRole('textbox', { name: 'Rename Terminal 1' });++ // The capture-phase handler sees an <input> target and stands down, so the+ // chord is not consumed and no reorder happens.+ const event = new KeyboardEvent('keydown', {+ key: 'ArrowRight',+ metaKey: true,+ shiftKey: true,+ cancelable: true,+ bubbles: true,+ });+ act(() => {+ input.dispatchEvent(event);+ });++ expect(event.defaultPrevented).toBe(false);+ expect(screen.getByRole('textbox', { name: 'Rename Terminal 1' })).toBeDefined();+ });++ test('reordering tabs does not move the session panels (live shells stay put)', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ await addTerminalTab(user);+ // Panels render in stable ordinal order regardless of tab order.+ const panelIds = () => sessionPanels().map((el) => el.getAttribute('data-terminal-session'));+ const stableOrder = ['terminal-session-1', 'terminal-session-2', 'terminal-session-3'];+ expect(panelIds()).toEqual(stableOrder);++ // Reorder the active tab (Terminal 3) one slot left.+ act(() => sessionPanels()[2]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());+ dispatchChord('ArrowLeft', { metaKey: true, shiftKey: true });++ // Tabs reordered, but the panel DOM order is UNCHANGED — the xterm containers+ // never move, so a reorder cannot refit/reset a running shell (SIGWINCH).+ expect(tabLabels()).toEqual(['Terminal 1', 'Terminal 3', 'Terminal 2']);+ expect(panelIds()).toEqual(stableOrder);+ });+test("closing a tab reaps only that session's PTY and leaves the others alive", async () => {const user = userEvent.setup();const view = renderDock(true);diff --git a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsxindex d484c9269..694ff7d0e 100644--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx@@ -28,7 +28,8 @@*/import { afterEach, describe, expect, mock, test } from 'bun:test';-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';+import { userEvent } from '@testing-library/user-event';import { useEffect, useRef, useState } from 'react';import { TooltipProvider } from '@/components/ui/tooltip';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';@@ -141,7 +142,13 @@ function ReloadHarness({* plausible names — the test asserts on the tabs surfaced, never on which alias* the fix calls.*/-function makeSurvivingMainBridge(preExisting: ReadonlyArray<{ ptyId: string }>) {+function makeSurvivingMainBridge(+ preExisting: ReadonlyArray<{+ ptyId: string;+ customLabel?: string | null;+ ordinal?: number | null;+ }>,+) {let freshCounter = 0;const create = mock(async () => {freshCounter += 1;@@ -152,6 +159,8 @@ function makeSurvivingMainBridge(preExisting: ReadonlyArray<{ ptyId: string }>)// session's live PTY is observable.const input = mock((_id: string, _d: string) => {});const listLive = mock(async () => preExisting);+ const setMeta = mock((_ptyId: string, _meta: unknown) => {});+ const setOrder = mock((_ids: readonly string[]) => {});const bridge = {onMenuAction: () => () => {},editor: { notifyViewMenuStateChanged: () => {} },@@ -164,9 +173,11 @@ function makeSurvivingMainBridge(preExisting: ReadonlyArray<{ ptyId: string }>)getSessions: listLive,snapshotSessions: listLive,restoreSessions: listLive,+ setMeta,+ setOrder,},} as unknown as OkDesktopBridge;- return { bridge, create, input, listLive };+ return { bridge, create, input, listLive, setMeta, setOrder };}function renderDock(bridge: OkDesktopBridge, visible: boolean) {@@ -201,6 +212,53 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a);});+ test("restores each survivor's custom name and the reordered tab order across reload", async () => {+ // Main returns survivors already in the user's reordered sequence, each with+ // the metadata it retained across the reload: a custom name on two, a bare+ // sticky ordinal on the third.+ const { bridge } = makeSurvivingMainBridge([+ { ptyId: 'pty-3', customLabel: 'deploy', ordinal: 3 },+ { ptyId: 'pty-1', customLabel: null, ordinal: 1 },+ { ptyId: 'pty-2', customLabel: 'logs', ordinal: 2 },+ ]);++ renderDock(bridge, true);++ await waitFor(() => expect(screen.getAllByTestId('terminal-session')).toHaveLength(3), {+ timeout: 2000,+ });++ // Tabs come back in main's returned (reordered) order with the custom names+ // restored; the un-named survivor falls back to its RESTORED sticky ordinal+ // (Terminal 1), not a positional renumber to Terminal 2.+ const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });+ const tabs = within(tablist).getAllByRole('tab');+ expect(tabs.map((tab) => tab.textContent)).toEqual(['deploy', 'Terminal 1', 'logs']);+ });++ test('a rename pushes the new custom label to main (renderer->main persist path)', async () => {+ const { bridge, setMeta } = makeSurvivingMainBridge([+ { ptyId: 'pty-1', customLabel: null, ordinal: 1 },+ ]);+ const user = userEvent.setup();++ renderDock(bridge, true);+ await waitFor(() => expect(screen.getAllByTestId('terminal-session')).toHaveLength(1), {+ timeout: 2000,+ });++ // Rename the tab: double-click -> inline input -> Enter. This is the push path+ // that keeps the custom name alive across a future reload; it is optional-chained+ // in production, so a mock omitting setMeta would leave it silently unverified.+ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 1' }));+ const input = screen.getByRole('textbox', { name: /^Rename/ });+ await user.clear(input);+ await user.type(input, 'deploy');+ await user.keyboard('{Enter}');++ await waitFor(() => expect(setMeta).toHaveBeenCalledWith('pty-1', { customLabel: 'deploy' }));+ });+// A render that can flip `visible` so the "open the dock after a reload with no// prior terminal" flow is exercised: the dock starts hidden (the reload restored// no visibility, since nothing was open), rehydration finds zero survivors anddiff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsxindex 0acb282a2..c18977d69 100644--- a/packages/app/src/components/TerminalSessionsHost.tsx+++ b/packages/app/src/components/TerminalSessionsHost.tsx@@ -25,11 +25,20 @@ import { TerminalTabStrip } from './TerminalTabStrip';* sessions opened from the tab strip carry none. `title` is the latest OSC 0/2* title the running program set (null → the tab shows its positional default).* `adoptPtyId` is the surviving ptyId after a renderer reload — the session- * adopts that live shell instead of spawning a fresh one; null for new tabs. */+ * adopts that live shell instead of spawning a fresh one; null for new tabs.+ * `customLabel` is a user-set tab name that pins over `title`; null until the+ * user renames the tab (an empty rename commit clears it back to null).+ * `ordinal` is an immutable per-session number assigned at creation from the+ * monotonic counter — the positional-fallback label ("Terminal N") uses it so a+ * reorder does not renumber untitled tabs (the number sticks to the session, not+ * the slot). Ordinals can have gaps (closing a tab leaves one) and reset to+ * positional on a renderer reload. */interface TerminalSessionDescriptor {readonly id: string;readonly launch: TerminalLaunchIntent | null;readonly title: string | null;+ readonly customLabel: string | null;+ readonly ordinal: number;readonly adoptPtyId: string | null;}@@ -47,6 +56,19 @@ function focusTerminalSession(id: string) {?.focus();}+/** True when keyboard focus currently sits inside the stable host div. */+function focusInsideHost(hostEl: HTMLElement | null): boolean {+ return hostEl?.contains(document.activeElement) ?? false;+}++/** Focus-gate shared by the terminal host's capture-phase keyboard chords (⌘1–9,+ * ⌘⇧←/→): a chord is in scope always in the window variant (the whole window IS+ * the terminal), and in the dock variant only while focus sits inside the host —+ * so the chords stay free everywhere else in the editor window. */+function chordTargetsHost(hostEl: HTMLElement | null, variant: 'dock' | 'window'): boolean {+ return variant === 'window' || focusInsideHost(hostEl);+}+interface TerminalSessionsHostProps {/** Desktop bridge — the host renders only on the Electron surface. */readonly bridge: OkDesktopBridge;@@ -160,7 +182,16 @@ export function TerminalSessionsHost({// set.const [sessions, setSessions] = useState<readonly TerminalSessionDescriptor[]>(() =>!canRehydrate && visible- ? [{ id: makeSessionId(1), launch, title: null, adoptPtyId: null }]+ ? [+ {+ id: makeSessionId(1),+ launch,+ title: null,+ customLabel: null,+ ordinal: 1,+ adoptPtyId: null,+ },+ ]: [],);const [activeSessionId, setActiveSessionId] = useState(() =>@@ -195,8 +226,21 @@ export function TerminalSessionsHost({// or torn down).const ptyIdBySessionRef = useRef(new Map<string, string>());function setSessionPtyId(id: string, ptyId: string | null) {- if (ptyId === null) ptyIdBySessionRef.current.delete(id);- else ptyIdBySessionRef.current.set(id, ptyId);+ if (ptyId === null) {+ ptyIdBySessionRef.current.delete(id);+ return;+ }+ ptyIdBySessionRef.current.set(id, ptyId);+ // Seed main with this session's reload-survival metadata as soon as its PTY+ // exists — the sticky ordinal (fixed at creation) plus any name set before the+ // shell spawned. Main outlives a renderer reload, so `list` reads it back.+ const session = sessionsRef.current.find((s) => s.id === id);+ if (session != null) {+ bridge.terminal?.setMeta?.(ptyId, {+ ordinal: session.ordinal,+ customLabel: session.customLabel,+ });+ }}// Monotonic nonce for tab-strip "New chat" launches. TerminalLaunchIntent// requires a nonce, but it is only load-bearing for the EditorPane→prop@@ -209,7 +253,14 @@ export function TerminalSessionsHost({const id = makeSessionId(sessionCounterRef.current);setSessions((prev) => [...prev,- { id, launch: launchForSession, title: null, adoptPtyId: null },+ {+ id,+ launch: launchForSession,+ title: null,+ customLabel: null,+ ordinal: sessionCounterRef.current,+ adoptPtyId: null,+ },]);setActiveSessionId(id);}@@ -273,6 +324,85 @@ export function TerminalSessionsHost({return prev.map((session) => (session.id === id ? { ...session, title: next } : session));});}++ // Commit a manual tab rename. A trimmed-empty value clears the custom label+ // (revert to OSC title / positional default). Same same-reference bailout as+ // setSessionTitle so an unchanged value causes no re-render.+ function setSessionCustomLabel(id: string, label: string) {+ const next = label.trim() === '' ? null : label.trim();+ setSessions((prev) => {+ if (!prev.some((session) => session.id === id && session.customLabel !== next)) return prev;+ return prev.map((session) =>+ session.id === id ? { ...session, customLabel: next } : session,+ );+ });+ // Persist the rename to main so it survives a renderer reload.+ const ptyId = ptyIdBySessionRef.current.get(id);+ if (ptyId != null) bridge.terminal?.setMeta?.(ptyId, { customLabel: next });+ }++ // Display label precedence, shared by the tab list and the reorder announcer:+ // a manual name pins over the OSC title, which pins over the sticky ordinal.+ function sessionLabel(session: TerminalSessionDescriptor): string {+ return session.customLabel ?? session.title ?? t`Terminal ${session.ordinal}`;+ }++ // True while a pointer drag is lifted (reported by the strip); the ⌘⇧←/→ chord+ // is suppressed then so the two reorder inputs never mutate order concurrently.+ const dragActiveRef = useRef(false);+ // sr-only polite live region for keyboard-reorder announcements. Imperative+ // textContent + trailing debounce (React batching would swallow rapid updates —+ // the app's announcer precedent); pointer drags keep dnd-kit's own announcements.+ const announcerRef = useRef<HTMLSpanElement>(null);+ const announceTimerRef = useRef<number | null>(null);++ // Apply a reorder from a desired visual order of session ids — the single spine+ // for both the pointer drag (strip) and the keyboard path. A length or unknown-id+ // mismatch refuses the whole reorder (no partial mutation); an unchanged order+ // keeps the same array reference (render bailout).+ function reorderSessions(newOrderIds: readonly string[]) {+ setSessions((prev) => {+ if (newOrderIds.length !== prev.length) return prev;+ const byId = new Map(prev.map((session) => [session.id, session]));+ const next: TerminalSessionDescriptor[] = [];+ for (const id of newOrderIds) {+ const session = byId.get(id);+ if (session == null) return prev;+ next.push(session);+ }+ if (next.every((session, index) => session === prev[index])) return prev;+ return next;+ });+ // Persist the new display order to main (ptyIds in visual order) so a drag /+ // keyboard reorder survives a renderer reload. Sessions without a live PTY yet+ // are skipped; main slots them after the listed block via its own fallback.+ const orderedPtyIds = newOrderIds+ .map((id) => ptyIdBySessionRef.current.get(id))+ .filter((ptyId): ptyId is string => ptyId != null);+ if (orderedPtyIds.length > 0) bridge.terminal?.setOrder?.(orderedPtyIds);+ }++ // Move the active tab one slot (keyboard reorder). Reads the post-commit mirror+ // (same source as ⌘1–9), no-ops at the edges, and returns the moved tab's label+ // + new 1-based position for the SR announcement (null = nothing moved).+ function moveActiveSession(+ direction: -1 | 1,+ ): { label: string; position: number; total: number } | null {+ const current = sessionsRef.current;+ const from = current.findIndex((session) => session.id === activeSessionIdRef.current);+ if (from < 0) return null;+ const to = from + direction;+ if (to < 0 || to >= current.length) return null;+ const ids = current.map((session) => session.id);+ const [movedId] = ids.splice(from, 1);+ ids.splice(to, 0, movedId);+ reorderSessions(ids);+ return { label: sessionLabel(current[from]), position: to + 1, total: current.length };+ }+ // Latest-ref so the keyboard effect calls the current closure without+ // re-subscribing (React Compiler forbids writing the ref during render).+ const moveActiveSessionRef = useRef(moveActiveSession);+// Latest-ref so deps-stable effects below call the current closure without// re-subscribing (React Compiler forbids writing the ref during render).const openSessionRef = useRef(openSession);@@ -307,6 +437,7 @@ export function TerminalSessionsHost({useEffect(() => {openSessionRef.current = openSession;+ moveActiveSessionRef.current = moveActiveSession;activeSessionIdRef.current = activeSessionId;sessionsRef.current = sessions;closeActiveRef.current = () => {@@ -354,7 +485,11 @@ export function TerminalSessionsHost({rehydratedRef.current = true;let cancelled = false;void (async () => {- let survivors: readonly { ptyId: string }[] = [];+ let survivors: readonly {+ ptyId: string;+ customLabel: string | null;+ ordinal: number | null;+ }[] = [];try {survivors = (await bridge.terminal.list()) ?? [];} catch (err) {@@ -370,9 +505,16 @@ export function TerminalSessionsHost({id: makeSessionId(index + 1),launch: null,title: null,+ // Restored from main so a rename + reorder survive a renderer reload;+ // ordinal falls back to positional for a session main never received one+ // for (created in the reload gap).+ customLabel: entry.customLabel ?? null,+ ordinal: entry.ordinal ?? index + 1,adoptPtyId: entry.ptyId,}));- sessionCounterRef.current = recovered.length;+ // Continue numbering above the highest restored ordinal so a new tab can't+ // collide with a survivor's sticky number.+ sessionCounterRef.current = Math.max(recovered.length, ...recovered.map((r) => r.ordinal));setSessions(recovered);setActiveSessionId(recovered[0]?.id ?? '');}@@ -439,8 +581,7 @@ export function TerminalSessionsHost({function onKeyDown(event: KeyboardEvent) {if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;if (!/^[1-9]$/.test(event.key)) return;- if (variant !== 'window' && (hostEl == null || !hostEl.contains(document.activeElement)))- return;+ if (!chordTargetsHost(hostEl, variant)) return;const target = sessionsRef.current[Number(event.key) - 1];if (target == null) return;event.preventDefault();@@ -452,6 +593,50 @@ export function TerminalSessionsHost({return () => window.removeEventListener('keydown', onKeyDown, { capture: true });}, [hostEl, variant]);+ // ⌘⇧← / ⌘⇧→ move the ACTIVE tab one slot. Same capture-phase + focus-gate shape+ // as ⌘1–9 (so a focused xterm doesn't swallow it, and the chord stays free+ // outside the terminal in the dock). Meta+Shift only — a focused xterm encodes+ // ⌃/⌥-arrows into the PTY, but leaves meta-modified arrows to the app. Suppressed+ // while the rename input is focused (event target is an <input> — xterm's focus+ // sink is a <textarea>, so the chord still works while typing in the shell) and+ // while a pointer drag is lifted. Keyboard reorders announce via the sr-only+ // region; pointer drags keep dnd-kit's own announcements.+ useEffect(() => {+ function onKeyDown(event: KeyboardEvent) {+ if (!event.metaKey || !event.shiftKey || event.ctrlKey || event.altKey) return;+ const direction = event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowRight' ? 1 : 0;+ if (direction === 0) return;+ if (!chordTargetsHost(hostEl, variant)) return;+ if (dragActiveRef.current) return;+ const target = event.target as HTMLElement | null;+ if (target?.tagName === 'INPUT' || target?.isContentEditable) return;+ const moved = moveActiveSessionRef.current(direction);+ if (moved == null) return; // no-op at the edges+ event.preventDefault();+ event.stopPropagation();+ queueMicrotask(() => focusTerminalSession(activeSessionIdRef.current));+ // Announce via the sr-only region (stable refs only; trailing debounce so+ // rapid repeats don't flood — React batching would swallow direct updates).+ const message = t`Moved ${moved.label} to position ${moved.position} of ${moved.total}`;+ if (announceTimerRef.current != null) window.clearTimeout(announceTimerRef.current);+ announceTimerRef.current = window.setTimeout(() => {+ announceTimerRef.current = null;+ if (announcerRef.current != null) announcerRef.current.textContent = message;+ }, 60);+ }+ window.addEventListener('keydown', onKeyDown, { capture: true });+ return () => {+ window.removeEventListener('keydown', onKeyDown, { capture: true });+ // Cancel any in-flight announce debounce: this effect re-runs on locale+ // change and tears down on unmount, and a pending 60 ms timer would+ // otherwise fire a stale-closure message against the old `t`/a dead node.+ if (announceTimerRef.current != null) {+ window.clearTimeout(announceTimerRef.current);+ announceTimerRef.current = null;+ }+ };+ }, [hostEl, variant, t]);+// Reflect PTY liveness to main so the Terminal menu's "Kill Terminal" item// enables only while at least one session is live. A collapsed-but-alive// terminal still counts: the session list tracks the latch, not visibility.@@ -475,7 +660,7 @@ export function TerminalSessionsHost({// collapse, close-last) always sets `visible` false, so focus-return still fires.useLayoutEffect(() => {if (isShowing || visible) return;- if (hostEl == null || !hostEl.contains(document.activeElement)) return;+ if (!focusInsideHost(hostEl)) return;onRequestEditorFocus();}, [isShowing, visible, hostEl, onRequestEditorFocus]);@@ -487,12 +672,23 @@ export function TerminalSessionsHost({focusTerminalSession(activeSessionIdRef.current);}, [isShowing]);- const tabDescriptors = sessions.map((session, index) => ({+ const tabDescriptors = sessions.map((session) => ({id: session.id,- // The program's OSC title when it set one, else the positional default.- label: session.title ?? t`Terminal ${index + 1}`,+ // A user-set custom name pins over the program's OSC title, which pins over+ // the sticky positional default. The default uses the session's immutable+ // ordinal (not its render index) so a reorder never renumbers untitled tabs.+ label: session.customLabel ?? session.title ?? t`Terminal ${session.ordinal}`,}));+ // Panels render in a STABLE order (by immutable ordinal), deliberately+ // decoupled from the tab order. A reorder must not move a panel's DOM node:+ // moving an xterm container fires its ResizeObserver refit (SIGWINCH), which+ // makes the running program (e.g. a Claude TUI) repaint and lose its screen —+ // reordering tabs would otherwise reset the live shell. The tabs reorder; the+ // panels stay put. Radix associates each panel with its trigger by `value`,+ // not DOM order, so the active panel still shows regardless of position.+ const panelSessions = [...sessions].sort((a, b) => a.ordinal - b.ordinal);+const sessionViews =sessions.length > 0 ? (<TerminalTabStrip@@ -507,6 +703,14 @@ export function TerminalSessionsHost({onNewChatPickCli={pickNewChatCli}onNewChatPickTerminal={pickNewChatTerminal}onClose={closeSession}+ onRename={setSessionCustomLabel}+ // Pointer-drag reorder: the strip computes the new visual order and the+ // host applies it (keyboard reorder shares reorderSessions). onDragActive+ // gates the ⌘⇧←/→ chord off while a drag is lifted.+ onReorder={reorderSessions}+ onDragActiveChange={(active) => {+ dragActiveRef.current = active;+ }}dockPosition={dockPosition}onToggleDock={onToggleDock}// Collapse hides the terminal but keeps every session alive (hide is not@@ -517,10 +721,12 @@ export function TerminalSessionsHost({draggable={variant === 'window'}className="h-full">- {sessions.map((session) => (+ {panelSessions.map((session) => (// forceMount keeps every session mounted (active shown, inactive// CSS-hidden) so each retains its xterm scrollback and keeps consuming- // output — switching tabs is show/hide, never unmount.+ // output — switching tabs is show/hide, never unmount. Iterating+ // `panelSessions` (stable ordinal order), NOT `sessions`, so a tab+ // reorder never moves a panel's DOM node (see panelSessions above).<TabsContentkey={session.id}value={session.id}@@ -560,6 +766,21 @@ export function TerminalSessionsHost({// Render the session subtree into the stable host div (which the relocate effect// appends to the active container). A constant portal target = no remount on a- // dock move.- return hostEl != null ? createPortal(sessionViews, hostEl) : null;+ // dock move. The sr-only announcer rides alongside so keyboard reorders are+ // announced (its textContent is set imperatively; see announceReorder).+ return hostEl != null+ ? createPortal(+ <>+ {sessionViews}+ <span+ ref={announcerRef}+ aria-live="polite"+ aria-atomic="true"+ className="sr-only"+ data-testid="terminal-reorder-announcer"+ />+ </>,+ hostEl,+ )+ : null;}diff --git a/packages/app/src/components/TerminalTabStrip.dom.test.tsx b/packages/app/src/components/TerminalTabStrip.dom.test.tsxindex adc43a032..681d981e7 100644--- a/packages/app/src/components/TerminalTabStrip.dom.test.tsx+++ b/packages/app/src/components/TerminalTabStrip.dom.test.tsx@@ -16,6 +16,8 @@ function renderStrip(props?: {dockPosition?: 'bottom' | 'right';newChatSelected?: 'claude' | 'codex' | 'opencode' | 'cursor' | 'terminal';draggable?: boolean;+ /** Omit the rename handler to assert the affordance is inert without it. */+ renameDisabled?: boolean;}) {const onSelect = mock((_id: string) => {});const onTabActivate = mock((_id: string) => {});@@ -23,9 +25,10 @@ function renderStrip(props?: {const onNewChatPickCli = mock((_cli: string) => {});const onNewChatPickTerminal = mock(() => {});const onClose = mock((_id: string) => {});+ const onRename = mock((_id: string, _label: string) => {});const onToggleDock = mock(() => {});const onCollapse = mock(() => {});- render(+ const view = render(// The app mounts a root TooltipProvider (main.tsx); the strip's control// tooltips need that context, so the isolated render supplies its own.// `draggable` mirrors the standalone terminal window's prop shape (same@@ -41,6 +44,7 @@ function renderStrip(props?: {onNewChatPickCli={onNewChatPickCli}onNewChatPickTerminal={onNewChatPickTerminal}onClose={onClose}+ onRename={props?.renameDisabled ? undefined : onRename}dockPosition={props?.draggable ? undefined : (props?.dockPosition ?? 'bottom')}onToggleDock={props?.draggable ? undefined : onToggleDock}onCollapse={props?.draggable ? undefined : onCollapse}@@ -55,8 +59,10 @@ function renderStrip(props?: {onNewChatPickCli,onNewChatPickTerminal,onClose,+ onRename,onToggleDock,onCollapse,+ rerender: view.rerender,};}@@ -275,4 +281,190 @@ describe('TerminalTabStrip', () => {expect(onNewChatLaunch).toHaveBeenCalledTimes(1);expect(onClose).toHaveBeenCalledWith('s1');});++ // ---- Manual rename: double-click / F2 → inline input ----++ test('double-clicking a tab opens an inline rename input, prefilled and focused', async () => {+ const user = userEvent.setup();+ renderStrip({ activeSessionId: 's2' });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 2' }));++ const input = screen.getByRole('textbox', { name: 'Rename Terminal 2' });+ expect(input).toBe(document.activeElement);+ expect((input as HTMLInputElement).value).toBe('Terminal 2');+ // The renaming tab's trigger is REPLACED by the input (never nested inside a+ // role="tab" button); the other tabs keep their triggers.+ expect(screen.queryByRole('tab', { name: 'Terminal 2' })).toBeNull();+ expect(screen.getByRole('tab', { name: 'Terminal 1' })).toBeDefined();+ expect(input.closest('[role="tab"]')).toBeNull();+ });++ test('double-click that opens rename fires onTabActivate at most once (second click suppressed)', async () => {+ const user = userEvent.setup();+ const { onTabActivate } = renderStrip({ activeSessionId: 's1' });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 2' }));++ // A double-click dispatches two click events (detail 1 then detail 2). The+ // onClick guard suppresses the detail>=2 one; without it, the second+ // activation focuses the terminal and blur-commits the rename input the same+ // gesture just opened. Exactly one call (the initial detail=1 select) pins+ // the guard — a regression that dropped or inverted it would read 2.+ expect(onTabActivate).toHaveBeenCalledTimes(1);+ expect(onTabActivate).toHaveBeenCalledWith('s2');+ // The rename input is open and focused — the activation did not steal it.+ expect(screen.getByRole('textbox', { name: 'Rename Terminal 2' })).toBe(document.activeElement);+ });++ test('F2 on a focused tab trigger opens the rename input (keyboard entry)', async () => {+ const user = userEvent.setup();+ renderStrip({ activeSessionId: 's1' });+ const tab = screen.getByRole('tab', { name: 'Terminal 1' });+ act(() => tab.focus());++ await user.keyboard('{F2}');++ expect(screen.getByRole('textbox', { name: 'Rename Terminal 1' })).toBe(document.activeElement);+ });++ test('Enter commits the trimmed new name via onRename and exits rename mode', async () => {+ const user = userEvent.setup();+ const { onRename } = renderStrip({ activeSessionId: 's2' });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 2' }));+ const input = screen.getByRole('textbox', { name: 'Rename Terminal 2' });+ await user.clear(input);+ await user.type(input, ' build ');+ await user.keyboard('{Enter}');++ expect(onRename).toHaveBeenCalledTimes(1);+ expect(onRename).toHaveBeenCalledWith('s2', 'build');+ // Strip is controlled — the visible label only changes when the parent+ // re-renders; here we assert the input closed and the trigger returned.+ expect(screen.queryByRole('textbox', { name: /Rename/ })).toBeNull();+ expect(screen.getByRole('tab', { name: 'Terminal 2' })).toBeDefined();+ });++ test('blurring the rename input commits the value', async () => {+ const user = userEvent.setup();+ const { onRename } = renderStrip({ activeSessionId: 's2' });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 2' }));+ const input = screen.getByRole('textbox', { name: 'Rename Terminal 2' });+ await user.clear(input);+ await user.type(input, 'logs');+ act(() => (input as HTMLInputElement).blur());++ expect(onRename).toHaveBeenCalledWith('s2', 'logs');+ });++ test('Escape cancels without committing and restores the tab trigger', async () => {+ const user = userEvent.setup();+ const { onRename } = renderStrip({ activeSessionId: 's2' });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 2' }));+ const input = screen.getByRole('textbox', { name: 'Rename Terminal 2' });+ await user.clear(input);+ await user.type(input, 'discard-me');+ await user.keyboard('{Escape}');++ // Escape sets the cancel guard, then blurs — the ensuing blur must NOT commit.+ expect(onRename).not.toHaveBeenCalled();+ expect(screen.queryByRole('textbox', { name: /Rename/ })).toBeNull();+ expect(screen.getByRole('tab', { name: 'Terminal 2' })).toBeDefined();+ });++ test('an empty commit clears the custom label (onRename with empty string)', async () => {+ const user = userEvent.setup();+ const { onRename } = renderStrip({+ activeSessionId: 's2',+ sessions: [{ id: 's2', label: 'my build' }],+ });++ await user.dblClick(screen.getByRole('tab', { name: 'my build' }));+ const input = screen.getByRole('textbox', { name: 'Rename my build' });+ await user.clear(input);+ await user.keyboard('{Enter}');++ expect(onRename).toHaveBeenCalledWith('s2', '');+ });++ test('a whitespace-only commit trims to empty and clears the custom label', async () => {+ const user = userEvent.setup();+ const { onRename } = renderStrip({+ activeSessionId: 's2',+ sessions: [{ id: 's2', label: 'my build' }],+ });++ await user.dblClick(screen.getByRole('tab', { name: 'my build' }));+ const input = screen.getByRole('textbox', { name: 'Rename my build' });+ // Whitespace-only input must trim to '' -> label-clear, not a real label of+ // spaces. Exercises the trim->empty path end-to-end (a broken trim would+ // silently promote whitespace to a custom label).+ await user.clear(input);+ await user.type(input, ' ');+ await user.keyboard('{Enter}');++ expect(onRename).toHaveBeenCalledWith('s2', '');+ });++ test('a tab that disappears mid-rename auto-cancels the input', async () => {+ const user = userEvent.setup();+ const { rerender } = renderStrip({ activeSessionId: 's3' });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 3' }));+ expect(screen.getByRole('textbox', { name: 'Rename Terminal 3' })).toBeDefined();++ // The session closes (PTY exit / ⌘W) — its descriptor leaves `sessions`.+ rerender(+ <TooltipProvider>+ <TerminalTabStrip+ sessions={[+ { id: 's1', label: 'Terminal 1' },+ { id: 's2', label: 'Terminal 2' },+ ]}+ activeSessionId="s1"+ onSelect={() => {}}+ newChatSelected="claude"+ onNewChatLaunch={() => {}}+ onNewChatPickCli={() => {}}+ onNewChatPickTerminal={() => {}}+ onClose={() => {}}+ onRename={() => {}}+ dockPosition="bottom"+ onToggleDock={() => {}}+ onCollapse={() => {}}+ />+ </TooltipProvider>,+ );++ expect(screen.queryByRole('textbox', { name: /Rename/ })).toBeNull();+ });++ test('without an onRename handler the rename affordance is inert', async () => {+ const user = userEvent.setup();+ renderStrip({ activeSessionId: 's2', renameDisabled: true });++ await user.dblClick(screen.getByRole('tab', { name: 'Terminal 2' }));++ expect(screen.queryByRole('textbox', { name: /Rename/ })).toBeNull();+ expect(screen.getByRole('tab', { name: 'Terminal 2' })).toBeDefined();+ });++ // ---- Reorder wiring ----+ // Pointer-drag geometry is covered by the chrome module's unit suite and the+ // opt-in desktop smoke (jsdom cannot faithfully simulate the pointer sensor);+ // here we pin that every tab is a sortable node and the tablist role survives+ // the dnd-kit wrapping (no injected role="button" on the wrapper).++ test('every tab is wrapped in a sortable node without disturbing the tablist', () => {+ renderStrip();+ expect(document.querySelectorAll('[data-terminal-tab-sortable]')).toHaveLength(3);+ // The dnd-kit wrapper is not focusable and adds no role — the Radix tablist+ // still sees exactly three tabs.+ const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });+ expect(within(tablist).getAllByRole('tab')).toHaveLength(3);+ expect(within(tablist).queryAllByRole('button', { name: /^Terminal/ })).toHaveLength(0);+ });});diff --git a/packages/app/src/components/TerminalTabStrip.tsx b/packages/app/src/components/TerminalTabStrip.tsxindex 8b4d003fd..e7fae9095 100644--- a/packages/app/src/components/TerminalTabStrip.tsx+++ b/packages/app/src/components/TerminalTabStrip.tsx@@ -1,3 +1,10 @@+import { DndContext, type DragEndEvent, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';+import {+ arrayMove,+ horizontalListSortingStrategy,+ SortableContext,+ useSortable,+} from '@dnd-kit/sortable';import type { TerminalCli } from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import {@@ -7,14 +14,76 @@ import {PanelRightIcon,XIcon,} from 'lucide-react';-import type { ReactNode } from 'react';+import { type ReactNode, useEffect, useRef, useState } from 'react';import { Button } from '@/components/ui/button';+import { InputGroup, InputGroupInput } from '@/components/ui/input-group';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import type { TerminalDockPosition } from '@/lib/terminal-dock-store';import { cn } from '@/lib/utils';+import {+ createTabReorderModifier,+ getSortableTabStyle,+ measureTabReorderBounds,+ TAB_REORDER_AUTO_SCROLL,+ type TabReorderBounds,+ tabRunCollisionDetection,+} from './editor-tabs-chrome';import { TerminalNewChatButton, type TerminalNewTabChoice } from './TerminalNewChatButton';+/** Attribute marking a terminal tab's sortable node — the surface-neutral chrome+ * module measures the reorder bounds against this (editor tabs use their own). */+const TERMINAL_TAB_SORTABLE_SELECTOR = '[data-terminal-tab-sortable]';++/**+ * One terminal tab as a `@dnd-kit/sortable` node. Only the pointer listeners ++ * transform are wired (no `attributes` spread and no `KeyboardSensor`): dnd-kit's+ * `attributes` would inject `role="button"` + `tabIndex` onto this wrapper and+ * break the Radix tablist's roving-focus semantics, and keyboard reorder is a+ * dedicated ⌘⇧←/→ chord in the host rather than dnd-kit's Space-lift model. The+ * wrapper is not focusable, so its listeners never intercept Radix arrow keys or+ * the trigger's F2. `disabled` short-circuits sortable while any rename is open.+ */+function SortableTerminalTab({+ id,+ disabled,+ isActive,+ children,+}: {+ id: string;+ disabled: boolean;+ isActive: boolean;+ children: ReactNode;+}) {+ const { setNodeRef, listeners, rect, transform, transition, isDragging } = useSortable({+ id,+ disabled,+ });+ const style = getSortableTabStyle({+ activeWidth: rect.current?.width,+ isDragging,+ transform,+ transition,+ });+ return (+ // dnd-kit pointer listeners on a non-focusable wrapper; the role="tab" child+ // owns keyboard + a11y, so this div carries no interactive role of its own.+ <div+ ref={setNodeRef}+ data-terminal-tab-sortable=""+ style={style}+ className={cn(+ 'group flex shrink-0 cursor-default items-center rounded-md pr-0.5 transition-colors',+ isActive ? 'bg-muted' : 'hover:bg-muted/50',+ isDragging && 'z-10',+ )}+ {...listeners}+ >+ {children}+ </div>+ );+}+/** One terminal session as the tab strip sees it: a stable id and a display label. */export interface TerminalTabDescriptor {readonly id: string;@@ -47,6 +116,24 @@ interface TerminalTabStripProps {readonly onNewChatPickTerminal: () => void;/** Fires with the session id when the user closes a tab. */readonly onClose: (id: string) => void;+ /**+ * Commit a manual tab rename: the trimmed label the user typed, or the empty+ * string to clear a previously-set custom name (revert to the program's OSC+ * title / positional default). Fires on Enter or blur, never on Escape. When+ * omitted, the rename affordance (double-click / F2) is inert — the host owns+ * whether a surface supports renaming.+ */+ readonly onRename?: (id: string, label: string) => void;+ /**+ * Commit a pointer-drag reorder: the new visual order of session ids after a+ * drop. When omitted, tabs are not draggable.+ */+ readonly onReorder?: (newOrderIds: readonly string[]) => void;+ /**+ * Reports whether a pointer drag is currently lifted, so the host can suppress+ * the ⌘⇧←/→ keyboard-reorder chord while a drag is in flight.+ */+ readonly onDragActiveChange?: (active: boolean) => void;/** Where the terminal is currently docked — drives the dock-toggle + collapse* button icons/labels. Absent on the standalone terminal window (nothing to* dock or collapse — the window is the terminal). */@@ -115,6 +202,9 @@ export function TerminalTabStrip({onNewChatPickCli,onNewChatPickTerminal,onClose,+ onRename,+ onReorder,+ onDragActiveChange,dockPosition,onToggleDock,onCollapse,@@ -124,6 +214,97 @@ export function TerminalTabStrip({}: TerminalTabStripProps) {const { t } = useLingui();const rightDocked = dockPosition === 'right';++ // Inline rename is transient presentation state owned here; the host owns the+ // durable custom label and receives the commit via onRename. Mirrors the+ // editor file-tab rename contract (double-click / F2 to enter, Enter or blur+ // to commit, Escape to cancel) without any of its document-rename plumbing.+ const [renamingId, setRenamingId] = useState<string | null>(null);+ const [renameValue, setRenameValue] = useState('');+ const renameInputRef = useRef<HTMLInputElement>(null);+ // Set the instant Escape fires so the ensuing blur does not commit —+ // Escape-then-blur must cancel. Reset after each rename ends.+ const cancelRenameRef = useRef(false);+ const renameEnabled = onRename != null;++ // Focus + select-all when a rename opens so the user types over the label.+ useEffect(() => {+ if (renamingId == null) return;+ renameInputRef.current?.focus();+ renameInputRef.current?.select();+ }, [renamingId]);++ // A tab that closes (PTY exit, ⌘W) mid-rename auto-cancels — its descriptor is+ // gone from `sessions`, so there is nothing left to commit to.+ useEffect(() => {+ if (renamingId != null && !sessions.some((session) => session.id === renamingId)) {+ cancelRenameRef.current = false;+ setRenamingId(null);+ setRenameValue('');+ }+ }, [sessions, renamingId]);++ function enterRename(session: TerminalTabDescriptor) {+ if (!renameEnabled) return;+ cancelRenameRef.current = false;+ setRenamingId(session.id);+ setRenameValue(session.label);+ }++ // Return focus to the tab's trigger after the input unmounts so a keyboard+ // user who renamed is not stranded on the document body.+ function focusTrigger(id: string) {+ // Session ids are attribute-safe (`terminal-session-<n>`), but escape+ // defensively where `CSS.escape` exists (absent in the jsdom test preload).+ const safeId = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(id) : id;+ queueMicrotask(() => {+ document.querySelector<HTMLElement>(`[role="tab"][data-tab-id="${safeId}"]`)?.focus();+ });+ }++ // Single exit point for commit AND cancel: Enter/Escape only blur the input,+ // and the input's blur is the sole caller — so a value is never committed+ // twice, and Escape's cancel flag suppresses the commit on the same blur.+ function endRename(id: string) {+ if (!cancelRenameRef.current) onRename?.(id, renameValue.trim());+ cancelRenameRef.current = false;+ setRenamingId(null);+ setRenameValue('');+ focusTrigger(id);+ }++ // Pointer-drag reorder. PointerSensor distance:8 keeps a plain click (activate+ // / double-click-to-rename) from starting a drag. No KeyboardSensor — keyboard+ // reorder is the host's ⌘⇧←/→ chord, so arrow keys stay with Radix roving focus.+ // Drag is disabled entirely while a rename is open. The chrome module (shared+ // with editor tabs) supplies the horizontal clamp, edge-snap collision, and+ // width stabilization; bounds are measured against the row on drag start.+ const rowRef = useRef<HTMLDivElement>(null);+ const [tabReorderBounds, setTabReorderBounds] = useState<TabReorderBounds | null>(null);+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));+ const reorderEnabled = onReorder != null;+ const reorderModifiers = [createTabReorderModifier(tabReorderBounds)];++ function handleDragStart() {+ setTabReorderBounds(measureTabReorderBounds(rowRef.current, TERMINAL_TAB_SORTABLE_SELECTOR));+ onDragActiveChange?.(true);+ }+ function handleDragEnd(event: DragEndEvent) {+ setTabReorderBounds(null);+ onDragActiveChange?.(false);+ const activeId = String(event.active.id);+ const overId = event.over ? String(event.over.id) : null;+ if (!overId || activeId === overId) return;+ const ids = sessions.map((session) => session.id);+ const from = ids.indexOf(activeId);+ const to = ids.indexOf(overId);+ if (from < 0 || to < 0 || from === to) return;+ onReorder?.(arrayMove(ids, from, to));+ }+ function handleDragCancel() {+ setTabReorderBounds(null);+ onDragActiveChange?.(false);+ }return (<Tabsvalue={activeSessionId}@@ -131,6 +312,7 @@ export function TerminalTabStrip({className={cn('flex min-h-0 min-w-0 flex-1 flex-col', className)}><div+ ref={rowRef}// Window mode: this row is the macOS title bar — h-[62px] to center the// tabs against the traffic lights, traffic-light reserve so the first tab// clears them, and a drag handle on the empty area (controls opt out via@@ -161,71 +343,153 @@ export function TerminalTabStrip({// No `flex-1`: the list sizes to its tabs so "New chat" can hug the// last one. `min-w-0` + `overflow-x-auto` keep the tabs scrolling// internally when they overflow the space the trailing controls leave.- className="flex h-auto min-w-0 items-center justify-start gap-0.5 overflow-x-auto bg-transparent p-0 [scrollbar-width:none] scroll-fade-mask-x"+ // Window mode: the whole tab run (incl. inter-tab gaps) is `no-drag` so+ // a pointer drag crossing a gap reorders instead of moving the window;+ // the row's empty space outside the run stays a drag region.+ className={cn(+ 'flex h-auto min-w-0 items-center justify-start gap-0.5 overflow-x-auto bg-transparent p-0 [scrollbar-width:none] scroll-fade-mask-x',+ draggable && '[-webkit-app-region:no-drag]',+ )}>- {sessions.map((session) => {- const isActive = session.id === activeSessionId;- return (- <div- key={session.id}- className={cn(- 'group flex shrink-0 cursor-default items-center rounded-md pr-0.5 transition-colors',- isActive ? 'bg-muted' : 'hover:bg-muted/50',- )}- >- {/* The label truncates at max-w-40, so a process-set title- (OSC 0/2) that overflows is hard-clipped in the tab — the- tooltip surfaces the full title on hover. */}- <Tooltip>- <TooltipTrigger asChild>- <TabsTrigger- value={session.id}- // Pointer/Enter activation routes through onClick (arrow-key- // navigation does not fire it), so the consumer can focus the- // terminal on a deliberate select without stealing focus while- // the user arrows across tabs.- onClick={() => onTabActivate?.(session.id)}- className={cn(- 'h-7 flex-none rounded-md px-2 text-xs',- draggable && '[-webkit-app-region:no-drag]',- )}- >- <span className="max-w-40 truncate">{session.label}</span>- </TabsTrigger>- </TooltipTrigger>- <TooltipContent side="bottom" sideOffset={8}>- {session.label}- </TooltipContent>- </Tooltip>- <Button- type="button"- variant="ghost"- size="icon-xs"- aria-label={t`Close ${session.label}`}- // Match the editor-tab pattern: only the active tab's close- // control sits in the tab order, so a keyboard user reaches a- // tab's close after activating it rather than tabbing past every- // inactive tab's close button.- tabIndex={isActive ? 0 : -1}- // Close reveals on tab hover or keyboard focus; the active tab- // keeps it persistently visible. Opacity (not unmount) keeps the- // control in layout + a11y tree so tabs don't reflow and the- // keyboard target stays reachable.- className={cn(- 'text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100',- isActive && 'opacity-100',- draggable && '[-webkit-app-region:no-drag]',- )}- onClick={(event) => {- event.stopPropagation();- onClose(session.id);- }}- >- <XIcon aria-hidden="true" />- </Button>- </div>- );- })}+ <DndContext+ sensors={sensors}+ autoScroll={TAB_REORDER_AUTO_SCROLL}+ collisionDetection={tabRunCollisionDetection}+ modifiers={reorderModifiers}+ onDragStart={handleDragStart}+ onDragEnd={handleDragEnd}+ onDragCancel={handleDragCancel}+ // Portal dnd-kit's SR live-region/described-by helpers to the body so+ // they don't land inside the tablist flex flow (same as editor tabs).+ accessibility={{+ container: typeof document !== 'undefined' ? document.body : undefined,+ }}+ >+ <SortableContext+ items={sessions.map((session) => session.id)}+ strategy={horizontalListSortingStrategy}+ >+ {sessions.map((session) => {+ const isActive = session.id === activeSessionId;+ return (+ <SortableTerminalTab+ key={session.id}+ id={session.id}+ // Drag off while a rename is open (strip-wide) or when the host+ // supplies no onReorder.+ disabled={!reorderEnabled || renamingId != null}+ isActive={isActive}+ >+ {renamingId === session.id ? (+ // Rename mode: the input REPLACES the trigger inside this group+ // div (never nested inside the `role="tab"` button — that is+ // invalid interactive nesting). The close control is hidden+ // while editing so a stray click can't kill the tab mid-rename.+ <InputGroup+ className={cn(+ 'h-7 w-40 rounded-md border-0 bg-transparent dark:bg-transparent',+ draggable && '[-webkit-app-region:no-drag]',+ )}+ >+ <InputGroupInput+ ref={renameInputRef}+ value={renameValue}+ aria-label={t`Rename ${session.label}`}+ data-testid="terminal-tab-rename-input"+ className="h-7 px-2 text-xs"+ onChange={(event) => setRenameValue(event.target.value)}+ onKeyDown={(event) => {+ // Enter/Escape only blur — endRename (the blur handler)+ // is the single commit/cancel point.+ if (event.key === 'Enter') {+ event.preventDefault();+ renameInputRef.current?.blur();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ cancelRenameRef.current = true;+ renameInputRef.current?.blur();+ }+ }}+ onBlur={() => endRename(session.id)}+ />+ </InputGroup>+ ) : (+ <>+ {/* The label truncates at max-w-40, so a process-set title+ (OSC 0/2) that overflows is hard-clipped in the tab — the+ tooltip surfaces the full title on hover. */}+ <Tooltip>+ <TooltipTrigger asChild>+ <TabsTrigger+ value={session.id}+ // Anchor for focus-return after a rename ends.+ data-tab-id={session.id}+ // Pointer/Enter activation routes through onClick (arrow-key+ // navigation does not fire it), so the consumer can focus the+ // terminal on a deliberate select without stealing focus while+ // the user arrows across tabs. The second click of a+ // double-click is skipped (detail >= 2): otherwise its+ // activation would focus the terminal and blur-commit the+ // rename that same double-click is opening.+ onClick={(event) => {+ if (event.detail >= 2) return;+ onTabActivate?.(session.id);+ }}+ // Double-click (pointer) and F2 (keyboard) enter rename —+ // the same two idioms the editor file tabs use. Inert+ // when the host supplies no onRename.+ onDoubleClick={() => enterRename(session)}+ onKeyDown={(event) => {+ if (event.key === 'F2') {+ event.preventDefault();+ enterRename(session);+ }+ }}+ className={cn(+ 'h-7 flex-none rounded-md px-2 text-xs',+ draggable && '[-webkit-app-region:no-drag]',+ )}+ >+ <span className="max-w-40 truncate">{session.label}</span>+ </TabsTrigger>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={8}>+ {session.label}+ </TooltipContent>+ </Tooltip>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={t`Close ${session.label}`}+ // Match the editor-tab pattern: only the active tab's close+ // control sits in the tab order, so a keyboard user reaches a+ // tab's close after activating it rather than tabbing past every+ // inactive tab's close button.+ tabIndex={isActive ? 0 : -1}+ // Close reveals on tab hover or keyboard focus; the active tab+ // keeps it persistently visible. Opacity (not unmount) keeps the+ // control in layout + a11y tree so tabs don't reflow and the+ // keyboard target stays reachable.+ className={cn(+ 'text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100',+ isActive && 'opacity-100',+ draggable && '[-webkit-app-region:no-drag]',+ )}+ onClick={(event) => {+ event.stopPropagation();+ onClose(session.id);+ }}+ >+ <XIcon aria-hidden="true" />+ </Button>+ </>+ )}+ </SortableTerminalTab>+ );+ })}+ </SortableContext>+ </DndContext></TabsList>{/* New-chat split button hugs the last tab (outside the tablist'sscroll+fade so it is never clipped): the primary launches the defaultdiff --git a/packages/app/src/components/editor-tabs-chrome.test.ts b/packages/app/src/components/editor-tabs-chrome.test.tsindex 4e29519f9..219adc906 100644--- a/packages/app/src/components/editor-tabs-chrome.test.ts+++ b/packages/app/src/components/editor-tabs-chrome.test.ts@@ -286,17 +286,20 @@ describe('editor tab chrome helpers', () => {});test('measures reorder bounds from sortable tab nodes only', () => {- const bounds = measureTabReorderBounds(fakeRootForRects([rect(80, 40), rect(150, 60)]));+ const bounds = measureTabReorderBounds(+ fakeRootForRects([rect(80, 40), rect(150, 60)]),+ '[data-editor-tab-sortable]',+ );expect(bounds).toEqual({ left: 80, right: 210 });});test('measureTabReorderBounds returns null without a tab root', () => {- expect(measureTabReorderBounds(null)).toBeNull();+ expect(measureTabReorderBounds(null, '[data-editor-tab-sortable]')).toBeNull();});test('measureTabReorderBounds returns null when no sortable tab nodes are present', () => {- expect(measureTabReorderBounds(fakeRootForRects([]))).toBeNull();+ expect(measureTabReorderBounds(fakeRootForRects([]), '[data-editor-tab-sortable]')).toBeNull();});test('horizontal modifier clamps x to measured tab bounds and removes y movement', () => {diff --git a/packages/app/src/components/editor-tabs-chrome.ts b/packages/app/src/components/editor-tabs-chrome.tsindex 5670f305a..55ee00dfb 100644--- a/packages/app/src/components/editor-tabs-chrome.ts+++ b/packages/app/src/components/editor-tabs-chrome.ts@@ -97,8 +97,14 @@ export function getSortableTabStyle({};}-export function measureTabReorderBounds(root: HTMLElement | null): TabReorderBounds | null {- const tabNodes = root?.querySelectorAll<HTMLElement>('[data-editor-tab-sortable]') ?? [];+export function measureTabReorderBounds(+ root: HTMLElement | null,+ // Surface-neutral: each consumer passes the attribute selector marking its own+ // sortable tab nodes (editor tabs vs terminal tabs), so this geometry helper is+ // not tied to one strip.+ sortableSelector: string,+): TabReorderBounds | null {+ const tabNodes = root?.querySelectorAll<HTMLElement>(sortableSelector) ?? [];let left = Number.POSITIVE_INFINITY;let right = Number.NEGATIVE_INFINITY;diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex c60742f13..9f5d84099 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -756,6 +756,11 @@ export type OkPtyCreateResult =/** Entry of `terminal.list`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */export interface OkPtyListEntry {readonly ptyId: string;+ /** User-set custom tab name that survives a renderer reload; null when unset. */+ readonly customLabel: string | null;+ /** Sticky per-session tab number, preserved across a renderer reload; null+ * until the renderer has reported it for a just-created session. */+ readonly ordinal: number | null;}/** Result of `terminal.adopt`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */@@ -1313,6 +1318,17 @@ export interface OkDesktopBridge {list(): Promise<OkPtyListEntry[]>;/** Reload-rehydration adopt. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */adopt(ptyId: string): Promise<OkPtyAdoptResult>;+ /**+ * Persist per-session tab metadata (custom name + sticky ordinal) in main so+ * it survives a renderer reload — main outlives the reload, so a reloaded dock+ * reads it back via `list`. Fire-and-forget; omit a field to leave it unchanged.+ */+ setMeta(ptyId: string, meta: { customLabel?: string | null; ordinal?: number }): void;+ /**+ * Persist the tab display order in main (ptyIds in visual order) so a reorder+ * survives a renderer reload. Fire-and-forget.+ */+ setOrder(orderedPtyIds: readonly string[]): void;/** Per-window dock visibility. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */getDockState(): Promise<{ visible: boolean }>;onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 12f6adf91..f56307b6e 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -50,6 +50,7 @@"0LBDjY": ["\"", ["0"], "\" uninstalled — back to a draft"],"0NA4b3": ["Keep my version"],"0SBTff": ["Show terminal"],+ "0TnCvC": ["Rename ", ["0"]],"0YEbfk": ["Connect to AI tools"],"0YUS3Q": ["Subfolder under current folder"],"0_J12R": [@@ -537,6 +538,7 @@"CifUuG": ["Update available"],"Ck9XRt": ["Couldn't save the key — please try again."],"CmeH9S": ["Add property to ", ["keyName"]],+ "CoHvYd": ["Moved ", ["0"], " to position ", ["1"], " of ", ["2"]],"CvsD6Y": ["via ", ["viaTags"]],"D-Oh1s": ["How to set up ", ["0"], " (opens in browser)"],"D12vtS": ["(detached)"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex b132d0505..0f7f7820f 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -4242,6 +4242,13 @@ msgstr "Moved \"{name}\" to {0}"msgid "Moved \"{name}\" to {0} ({skipped} binary file(s) not copied)"msgstr "Moved \"{name}\" to {0} ({skipped} binary file(s) not copied)"+#. placeholder {0}: moved.label+#. placeholder {1}: moved.position+#. placeholder {2}: moved.total+#: src/components/TerminalSessionsHost.tsx+msgid "Moved {0} to position {1} of {2}"+msgstr "Moved {0} to position {1} of {2}"+#: src/components/FolderTimelineCard.tsxmsgid "moved template"msgstr "moved template"@@ -5663,6 +5670,11 @@ msgstr "Removing"msgid "Rename"msgstr "Rename"+#. placeholder {0}: session.label+#: src/components/TerminalTabStrip.tsx+msgid "Rename {0}"+msgstr "Rename {0}"+#: src/components/FrontmatterRow.tsxmsgid "Rename {keyName}"msgstr "Rename {keyName}"@@ -6867,7 +6879,7 @@ msgstr "Templates available"msgid "Terminal"msgstr "Terminal"-#. placeholder {0}: index + 1+#. placeholder {0}: session.ordinal#: src/components/TerminalSessionsHost.tsxmsgid "Terminal {0}"msgstr "Terminal {0}"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 54739ec16..539d609cb 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -50,6 +50,7 @@"0LBDjY": ["\"", ["0"], "\" ũńĩńśţàĺĺēď — ƀàćķ ţō à ďŕàƒţ"],"0NA4b3": ["Ķēēƥ ḿŷ vēŕśĩōń"],"0SBTff": ["Śĥōŵ ţēŕḿĩńàĺ"],+ "0TnCvC": ["Ŕēńàḿē ", ["0"]],"0YEbfk": ["Ćōńńēćţ ţō ÀĨ ţōōĺś"],"0YUS3Q": ["Śũƀƒōĺďēŕ ũńďēŕ ćũŕŕēńţ ƒōĺďēŕ"],"0_J12R": [@@ -537,6 +538,7 @@"CifUuG": ["Ũƥďàţē àvàĩĺàƀĺē"],"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],+ "CoHvYd": ["Ḿōvēď ", ["0"], " ţō ƥōśĩţĩōń ", ["1"], " ōƒ ", ["2"]],"CvsD6Y": ["vĩà ", ["viaTags"]],"D-Oh1s": ["Ĥōŵ ţō śēţ ũƥ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],"D12vtS": ["(ďēţàćĥēď)"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex e83517beb..c14847de9 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -4237,6 +4237,13 @@ msgstr ""msgid "Moved \"{name}\" to {0} ({skipped} binary file(s) not copied)"msgstr ""+#. placeholder {0}: moved.label+#. placeholder {1}: moved.position+#. placeholder {2}: moved.total+#: src/components/TerminalSessionsHost.tsx+msgid "Moved {0} to position {1} of {2}"+msgstr ""+#: src/components/FolderTimelineCard.tsxmsgid "moved template"msgstr ""@@ -5658,6 +5665,11 @@ msgstr ""msgid "Rename"msgstr ""+#. placeholder {0}: session.label+#: src/components/TerminalTabStrip.tsx+msgid "Rename {0}"+msgstr ""+#: src/components/FrontmatterRow.tsxmsgid "Rename {keyName}"msgstr ""@@ -6862,7 +6874,7 @@ msgstr ""msgid "Terminal"msgstr ""-#. placeholder {0}: index + 1+#. placeholder {0}: session.ordinal#: src/components/TerminalSessionsHost.tsxmsgid "Terminal {0}"msgstr ""diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex 62f574057..7b88e558f 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -577,6 +577,8 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): Pdrain: () => {},list: async () => [],adopt: async () => ({ ok: true as const, replay: '' }),+ setMeta: () => {},+ setOrder: () => {},getDockState: async () => ({ visible: false }),onData: () => () => {},onExit: () => () => {},diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 29e345677..5ecf158ed 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -861,6 +861,11 @@ export type OkPtyCreateResult =/** Entry of `terminal.list`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */export interface OkPtyListEntry {readonly ptyId: string;+ /** User-set custom tab name that survives a renderer reload; null when unset. */+ readonly customLabel: string | null;+ /** Sticky per-session tab number, preserved across a renderer reload; null+ * until the renderer has reported it for a just-created session. */+ readonly ordinal: number | null;}/** Result of `terminal.adopt`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */@@ -1556,6 +1561,17 @@ export interface OkDesktopBridge {list(): Promise<OkPtyListEntry[]>;/** Reload-rehydration adopt. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */adopt(ptyId: string): Promise<OkPtyAdoptResult>;+ /**+ * Persist per-session tab metadata (custom name + sticky ordinal) in main so+ * it survives a renderer reload — main outlives the reload, so a reloaded dock+ * reads it back via `list`. Fire-and-forget; omit a field to leave it unchanged.+ */+ setMeta(ptyId: string, meta: { customLabel?: string | null; ordinal?: number }): void;+ /**+ * Persist the tab display order in main (ptyIds in visual order) so a reorder+ * survives a renderer reload. Fire-and-forget.+ */+ setOrder(orderedPtyIds: readonly string[]): void;/** Per-window dock visibility. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */getDockState(): Promise<{ visible: boolean }>;onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 444af11a6..af994fec3 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -2812,6 +2812,23 @@ function registerIpcHandlers() {webContents: win.webContents,});});+ handle('ok:pty:set-meta', async (event, req) => {+ const win = BrowserWindow.fromWebContents(event.sender);+ if (win)+ terminalManager.setSessionMeta({+ windowId: win.id,+ ptyId: req.ptyId,+ customLabel: req.customLabel,+ ordinal: req.ordinal,+ });+ return undefined;+ });+ handle('ok:pty:set-order', async (event, req) => {+ const win = BrowserWindow.fromWebContents(event.sender);+ if (win)+ terminalManager.setSessionOrder({ windowId: win.id, orderedPtyIds: req.orderedPtyIds });+ return undefined;+ });handle('ok:terminal:claude-assist', async (event, req) => {let rewireError: string | undefined;if (req.action === 'rewire' && process.platform === 'darwin' && app.isPackaged) {diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.tsindex 30718915a..75bcfd29c 100644--- a/packages/desktop/src/main/terminal-manager.ts+++ b/packages/desktop/src/main/terminal-manager.ts@@ -151,6 +151,16 @@ interface SessionState {* command contents.*/commandRan: boolean;+ /** User-set custom tab name (renderer-owned, pushed via set-meta). Retained so+ * `listSessions` restores it after a renderer reload. Null = no custom name. */+ customLabel: string | null;+ /** Sticky per-session tab number the renderer assigns and pushes via set-meta;+ * echoed back on reload so the tab keeps its number. Null until reported. */+ ordinal: number | null;+ /** Display position, ascending. Defaults to creation order; the renderer+ * overwrites it via set-order on a drag / keyboard reorder, and `listSessions`+ * sorts by it so a reload restores the user's arrangement. */+ order: number;}interface PtyWindowHandle {@@ -210,11 +220,27 @@ export interface TerminalManager {kill(req: TerminalAddressedRequest): void;drain(req: TerminalAddressedRequest & { bytes: number }): void;/**- * Live ptyIds for a window — the reload-rehydration inventory a reloaded- * renderer queries to rediscover its surviving shells. Insertion order =- * creation order = natural tab order. Empty for a window with no host.+ * The reload-rehydration inventory a reloaded renderer queries to rediscover its+ * surviving shells. Each entry carries the ptyId plus the custom name + sticky+ * ordinal retained across the reload, returned in the persisted display order+ * (creation order until the renderer pushes a reorder). Empty for a window with+ * no host.*/listSessions(windowId: number): OkPtyListEntry[];+ /**+ * Persist per-session tab metadata (custom name, sticky ordinal) so a renderer+ * reload can restore it. A field left `undefined` is unchanged. Unknown+ * window/ptyId is a no-op (the session may have exited).+ */+ setSessionMeta(+ req: TerminalAddressedRequest & { customLabel?: string | null; ordinal?: number },+ ): void;+ /**+ * Persist the tab display order (`orderedPtyIds` in visual order) so a reorder+ * survives a renderer reload. Any live session not in the list sorts after the+ * listed ones, keeping its prior relative order.+ */+ setSessionOrder(req: { windowId: number; orderedPtyIds: readonly string[] }): void;/*** Re-bind a surviving session to a reloaded renderer's fresh webContents and* clear the backpressure the dead page stranded (so a session paused under a@@ -456,6 +482,12 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage// rendering. A soft cap is deferred until the concurrency-depth signal// below shows users actually approach that ceiling.// A new tab ADDS a session; the window's existing shells keep running.+ // Default display order = end of the current set (creation order); the+ // renderer overrides it via set-order on a reorder.+ const nextOrder =+ handle.sessions.size === 0+ ? 0+ : Math.max(...[...handle.sessions.values()].map((s) => s.order)) + 1;handle.sessions.set(ptyId, {outbound: '',replay: '',@@ -463,6 +495,9 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagependingBytes: 0,paused: false,commandRan: false,+ customLabel: null,+ ordinal: null,+ order: nextOrder,});// Record the concurrency reached by this open (1 for a solo tab, N for the// Nth concurrent tab). Concurrency only rises on create, so the per-window@@ -518,10 +553,43 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagelistSessions(windowId): OkPtyListEntry[] {const handle = handles.get(windowId);if (!handle) return [];- // Map insertion order is creation order, so the inventory matches the- // dock's original left-to-right tab order. A session that exited has- // already been deleted by `onUtilityMessage`, so it never appears here.- return [...handle.sessions.keys()].map((ptyId) => ({ ptyId }));+ // Sorted by the stored display order (creation order until the renderer+ // pushes a reorder via set-order), so a reloaded dock restores the user's+ // arrangement instead of snapping back to creation order. customLabel ++ // ordinal ride along so the reloaded tabs keep their names + sticky numbers.+ // An exited session was already deleted by `onUtilityMessage`, so it never+ // appears here.+ return [...handle.sessions.entries()]+ .sort((a, b) => a[1].order - b[1].order)+ .map(([ptyId, session]) => ({+ ptyId,+ customLabel: session.customLabel,+ ordinal: session.ordinal,+ }));+ },++ setSessionMeta(req): void {+ const session = handles.get(req.windowId)?.sessions.get(req.ptyId);+ if (!session) return;+ if (req.customLabel !== undefined) session.customLabel = req.customLabel;+ if (req.ordinal !== undefined) session.ordinal = req.ordinal;+ },++ setSessionOrder(req): void {+ const handle = handles.get(req.windowId);+ if (!handle) return;+ let i = 0;+ const listed = new Set(req.orderedPtyIds);+ for (const ptyId of req.orderedPtyIds) {+ const session = handle.sessions.get(ptyId);+ if (session) session.order = i++;+ }+ // A live session not named in the reorder (e.g. one created in the gap)+ // sorts after the listed block, keeping its prior relative order.+ const rest = [...handle.sessions.entries()]+ .filter(([ptyId]) => !listed.has(ptyId))+ .sort((a, b) => a[1].order - b[1].order);+ for (const [, session] of rest) session.order = i++;},adoptSession(req): OkPtyAdoptResult {diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex b66626dac..0666e4e8a 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -668,6 +668,13 @@ const bridge: OkDesktopBridge = {},list: () => invoke('ok:pty:list'),adopt: (ptyId) => invoke('ok:pty:adopt', { ptyId }),+ // Fire-and-forget reload-survival metadata (swallow a teardown-race rejection).+ setMeta: (ptyId, meta) => {+ invoke('ok:pty:set-meta', { ptyId, ...meta }).catch(() => {});+ },+ setOrder: (orderedPtyIds) => {+ invoke('ok:pty:set-order', { orderedPtyIds: [...orderedPtyIds] }).catch(() => {});+ },getDockState: () => invoke('ok:terminal:dock-state'),onData(cb) {const listener = (_event: IpcRendererEvent, msg: OkPtyData) => cb(msg);diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 544669e57..e2e2f1199 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -879,6 +879,11 @@ export type OkPtyCreateResult =*/export interface OkPtyListEntry {readonly ptyId: string;+ /** User-set custom tab name that survives a renderer reload; null when unset. */+ readonly customLabel: string | null;+ /** Sticky per-session tab number, preserved across a renderer reload; null+ * until the renderer has reported it for a just-created session. */+ readonly ordinal: number | null;}/**@@ -1841,6 +1846,17 @@ export interface OkDesktopBridge {* exited in the gap since `list`, so the caller spawns a fresh shell instead.*/adopt(ptyId: string): Promise<OkPtyAdoptResult>;+ /**+ * Persist per-session tab metadata (custom name + sticky ordinal) in main so+ * it survives a renderer reload — main outlives the reload, so a reloaded dock+ * reads it back via `list`. Fire-and-forget; omit a field to leave it unchanged.+ */+ setMeta(ptyId: string, meta: { customLabel?: string | null; ordinal?: number }): void;+ /**+ * Persist the tab display order in main (ptyIds in visual order) so a reorder+ * survives a renderer reload. Fire-and-forget.+ */+ setOrder(orderedPtyIds: readonly string[]): void;/*** Per-window dock visibility retained in main, read once on reload so the* dock re-expands when it was open before the reload (and stays hidden afterdiff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex edaef5af5..ee6b10a0f 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -30,7 +30,7 @@* existing channels is preferred over net-new hand-rolled channels until* that migration lands.*- * Count is 79 (ratchet cap 79). The 74→75 bump reconciled a merge collision:+ * Count is 81 (ratchet cap 81). The 74→75 bump reconciled a merge collision:* the worktree selector (`ok:worktree:dispatch`) and the terminal-controls PR* (`ok:terminal:cli-installed-map`) each landed in the base tree's single free* slot concurrently. The 75→76 bump then unioned in the desktop@@ -41,7 +41,10 @@* discriminated fold per the worktree-dispatch precedent). The 78→79 bump added* its project-scoped sibling Settings → This project → AI tools* (`ok:project-integrations:dispatch`, same status+set fold, scoped to the- * sender window's project). Full rationale in the ratchet test header.+ * sender window's project). The 79→81 bump added terminal-tab reload-survival+ * (`ok:pty:set-meta` + `ok:pty:set-order`) — two slots, following the `ok:pty:*`+ * one-channel-per-operation design rather than a dispatch fold. Full rationale in+ * the ratchet test header.*/import type {@@ -1410,6 +1413,23 @@ export interface RequestChannels {args: [req: { ptyId: string }];result: OkPtyAdoptResult;};+ /**+ * Persist per-session tab metadata (custom name + sticky ordinal) in main so it+ * survives a renderer reload (the PTY host outlives the page; `ok:pty:list`+ * reads it back). Fire-and-forget; a field omitted is left unchanged.+ */+ 'ok:pty:set-meta': {+ args: [req: { ptyId: string; customLabel?: string | null; ordinal?: number }];+ result: undefined;+ };+ /**+ * Persist the tab display order in main (ptyIds in visual order) so a drag /+ * keyboard reorder survives a renderer reload. Fire-and-forget.+ */+ 'ok:pty:set-order': {+ args: [req: { orderedPtyIds: string[] }];+ result: undefined;+ };/*** Docked-terminal Claude Code readiness + re-arm. One discriminated* channel folds the `preflight` read (is `claude` on PATH, is thediff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.tsindex cbccdb635..0fbcc9eb8 100644--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts@@ -295,8 +295,24 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');* `ok:project-integrations:*` namespace, single member. The typed-ipc* migration remains the committed end state; scoped exception with the* `ipc-channels.ts` header commitment updated in lock-step.+ *+ * Bumped from 79 to 81 for terminal-tab reload-survival (custom name + order+ * persisted in main so a ⌘R renderer reload restores them, not just the live+ * shells):+ *+ * - `ok:pty:set-meta` — per-session tab metadata (custom name + sticky+ * ordinal), a partial fire-and-forget update keyed by ptyId.+ * - `ok:pty:set-order` — the window's tab display order (ptyIds in visual+ * order), fire-and-forget.+ * Two slots, not one: the `ok:pty:*` surface is "the smallest faithful PTY+ * protocol" — one channel per operation (create/input/resize/kill/drain/+ * list/adopt), NOT the dispatch-folding precedent — and these two payloads+ * differ in shape AND cardinality (per-session partial meta vs per-window+ * full ordering). Folding them into one discriminated channel would wear a+ * single channel over two distinct operations against a namespace that+ * deliberately keeps each PTY operation on its own channel.*/-const REQUEST_CHANNEL_CAP = 79;+const REQUEST_CHANNEL_CAP = 81;/*** Extract the body of an interface block by name. Returns the substringdiff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.tsindex 03adb3cb7..437eee50a 100644--- a/packages/desktop/tests/main/terminal-manager.test.ts+++ b/packages/desktop/tests/main/terminal-manager.test.ts@@ -985,3 +985,69 @@ describe('clampPtyDimension', () => {expect(clampPtyDimension(null, DEFAULT_PTY_COLS)).toBe(DEFAULT_PTY_COLS);});});++describe('createTerminalManager — reload-survival metadata (label + order)', () => {+ test('listSessions returns creation order with null label/ordinal until set', () => {+ const h = makeManager();+ const wc = makeWebContents();+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 });+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 });+ expect(h.mgr.listSessions(1)).toEqual([+ { ptyId: 'pty-1', customLabel: null, ordinal: null },+ { ptyId: 'pty-2', customLabel: null, ordinal: null },+ ]);+ });++ test('setSessionMeta persists name + ordinal, setSessionOrder reorders, listSessions restores both', () => {+ const h = makeManager();+ const wc = makeWebContents();+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-1+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-2+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-3++ h.mgr.setSessionMeta({ windowId: 1, ptyId: 'pty-1', customLabel: 'alpha', ordinal: 1 });+ h.mgr.setSessionMeta({ windowId: 1, ptyId: 'pty-3', customLabel: 'gamma', ordinal: 3 });+ // The user drags pty-3 to the front.+ h.mgr.setSessionOrder({ windowId: 1, orderedPtyIds: ['pty-3', 'pty-1', 'pty-2'] });++ // Restored in the reordered sequence with names + sticky ordinals intact; the+ // untouched survivor keeps its null metadata (renderer falls back positionally).+ expect(h.mgr.listSessions(1)).toEqual([+ { ptyId: 'pty-3', customLabel: 'gamma', ordinal: 3 },+ { ptyId: 'pty-1', customLabel: 'alpha', ordinal: 1 },+ { ptyId: 'pty-2', customLabel: null, ordinal: null },+ ]);+ });++ test('setSessionMeta is a partial update — one field never clobbers the other', () => {+ const h = makeManager();+ const wc = makeWebContents();+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-1+ h.mgr.setSessionMeta({ windowId: 1, ptyId: 'pty-1', ordinal: 5 });+ h.mgr.setSessionMeta({ windowId: 1, ptyId: 'pty-1', customLabel: 'renamed' });+ expect(h.mgr.listSessions(1)).toEqual([{ ptyId: 'pty-1', customLabel: 'renamed', ordinal: 5 }]);+ // An empty rename clears the label (null) but leaves the ordinal intact.+ h.mgr.setSessionMeta({ windowId: 1, ptyId: 'pty-1', customLabel: null });+ expect(h.mgr.listSessions(1)).toEqual([{ ptyId: 'pty-1', customLabel: null, ordinal: 5 }]);+ });++ test('a session created after a reorder appends after the reordered block', () => {+ const h = makeManager();+ const wc = makeWebContents();+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-1+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-2+ h.mgr.setSessionOrder({ windowId: 1, orderedPtyIds: ['pty-2', 'pty-1'] });+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-3+ expect(h.mgr.listSessions(1).map((e) => e.ptyId)).toEqual(['pty-2', 'pty-1', 'pty-3']);+ });++ test('setSessionMeta / setSessionOrder on an unknown window or ptyId is a no-op', () => {+ const h = makeManager();+ const wc = makeWebContents();+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 }); // pty-1+ h.mgr.setSessionMeta({ windowId: 999, ptyId: 'pty-1', customLabel: 'x' });+ h.mgr.setSessionMeta({ windowId: 1, ptyId: 'pty-UNKNOWN', customLabel: 'x' });+ h.mgr.setSessionOrder({ windowId: 999, orderedPtyIds: ['pty-1'] });+ expect(h.mgr.listSessions(1)).toEqual([{ ptyId: 'pty-1', customLabel: null, ordinal: null }]);+ });+});diff --git a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts b/packages/desktop/tests/smoke/terminal-tabs.e2e.tsnew file mode 100644index 000000000..f21140595--- /dev/null+++ b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts@@ -0,0 +1,413 @@+/**+ * Multi-tab terminal live-Electron smoke. Drives the real+ * renderer + preload bridge + main + per-window utilityProcess hosting node-pty,+ * exercising the TAB surface the mocked dom tests cannot reach at real fidelity:+ *+ * - a second tab spawns its OWN live node-pty shell (independent sessions);+ * - closing a tab reaps only that tab's shell — the survivor stays interactive;+ * - a manual rename pins over the program's OSC 0/2 title (the running shell+ * sets a title; the user's custom name wins);+ * - keyboard reorder (⌘⇧←/→) changes tab order, keeps each session's sticky+ * number, and PRESERVES the moved tab's live shell + scrollback — the+ * regression that shipped ("reorder resets my terminal"): reordering moved+ * the panel's xterm container in the DOM, disrupting the running program.+ *+ * These seams are real-PTY + real-xterm: the dom tests mock TerminalGate, so a+ * shell that never spawns (the #2472 node-pty-bundling class) or an xterm that+ * resets on a DOM move is invisible below this rung. The dom tests pin the+ * deterministic half (TerminalDock.dom.test.tsx: panels stay in ordinal order on+ * reorder); this pins the live-session outcome.+ *+ * Skip gates mirror the sibling terminal smokes: opt-in via OK_DESKTOP_E2E_SMOKE=1,+ * darwin-only, the electron-vite build must exist (out/main/index.js), and+ * CI-quarantined (the live-Electron terminal surface degrades on the constrained+ * runner — allowlisted in the CI no-skip guard, not hidden). Runs in local dev /+ * the release gate. Not part of `bun run check`.+ */++import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { ElectronApplication, Page } from '@playwright/test';+import { _electron as electron } from '@playwright/test';+import { expect, test } from './_helpers/smoke-test';++const __dirname = dirname(fileURLToPath(import.meta.url));+const MAIN_ENTRY = resolve(__dirname, '..', '..', 'out', 'main', 'index.js');++const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';+const DARWIN = process.platform === 'darwin';+const BUILD_EXISTS = existsSync(MAIN_ENTRY);+const IS_CI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';+const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';++interface Seed {+ tmpHome: string;+ userDataDir: string;+ projectDir: string;+}++function seed(prefix: string): Seed {+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), `ok-tabs-${prefix}-home-`)));+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), `ok-tabs-${prefix}-proj-`)));+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");+ // Pre-grant terminal consent so the shell spawns without the enable gate.+ writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');++ const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ mkdirSync(userDataDir, { recursive: true });+ writeFileSync(+ join(userDataDir, 'state.json'),+ JSON.stringify({+ recentProjects: [+ { path: projectDir, name: 'Terminal Tabs Smoke', lastOpenedAt: new Date().toISOString() },+ ],+ lastOpenedProject: projectDir,+ versionPendingInstall: null,+ lastSeenVersion: null,+ lastSuccessfulCheckAt: null,+ stuckHintShown: false,+ }),+ );+ return { tmpHome, userDataDir, projectDir };+}++async function launchApp(s: Seed): Promise<ElectronApplication> {+ const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;+ // Restricted, system-only PATH: the New-chat carat opens a BARE shell (the+ // "Terminal" pick) so no `claude` install is needed to spawn a live PTY.+ const PATH = '/usr/bin:/bin:/usr/sbin:/sbin';+ return electron.launch({+ args: [MAIN_ENTRY, `--user-data-dir=${s.userDataDir}`, deepLink],+ timeout: 30_000,+ env: {+ ...process.env,+ HOME: s.tmpHome,+ PATH,+ OK_DESKTOP_E2E_SMOKE: '1',+ OK_RECLAIM_DISABLE: '1',+ },+ });+}++async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Promise<Page> {+ let page: Page | undefined;+ await expect(async () => {+ for (const p of app.windows()) {+ const mode = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);+ if (mode === 'editor') {+ page = p;+ return;+ }+ }+ throw new Error('no editor window yet');+ }).toPass({ timeout: timeoutMs });+ if (!page) throw new Error('editor window vanished after readiness poll');+ return page;+}++async function clickViewTerminalItem(app: ElectronApplication): Promise<void> {+ await app.evaluate(async ({ Menu }) => {+ const view = Menu.getApplicationMenu()?.items.find((i) => i.label === 'View');+ const item = view?.submenu?.items.find(+ (i) => i.label === 'Show Terminal' || i.label === 'Hide Terminal',+ );+ item?.click();+ });+}++// The active tab's panel is the only VISIBLE one — inactive panels are+// data-[state=inactive]:hidden (display:none) — so `:visible` targets the active+// session's <section> (and the status/xterm nested inside it) without assuming+// tab order. Scoping the status query WITHIN the visible section is what keeps it+// unambiguous once a second tab exists (each session mounts its own section ++// status via forceMount).+const visibleSection = (page: Page) => page.locator('section[aria-label="Terminal"]:visible');+// Scope to the terminal strip's own tablist — the editor sidebar also renders+// role="tab" (Outline / Links / Graph / Timeline), so an unscoped query is+// ambiguous.+const terminalTabs = (page: Page) =>+ page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');++/**+ * Open the dock and wait for the first session's shell to be running. The live+ * shell occasionally exits before reaching "running" on constrained hardware+ * (the documented terminal-smoke degradation) — retry the View toggle until a+ * running shell settles rather than fail on a transient exit.+ */+async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {+ await expect(async () => {+ await clickViewTerminalItem(app);+ await expect(visibleSection(page)).toBeVisible({ timeout: 8_000 });+ await expect(visibleSection(page).locator('[data-terminal-status]')).toHaveAttribute(+ 'data-terminal-status',+ 'running',+ { timeout: 8_000 },+ );+ }).toPass({ timeout: 40_000, intervals: [2_000] });+}++async function waitActiveRunning(page: Page, timeoutMs = 25_000): Promise<void> {+ await expect(visibleSection(page)).toBeVisible({ timeout: 15_000 });+ await expect(visibleSection(page).locator('[data-terminal-status]')).toHaveAttribute(+ 'data-terminal-status',+ 'running',+ { timeout: timeoutMs },+ );+}++/** Open a second (or further) tab running a BARE shell via the New-chat carat →+ * "Terminal" pick. The new tab activates; wait for its shell to be running. */+async function openBareTab(page: Page): Promise<void> {+ await page.getByRole('button', { name: 'Choose CLI for new chat' }).click();+ await page.getByRole('menuitem', { name: 'Terminal' }).click();+ await waitActiveRunning(page);+}++async function activateTab(page: Page, name: string): Promise<void> {+ await page.getByRole('tab', { name }).click();+ await expect(page.getByRole('tab', { name })).toHaveAttribute('aria-selected', 'true');+}++/**+ * Pointer-drag one tab onto another and drop. Mirrors the real dnd-kit gesture:+ * press on the source, exceed the PointerSensor's 8px activation distance, drag+ * over the target in steps, then release. Used to exercise the pointer path+ * (the keyboard chord is covered separately).+ */+async function dragTabOnto(page: Page, fromName: string, toName: string): Promise<void> {+ const from = await page.getByRole('tab', { name: fromName }).boundingBox();+ const to = await page.getByRole('tab', { name: toName }).boundingBox();+ if (!from || !to) throw new Error(`tab bounding box missing (${fromName} → ${toName})`);+ await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);+ await page.mouse.down();+ // Cross the 8px activation threshold before moving to the target so the drag+ // actually lifts (a sub-8px move stays a click).+ await page.mouse.move(from.x + from.width / 2 + 14, from.y + from.height / 2, { steps: 4 });+ await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 12 });+ await page.mouse.up();+}++/** Type into the ACTIVE tab's xterm (its hidden helper textarea receives keys). */+async function typeInActive(page: Page, text: string): Promise<void> {+ await visibleSection(page).locator('.xterm').click();+ await page.keyboard.type(text);+}++/** Read the ACTIVE tab's rendered terminal text (a11y live region + rows). */+async function readActiveText(page: Page): Promise<string> {+ return visibleSection(page).evaluate((sec) => {+ const a11y = sec.querySelector('.xterm-accessibility')?.textContent ?? '';+ const rows = sec.querySelector('.xterm-rows')?.textContent ?? '';+ return `${a11y}\n${rows}`;+ });+}++const cleanup: string[] = [];+function track(...paths: string[]): void {+ cleanup.push(...paths);+}++test.describe('Terminal tabs — live Electron', () => {+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ test.skip(!DARWIN, 'Desktop is darwin-only.');+ test.skip(!BUILD_EXISTS, `Main build missing at ${MAIN_ENTRY} — run "bun run build:desktop".`);+ test.skip(+ IS_CI,+ 'Quarantined on CI: the live-Electron terminal surface degrades on the constrained runner — see inkeep/agents-private#2187.',+ );++ test.afterEach(() => {+ for (const target of cleanup.splice(0)) {+ try {+ rmSync(target, { recursive: true, force: true });+ } catch {+ // best-effort+ }+ }+ });++ test('a second tab spawns its own live shell (independent sessions)', async ({+ captureStderrFor,+ }) => {+ const s = seed('two-shells');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);++ // Tab 1: write a marker into its shell.+ await typeInActive(page, 'echo TAB1_ONLY_AAA\r');+ await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('TAB1_ONLY_AAA');++ // Open a second bare tab — it gets its own PTY and becomes active.+ await openBareTab(page);+ await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);++ // Tab 2 is a distinct shell: it has never seen tab 1's marker, and its own+ // marker is independent.+ await typeInActive(page, 'echo TAB2_ONLY_BBB\r');+ await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('TAB2_ONLY_BBB');+ expect(await readActiveText(page)).not.toContain('TAB1_ONLY_AAA');+ });++ test('closing a tab reaps only that shell; the survivor stays interactive', async ({+ captureStderrFor,+ }) => {+ const s = seed('close-one');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);+ await openBareTab(page); // Terminal 1 + Terminal 2++ // Close Terminal 1; Terminal 2 remains and its shell is still live.+ await page.getByRole('button', { name: 'Close Terminal 1' }).click();+ await expect(terminalTabs(page)).toHaveText(['Terminal 2']);+ await waitActiveRunning(page);+ await typeInActive(page, 'echo SURVIVOR_CCC\r');+ await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('SURVIVOR_CCC');+ });++ test('a manual rename pins over the program’s OSC title', async ({ captureStderrFor }) => {+ const s = seed('rename-pin');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);++ // Double-click the tab to rename it, commit with Enter.+ await page.getByRole('tab', { name: 'Terminal 1' }).dblclick();+ const input = page.getByRole('textbox', { name: /^Rename/ });+ await input.fill('my build');+ await input.press('Enter');+ await expect(page.getByRole('tab', { name: 'my build' })).toBeVisible({ timeout: 5_000 });++ // The running shell now sets an OSC 0/2 title. With a custom label pinned,+ // the visible tab name must NOT change to the program title. Emit the OSC+ // title and a scrollback marker in one write: xterm parses the byte stream+ // in order, so once the marker is on screen the OSC title has definitely+ // been fed through xterm → onTitleChange. Waiting on that marker (instead of+ // a fixed sleep) is what keeps the pin assertion from passing vacuously — if+ // the OSC were slow, the challenge simply hasn't landed yet and we keep+ // polling rather than asserting into an empty window.+ await typeInActive(page, "printf '\\033]0;PROGRAM_TITLE_ZZZ\\007'; echo OSC_FED_QQQ\r");+ await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('OSC_FED_QQQ');+ await expect(terminalTabs(page)).toHaveText(['my build']);+ await expect(page.getByRole('tab', { name: 'PROGRAM_TITLE_ZZZ' })).toHaveCount(0);+ });++ test('keyboard reorder changes order, keeps sticky numbers, and preserves the live shell', async ({+ captureStderrFor,+ }) => {+ const s = seed('reorder-survive');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);++ // Terminal 1: pin the live shell with an env marker (survives only in THIS+ // PTY process) and print a scrollback marker (survives only if the xterm is+ // not reset/cleared by the reorder).+ await typeInActive(page, 'export OK_TABMARK=SURVIVED_888\r');+ await typeInActive(page, 'echo BEFORE_REORDER_DDD\r');+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain('BEFORE_REORDER_DDD');++ // Open a second tab, then re-activate Terminal 1 and focus its shell.+ await openBareTab(page);+ await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);+ await activateTab(page, 'Terminal 1');+ await visibleSection(page).locator('.xterm').click();++ // ⌘⇧→ moves the active tab (Terminal 1) one slot right.+ await page.keyboard.press('Meta+Shift+ArrowRight');++ // Order changed; the sticky numbers rode with their sessions (NOT renumbered+ // by position).+ await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);++ // Terminal 1 is still the active tab and STILL THE SAME LIVE SHELL: the env+ // marker (same PTY) and the pre-reorder scrollback both survive. On the+ // pre-fix code the panel's xterm moved in the DOM and the running program+ // reset — here it is untouched.+ await expect(page.getByRole('tab', { name: 'Terminal 1' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+ expect(await readActiveText(page)).toContain('BEFORE_REORDER_DDD');+ await typeInActive(page, 'echo "mk=[$OK_TABMARK]"\r');+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain('mk=[SURVIVED_888]');+ });++ test('pointer-drag reorder changes order and preserves the live shell', async ({+ captureStderrFor,+ }) => {+ const s = seed('drag-survive');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);++ // Terminal 1: pin its live shell with an env marker + a scrollback marker.+ await typeInActive(page, 'export OK_DRAGMARK=DRAG_SURVIVED_444\r');+ await typeInActive(page, 'echo BEFORE_DRAG_EEE\r');+ await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('BEFORE_DRAG_EEE');++ // Open a second tab, then DRAG Terminal 1 onto Terminal 2 with the pointer.+ await openBareTab(page);+ await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);+ await dragTabOnto(page, 'Terminal 1', 'Terminal 2');++ // Order changed via the real drag; sticky numbers rode with their sessions.+ await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);++ // Terminal 1's shell is the SAME live session (env marker) with intact+ // scrollback (the pre-drag echo) — a pointer drag must not reset it either.+ await activateTab(page, 'Terminal 1');+ await visibleSection(page).locator('.xterm').click();+ expect(await readActiveText(page)).toContain('BEFORE_DRAG_EEE');+ await typeInActive(page, 'echo "dm=[$OK_DRAGMARK]"\r');+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain('dm=[DRAG_SURVIVED_444]');+ });++ test('a renderer reload preserves custom names and tab order', async ({ captureStderrFor }) => {+ const s = seed('reload-preserve');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);++ // Two tabs: rename Terminal 1 -> "build", then reorder so Terminal 2 leads.+ await openBareTab(page);+ await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);+ await page.getByRole('tab', { name: 'Terminal 1' }).dblclick();+ const input = page.getByRole('textbox', { name: /^Rename/ });+ await input.fill('build');+ await input.press('Enter');+ await expect(terminalTabs(page)).toHaveText(['build', 'Terminal 2']);+ await dragTabOnto(page, 'build', 'Terminal 2');+ await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'build']);++ // Reload the renderer (⌘R). Main + the per-window PTY host — and the tab name+ // + order they now retain — survive the reload; the reloaded dock rehydrates+ // from main rather than resetting to positional creation order (the bug fixed).+ await page.reload();+ await expect(visibleSection(page)).toBeVisible({ timeout: 20_000 });+ await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'build'], { timeout: 25_000 });+ });+});