Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): movable terminal dock — bottom or right (#2302)
serafin-garcia3d989305a114
diff --git a/.changeset/terminal-dock-right-default.md b/.changeset/terminal-dock-right-default.mdnew file mode 100644index 000000000..03602d75e--- /dev/null+++ b/.changeset/terminal-dock-right-default.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++The docked terminal now opens as a right-side column by default, sitting to the right of the document panel (editor, then document panel, then terminal). A dock button in the terminal's tab strip moves it between the right column and the bottom dock, and a collapse button hides it while keeping the running sessions alive. Your chosen dock position is remembered across sessions. Moving the terminal by dragging has been replaced by these buttons.diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsxindex 62a7ef1d7..bb9d1e959 100644--- a/packages/app/src/components/EditorArea.dom.test.tsx+++ b/packages/app/src/components/EditorArea.dom.test.tsx@@ -225,7 +225,7 @@ describe('EditorArea empty-state terminal host', () => {terminalBridge={{} as never}terminalVisibleonTerminalVisibleChange={() => {}}- terminalLaunch={null}+ terminalDock="bottom"/>,);@@ -236,6 +236,27 @@ describe('EditorArea empty-state terminal host', () => {expect(emptyState?.getAttribute('data-terminal-visible')).toBe('true');});+ test('keeps the empty-state mascot full-size when the terminal is right-docked', () => {+ render(+ <EditorArea+ editorMode="wysiwyg"+ onModeChange={() => {}}+ activeTab="timeline"+ onActiveTabChange={() => {}}+ terminalBridge={{} as never}+ terminalVisible+ onTerminalVisibleChange={() => {}}+ terminalDock="right"+ />,+ );++ const dock = screen.getByTestId('terminal-dock');+ expect(dock.getAttribute('data-visible')).toBe('true');+ const emptyState = dock.querySelector('[data-testid="empty-editor-state"]');+ expect(emptyState).not.toBeNull();+ expect(emptyState?.getAttribute('data-terminal-visible')).toBe('false');+ });+test('renders the empty state with no terminal dock on the web host (no bridge)', () => {render(<EditorArea@@ -267,7 +288,6 @@ describe('EditorArea folder-view terminal host', () => {terminalBridge={{} as never}terminalVisibleonTerminalVisibleChange={() => {}}- terminalLaunch={null}/>,);@@ -300,7 +320,6 @@ describe('EditorArea large-file-view terminal host', () => {terminalBridge={{} as never}terminalVisibleonTerminalVisibleChange={() => {}}- terminalLaunch={null}/>,);@@ -333,7 +352,6 @@ describe('EditorArea asset-view terminal host', () => {terminalBridge={{} as never}terminalVisibleonTerminalVisibleChange={() => {}}- terminalLaunch={null}/>,);@@ -366,7 +384,6 @@ describe('EditorArea terminal persists across view-kind switches', () => {terminalBridge: {} as never,terminalVisible: true,onTerminalVisibleChange: () => {},- terminalLaunch: null,};const { rerender } = render(<EditorArea {...props} />);const mountsAfterInitial = terminalDockMounts;@@ -411,7 +428,6 @@ describe('EditorArea hash-load skeleton renders outside the panel group (cold stterminalBridge={{} as never}terminalVisibleonTerminalVisibleChange={() => {}}- terminalLaunch={null}/>,);@@ -441,7 +457,6 @@ describe('EditorArea terminal persists across a mid-session cold navigation', ()terminalBridge: {} as never,terminalVisible: true,onTerminalVisibleChange: () => {},- terminalLaunch: null,};const { rerender } = render(<EditorArea {...props} />);const mountsAfterInitial = terminalDockMounts;diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsxindex 764179907..4ba6a4fb5 100644--- a/packages/app/src/components/EditorArea.tsx+++ b/packages/app/src/components/EditorArea.tsx@@ -1,5 +1,6 @@import { detectEmbeddedHostFromBrowser } from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';+import { useTheme } from 'next-themes';import {lazy,type ReactNode,@@ -40,6 +41,13 @@ import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';import { ProfilerBoundary } from '@/lib/perf';import { RIGHT_COLLAPSE_THRESHOLD, resolvePartition } from '@/lib/sidebar-partition';import { applyToggle, readPins, resolveEffectiveState } from '@/lib/sidebar-pin-store';+import type { TerminalDockPosition } from '@/lib/terminal-dock-store';+import {+ getInitialTerminalWidth,+ MAX_TERMINAL_WIDTH,+ MIN_TERMINAL_WIDTH,+ writeTerminalWidth,+} from '@/lib/terminal-width-store';import { useSettingsRoute } from '@/lib/use-settings-route';import { cn } from '@/lib/utils';import { useSyncStatus } from '@/presence/use-sync-status';@@ -47,10 +55,11 @@ import { BottomComposer } from './BottomComposer';import { shouldShowBottomComposer, shouldShowFolderComposer } from './bottom-composer-gate';import { EditorActivityPool } from './EditorActivityPool';import { EditorFooter } from './EditorFooter';-import type { EditorMode, TerminalLaunchIntent } from './EditorPane';+import type { EditorMode } from './EditorPane';import { EditorToolbar } from './EditorToolbar';import { shouldPaintOverlay } from './editor-area-overlay';import { TerminalDock } from './TerminalDock';+import { xtermThemeForMode } from './terminal-theme';const LazyActivityModeContent = lazy(async () => {const mod = await import('@/components/ActivityModeContent');@@ -60,6 +69,13 @@ const LazyActivityModeContent = lazy(async () => {const DOC_PANEL_MIN_SIZE = '300px';const DOC_PANEL_MAX_SIZE = '600px';+export interface TerminalPlacement {+ readonly container: HTMLElement | null;+ readonly isShowing: boolean;+ readonly dockPosition: TerminalDockPosition;+ readonly editorRegion: HTMLElement | null;+}+interface EditorAreaProps {editorMode: EditorMode;onModeChange: (mode: EditorMode) => void;@@ -68,9 +84,13 @@ interface EditorAreaProps {terminalBridge?: OkDesktopBridge | null;terminalVisible?: boolean;onTerminalVisibleChange?: (visible: boolean) => void;- /** "Open in terminal" launch intent — carried to the terminal session, which- * writes the `claude` launch once per nonce. Null until a UI click. */- terminalLaunch?: TerminalLaunchIntent | null;+ /** Terminal dock position (right default | bottom). When `'right'` the terminal+ * is its own column to the right of the doc/agent panel (MD | PANE | TERMINAL)+ * instead of docking under the editor. */+ terminalDock?: TerminalDockPosition;+ /** Report the terminal's attach point up to EditorPane (which owns the session+ * host). See {@link TerminalPlacement}. */+ onTerminalPlacement?: (placement: TerminalPlacement) => void;}export function EditorArea(props: EditorAreaProps) {@@ -110,9 +130,12 @@ function EditorAreaInner({terminalBridge,terminalVisible = false,onTerminalVisibleChange,- terminalLaunch = null,+ terminalDock = 'right',+ onTerminalPlacement,}: EditorAreaProps) {const { t } = useLingui();+ const { resolvedTheme } = useTheme();+ const xtermBackground = xtermThemeForMode(resolvedTheme).background;const {activeDocName,activeProvider,@@ -153,12 +176,43 @@ function EditorAreaInner({rightPartitionRef.current = rightPartition;}, [rightPartition]);const panelRef = usePanelRef();+ const terminalColumnPanelRef = usePanelRef();const [initialRightCollapsed] = useState(() => {const pins = readPins();return resolveEffectiveState('right', rightPartition, pins) === 'collapsed';});const [isCollapsed, setIsCollapsed] = useState(initialRightCollapsed);const isCollapsedRef = useRef(isCollapsed);++ const [rightTerminalContainer, setRightTerminalContainer] = useState<HTMLDivElement | null>(null);+ const [bottomTerminalContainer, setBottomTerminalContainer] = useState<HTMLDivElement | null>(+ null,+ );+ const [terminalEditorRegion, setTerminalEditorRegion] = useState<HTMLDivElement | null>(null);++ const rightDocked = terminalDock === 'right';+ const terminalDockPosition: TerminalDockPosition = rightDocked ? 'right' : 'bottom';+ const rightTerminalShowing = rightDocked && terminalVisible && rightTerminalContainer != null;+ const activeTerminalContainer = rightTerminalShowing+ ? rightTerminalContainer+ : bottomTerminalContainer;+ const terminalShowing =+ (rightDocked ? rightTerminalShowing : terminalVisible) && activeTerminalContainer != null;+ useEffect(() => {+ onTerminalPlacement?.({+ container: activeTerminalContainer,+ isShowing: terminalShowing,+ dockPosition: terminalDockPosition,+ editorRegion: terminalEditorRegion,+ });+ }, [+ onTerminalPlacement,+ activeTerminalContainer,+ terminalShowing,+ terminalDockPosition,+ terminalEditorRegion,+ ]);+useEffect(() => {isCollapsedRef.current = isCollapsed;}, [isCollapsed]);@@ -175,9 +229,24 @@ function EditorAreaInner({writeTimerRef.current = null;}, 100);}++ const [initialTerminalWidthPx] = useState(() => getInitialTerminalWidth());+ const terminalWidthPxRef = useRef(initialTerminalWidthPx);+ const [isDraggingTerminalHandle, setIsDraggingTerminalHandle] = useState(false);+ const isDraggingTerminalHandleRef = useRef(false);+ const terminalWriteTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ function debouncedWriteTerminalWidth(px: number) {+ if (terminalWriteTimerRef.current != null) clearTimeout(terminalWriteTimerRef.current);+ terminalWriteTimerRef.current = setTimeout(() => {+ writeTerminalWidth(px);+ terminalWriteTimerRef.current = null;+ }, 100);+ }+useEffect(() => () => {if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);+ if (terminalWriteTimerRef.current != null) clearTimeout(terminalWriteTimerRef.current);},[],);@@ -219,13 +288,16 @@ function EditorAreaInner({if (groupContainerEl == null) return;if (isEmbedded) return;const ro = new ResizeObserver(() => {- if (isCollapsedRef.current) return;- if (isDraggingDocHandleRef.current) return;- panelRef.current?.resize(`${docPanelWidthPxRef.current}px`);+ if (!isDraggingDocHandleRef.current && !isCollapsedRef.current) {+ panelRef.current?.resize(`${docPanelWidthPxRef.current}px`);+ }+ if (!isDraggingTerminalHandleRef.current) {+ terminalColumnPanelRef.current?.resize(`${terminalWidthPxRef.current}px`);+ }});ro.observe(groupContainerEl);return () => ro.disconnect();- }, [groupContainerEl, isEmbedded, panelRef]);+ }, [groupContainerEl, isEmbedded, panelRef, terminalColumnPanelRef]);useEffect(() => {const openRequestedTab = (tab: PanelTab) => {@@ -419,7 +491,9 @@ function EditorAreaInner({return <EditorSkeleton />;}} else {- viewContent = <EmptyEditorState terminalVisible={terminalVisible} />;+ viewContent = (+ <EmptyEditorState terminalVisible={terminalVisible && terminalDockPosition === 'bottom'} />+ );}} else {const isSourceMode = editorMode === 'source';@@ -606,10 +680,11 @@ function EditorAreaInner({const leftColumn =terminalBridge != null ? (<TerminalDock- bridge={terminalBridge}visible={terminalVisible}onVisibleChange={onTerminalVisibleChange ?? (() => {})}- launch={terminalLaunch}+ dockPosition={terminalDockPosition}+ onBottomContainer={setBottomTerminalContainer}+ onEditorRegion={setTerminalEditorRegion}>{viewContent}</TerminalDock>@@ -617,24 +692,71 @@ function EditorAreaInner({viewContent);+ const terminalColumnPresent = terminalBridge != null && rightDocked && terminalVisible;+ const terminalColumn = terminalColumnPresent ? (+ <>+ <ResizableHandle+ withHandle+ onPointerDown={() => {+ setIsDraggingTerminalHandle(true);+ isDraggingTerminalHandleRef.current = true;+ const handleUp = () => {+ setIsDraggingTerminalHandle(false);+ isDraggingTerminalHandleRef.current = false;+ window.removeEventListener('pointerup', handleUp);+ };+ window.addEventListener('pointerup', handleUp);+ }}+ />+ <ResizablePanel+ id="terminal-column"+ panelRef={terminalColumnPanelRef}+ style={{ backgroundColor: xtermBackground }}+ defaultSize={`${initialTerminalWidthPx}px`}+ minSize={`${MIN_TERMINAL_WIDTH}px`}+ maxSize={`${MAX_TERMINAL_WIDTH}px`}+ onResize={(size) => {+ if (size.inPixels > 0 && isDraggingTerminalHandleRef.current) {+ terminalWidthPxRef.current = size.inPixels;+ debouncedWriteTerminalWidth(size.inPixels);+ }+ }}+ className={cn(+ 'flex flex-col',+ !isDraggingTerminalHandle &&+ 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0',+ )}+ >+ {/* Mount point for the session host's stable host div when right-docked. */}+ <div+ ref={setRightTerminalContainer}+ className="flex min-h-0 flex-1 flex-col overflow-hidden"+ />+ </ResizablePanel>+ </>+ ) : null;++ const editorAbsorbsResidual =+ (rightPanel != null && !initialRightCollapsed) || terminalColumnPresent;+return (<div className="flex min-h-0 flex-1" ref={setGroupContainerEl}><ResizablePanelGrouporientation="horizontal"- data-dragging={isDraggingDocHandle || undefined}+ data-dragging={isDraggingDocHandle || isDraggingTerminalHandle || undefined}><ResizablePanelminSize="30%"- {...(rightPanel != null && !initialRightCollapsed ? {} : { defaultSize: '100%' })}- className={- isDraggingDocHandle- ? undefined- : 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0'- }+ {...(editorAbsorbsResidual ? {} : { defaultSize: '100%' })}+ className={cn(+ !(isDraggingDocHandle || isDraggingTerminalHandle) &&+ 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0',+ )}>{leftColumn}</ResizablePanel>{rightPanel}+ {terminalColumn}</ResizablePanelGroup></div>);diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex c64b69596..f6062ddb3 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -51,24 +51,21 @@ mock.module('./EditorHeader', () => ({}));mock.module('./EditorArea', () => ({- EditorArea: ({- terminalBridge,- terminalVisible,- terminalLaunch,+ EditorArea: () => <div data-testid="editor-area" />,+}));+mock.module('./TerminalSessionsHost', () => ({+ TerminalSessionsHost: ({+ visible,+ launch,}: {- terminalBridge?: unknown;- terminalVisible?: boolean;- terminalLaunch?: { nonce: number } | null;+ visible?: boolean;+ launch?: { nonce: number } | null;}) => (- <div data-testid="editor-area">- {terminalBridge != null ? (- <div- data-testid="terminal-dock"- data-visible={String(terminalVisible)}- data-launch-nonce={terminalLaunch ? String(terminalLaunch.nonce) : 'none'}- />- ) : null}- </div>+ <div+ data-testid="terminal-dock"+ data-visible={String(visible)}+ data-launch-nonce={launch ? String(launch.nonce) : 'none'}+ />),}));@@ -277,8 +274,8 @@ describe('EditorPane terminal dock wiring', () => {await renderEditorPane();expect(screen.getByTestId('editor-header')).toBeTruthy();- const area = screen.getByTestId('editor-area');- expect(area.querySelector('[data-testid="terminal-dock"]')).not.toBeNull();+ expect(screen.getByTestId('editor-area')).toBeTruthy();+ expect(screen.queryByTestId('terminal-dock')).not.toBeNull();});test('desktop: toggle-terminal menu action flips dock visibility and pushes the view-menu state', async () => {diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex e2a3d8f94..c4ab62483 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -9,14 +9,20 @@ import { useGitSyncStatus } from '@/hooks/use-git-sync-status';import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';import { useConfigContext } from '@/lib/config-provider';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';+import {+ getInitialTerminalDock,+ type TerminalDockPosition,+ writeTerminalDock,+} from '@/lib/terminal-dock-store';import { recordTerminalOpened } from '@/lib/terminal-telemetry';import { AuthModal } from './AuthModal';import { AutoSyncOnboardingDialog } from './AutoSyncOnboardingDialog';import { shouldShowAutoSyncOnboarding } from './auto-sync-onboarding-gate';import { type PanelTab, TABS } from './DocPanel';-import { EditorArea } from './EditorArea';+import { EditorArea, type TerminalPlacement } from './EditorArea';import { EditorHeader } from './EditorHeader';import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';+import { TerminalSessionsHost } from './TerminalSessionsHost';export interface TerminalLaunchIntent {readonly prompt: string;@@ -42,6 +48,22 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {const [dockRestoreSettled, setDockRestoreSettled] = useState(false);const restoreRevealRef = useRef(false);const [terminalLaunch, setTerminalLaunch] = useState<TerminalLaunchIntent | null>(null);+ const [terminalDock, setTerminalDockState] =+ useState<TerminalDockPosition>(getInitialTerminalDock);+ function setTerminalDock(next: TerminalDockPosition) {+ setTerminalDockState(next);+ writeTerminalDock(next);+ setTerminalVisible(true);+ }+ function toggleTerminalDock() {+ setTerminalDock(terminalDock === 'right' ? 'bottom' : 'right');+ }+ const [terminalPlacement, setTerminalPlacement] = useState<TerminalPlacement>({+ container: null,+ isShowing: false,+ dockPosition: 'bottom',+ editorRegion: null,+ });const launchNonceRef = useRef(0);const syncStatus = useGitSyncStatus();@@ -169,10 +191,11 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {}}onOpenSearch={onOpenSearch}/>- {/* The terminal docks under the editor/file column only — EditorArea- nests the vertical split inside its horizontal editor↔doc-panel- split so the doc panel stays full-height beside the terminal. The- ⌘J/menu/telemetry state stays owned here and is threaded down. */}+ {/* The terminal docks to the right of the doc panel (its own column) or+ under the editor/file column. EditorArea owns the layout; the dock+ position, visibility, and the dock-toggle/collapse controls' state stay+ owned here and are threaded down — to EditorArea (placement) and to the+ session host (which renders the tab strip's controls via its portal). */}<EditorAreaeditorMode={editorMode}onModeChange={handleModeChange}@@ -181,8 +204,22 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {terminalBridge={desktopBridge}terminalVisible={terminalVisible}onTerminalVisibleChange={setTerminalVisible}- terminalLaunch={terminalLaunch}+ terminalDock={terminalDock}+ onTerminalPlacement={setTerminalPlacement}/>+ {desktopBridge != null ? (+ <TerminalSessionsHost+ bridge={desktopBridge}+ visible={terminalVisible}+ onVisibleChange={setTerminalVisible}+ launch={terminalLaunch}+ container={terminalPlacement.container}+ isShowing={terminalPlacement.isShowing}+ onRequestEditorFocus={() => terminalPlacement.editorRegion?.focus()}+ dockPosition={terminalDock}+ onToggleDock={toggleTerminalDock}+ />+ ) : null}<AuthModalopen={authModalOpen}onOpenChange={setAuthModalOpen}diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsxindex 9d26e050a..7e40dad68 100644--- a/packages/app/src/components/TerminalDock.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.dom.test.tsx@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { useEffect, useRef } from 'react';+import { useEffect, useRef, useState } from 'react';import { TooltipProvider } from '@/components/ui/tooltip';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';@@ -104,6 +104,7 @@ mock.module('@/lib/terminal-height-store', () => ({}));const { TerminalDock } = await import('./TerminalDock');+const { TerminalSessionsHost } = await import('./TerminalSessionsHost');function makeBridge() {const menuHandlers: Array<(action: string) => void> = [];@@ -140,21 +141,42 @@ function makeBridge() {};}-function renderDock(visible: boolean, launch?: { prompt: string; nonce: number } | null) {- const onVisibleChange = mock((_v: boolean) => {});- const { bridge, create, kill, viewMenuPushes, dispatchMenuAction } = makeBridge();- const ui = (v: boolean, l?: { prompt: string; nonce: number } | null) => (+// biome-ignore lint/suspicious/noExplicitAny: test harness props+function DockHarness({ v, l, onVisibleChange, bridge }: any) {+ const [bottomContainer, setBottomContainer] = useState<HTMLDivElement | null>(null);+ const [editorRegionEl, setEditorRegionEl] = useState<HTMLDivElement | null>(null);+ return (<TooltipProvider><TerminalDock- bridge={bridge}visible={v}onVisibleChange={onVisibleChange}- launch={l ?? null}+ dockPosition="bottom"+ onBottomContainer={setBottomContainer}+ onEditorRegion={setEditorRegionEl}><div data-testid="editor-child" /></TerminalDock>+ <TerminalSessionsHost+ bridge={bridge}+ visible={v}+ onVisibleChange={onVisibleChange}+ launch={l ?? null}+ container={bottomContainer}+ isShowing={v && bottomContainer != null}+ onRequestEditorFocus={() => editorRegionEl?.focus()}+ dockPosition="bottom"+ onToggleDock={() => {}}+ /></TooltipProvider>);+}++function renderDock(visible: boolean, launch?: { prompt: string; nonce: number } | null) {+ const onVisibleChange = mock((_v: boolean) => {});+ const { bridge, create, kill, viewMenuPushes, dispatchMenuAction } = makeBridge();+ const ui = (v: boolean, l?: { prompt: string; nonce: number } | null) => (+ <DockHarness v={v} l={l ?? null} onVisibleChange={onVisibleChange} bridge={bridge} />+ );const utils = render(ui(visible, launch));return {...utils,@@ -207,6 +229,13 @@ describe('TerminalDock multi-session', () => {cleanup();});+ test('tab strip exposes the dock-toggle + collapse buttons and no drag grip', () => {+ renderDock(true);+ expect(screen.getByRole('button', { name: 'Dock terminal to the right' })).not.toBeNull();+ expect(screen.getByRole('button', { name: 'Collapse terminal' })).not.toBeNull();+ expect(screen.queryByRole('button', { name: 'Drag to dock the terminal' })).toBeNull();+ });+test('mounts no session until first opened, then keeps the session mounted on hide', () => {const view = renderDock(false);expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);@@ -672,3 +701,64 @@ describe('TerminalDock multi-session', () => {expect(document.activeElement).toBe(session);});});++describe('TerminalSessionsHost focus-return gating across a dock move', () => {+ afterEach(() => cleanup());++ function FocusHarness({+ bridge,+ isShowing,+ visible,+ onEditorFocus,+ }: {+ // biome-ignore lint/suspicious/noExplicitAny: test harness bridge stub+ bridge: any;+ isShowing: boolean;+ visible: boolean;+ onEditorFocus: () => void;+ }) {+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ return (+ <TooltipProvider>+ <div ref={setContainer} data-testid="term-host-container" />+ <TerminalSessionsHost+ bridge={bridge}+ visible={visible}+ onVisibleChange={() => {}}+ launch={null}+ container={container}+ isShowing={isShowing}+ onRequestEditorFocus={onEditorFocus}+ dockPosition="right"+ onToggleDock={() => {}}+ />+ </TooltipProvider>+ );+ }++ test('a dock move keeps focus (visible stays true); a genuine hide returns focus to the editor', () => {+ const onEditorFocus = mock(() => {});+ const { bridge } = makeBridge();+ const ui = (isShowing: boolean, visible: boolean) => (+ <FocusHarness+ bridge={bridge}+ isShowing={isShowing}+ visible={visible}+ onEditorFocus={onEditorFocus}+ />+ );+ const { rerender } = render(ui(true, true));++ const sink = document.querySelector<HTMLElement>(+ '[data-terminal-session] .xterm-helper-textarea',+ );+ act(() => sink?.focus());+ expect(onEditorFocus).not.toHaveBeenCalled();++ act(() => rerender(ui(false, true)));+ expect(onEditorFocus).not.toHaveBeenCalled();++ act(() => rerender(ui(false, false)));+ expect(onEditorFocus).toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsxindex 1d4600c93..e8136fd6c 100644--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx@@ -1,5 +1,6 @@import { afterEach, describe, expect, mock, test } from 'bun:test';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { useState } from 'react';import { TooltipProvider } from '@/components/ui/tooltip';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';@@ -39,6 +40,35 @@ mock.module('@/lib/terminal-height-store', () => ({}));const { TerminalDock } = await import('./TerminalDock');+const { TerminalSessionsHost } = await import('./TerminalSessionsHost');++function ReloadHarness({ bridge, visible }: { bridge: OkDesktopBridge; visible: boolean }) {+ const [bottomContainer, setBottomContainer] = useState<HTMLDivElement | null>(null);+ return (+ <TooltipProvider>+ <TerminalDock+ visible={visible}+ onVisibleChange={() => {}}+ dockPosition="bottom"+ onBottomContainer={setBottomContainer}+ onEditorRegion={() => {}}+ >+ <div data-testid="editor-child" />+ </TerminalDock>+ <TerminalSessionsHost+ bridge={bridge}+ visible={visible}+ onVisibleChange={() => {}}+ launch={null}+ container={bottomContainer}+ isShowing={visible && bottomContainer != null}+ onRequestEditorFocus={() => {}}+ dockPosition="bottom"+ onToggleDock={() => {}}+ />+ </TooltipProvider>+ );+}function makeSurvivingMainBridge(preExisting: ReadonlyArray<{ ptyId: string }>) {let freshCounter = 0;@@ -65,13 +95,7 @@ function makeSurvivingMainBridge(preExisting: ReadonlyArray<{ ptyId: string }>)}function renderDock(bridge: OkDesktopBridge, visible: boolean) {- return render(- <TooltipProvider>- <TerminalDock bridge={bridge} visible={visible} onVisibleChange={() => {}} launch={null}>- <div data-testid="editor-child" />- </TerminalDock>- </TooltipProvider>,- );+ return render(<ReloadHarness bridge={bridge} visible={visible} />);}describe('issue #351 — the terminal dock rehydrates surviving sessions after a renderer reload', () => {@@ -95,13 +119,7 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a});function dockUi(bridge: OkDesktopBridge, visible: boolean) {- return (- <TooltipProvider>- <TerminalDock bridge={bridge} visible={visible} onVisibleChange={() => {}} launch={null}>- <div data-testid="editor-child" />- </TerminalDock>- </TooltipProvider>- );+ return <ReloadHarness bridge={bridge} visible={visible} />;}test('zero survivors settles so a later open still cold-starts exactly one tab', async () => {diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsxindex 153f37c94..20ebf2025 100644--- a/packages/app/src/components/TerminalDock.tsx+++ b/packages/app/src/components/TerminalDock.tsx@@ -1,134 +1,35 @@-import { useLingui } from '@lingui/react/macro';import { useTheme } from 'next-themes';-import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { type ReactNode, useEffect, useRef, useState } from 'react';import { usePanelRef } from 'react-resizable-panels';import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';-import { TabsContent } from '@/components/ui/tabs';-import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import type { TerminalDockPosition } from '@/lib/terminal-dock-store';import { getInitialTerminalHeight, writeTerminalHeight } from '@/lib/terminal-height-store';import { cn } from '@/lib/utils';-import type { TerminalLaunchIntent } from './EditorPane';-import { TerminalGate } from './TerminalGate';-import { TerminalTabStrip } from './TerminalTabStrip';import { xtermThemeForMode } from './terminal-theme';const TERMINAL_PANEL_ID = 'terminal-dock-panel';-/** A concurrent terminal session the dock hosts as a tab. `id` is a stable- * client-side identity (not the async PTY id — the session resolves its own PTY- * on mount). `launch` is the one-shot intent the session writes once it is live;- * sessions opened from the tab strip carry none. `title` is the latest title the- * running program set via an OSC 0/2 escape sequence (shell prompt, `vim`, the- * `claude` TUI); null until the program sets one, falling back to the positional- * `Terminal N` default. Titles live for the session lifetime only. */-interface TerminalSessionDescriptor {- readonly id: string;- readonly launch: TerminalLaunchIntent | null;- readonly title: string | null;- /** The surviving PTY this tab reconnects to after a renderer reload, or `null`- * for a freshly-opened tab that spawns its own shell. */- readonly adoptPtyId: string | null;-}--function makeSessionId(counter: number): string {- return `terminal-session-${counter}`;-}--/** Move focus into a session's terminal. xterm routes keystrokes through its- * helper textarea, so focusing it is equivalent to term.focus(). No-ops when- * the textarea has not mounted yet (xterm mounts asynchronously). */-function focusTerminalSession(id: string) {- if (id === '') return;- document- .querySelector<HTMLElement>(`[data-terminal-session="${id}"] .xterm-helper-textarea`)- ?.focus();-}-interface TerminalDockProps {- readonly bridge: OkDesktopBridge;readonly children: ReactNode;readonly visible: boolean;readonly onVisibleChange: (visible: boolean) => void;- readonly launch?: TerminalLaunchIntent | null;+ readonly dockPosition?: TerminalDockPosition;+ readonly onBottomContainer: (el: HTMLDivElement | null) => void;+ readonly onEditorRegion: (el: HTMLDivElement | null) => void;}export function TerminalDock({- bridge,children,visible,onVisibleChange,- launch = null,+ dockPosition = 'bottom',+ onBottomContainer,+ onEditorRegion,}: TerminalDockProps) {- const { t } = useLingui();const { resolvedTheme } = useTheme();const panelRef = usePanelRef();- const editorRegionRef = useRef<HTMLDivElement | null>(null);const [isCollapsed, setIsCollapsed] = useState(!visible);-- const canRehydrate = typeof bridge.terminal?.list === 'function';-- const [sessions, setSessions] = useState<readonly TerminalSessionDescriptor[]>(() =>- !canRehydrate && visible- ? [{ id: makeSessionId(1), launch, title: null, adoptPtyId: null }]- : [],- );- const [activeSessionId, setActiveSessionId] = useState(() =>- !canRehydrate && visible ? makeSessionId(1) : '',- );- const [rehydrationSettled, setRehydrationSettled] = useState(!canRehydrate);- const rehydratedRef = useRef(false);- const activeSessionIdRef = useRef(activeSessionId);- const sessionsRef = useRef(sessions);- const sessionCounterRef = useRef(!canRehydrate && visible ? 1 : 0);- const lastHandledLaunchNonceRef = useRef<number | null>(visible && launch ? launch.nonce : null);- const prevVisibleRef = useRef(visible);-- function openSession(launchForSession: TerminalLaunchIntent | null) {- sessionCounterRef.current += 1;- const id = makeSessionId(sessionCounterRef.current);- setSessions((prev) => [- ...prev,- { id, launch: launchForSession, title: null, adoptPtyId: null },- ]);- setActiveSessionId(id);- }-- function setSessionTitle(id: string, title: string) {- const next = title.trim() === '' ? null : title.trim();- setSessions((prev) => {- if (!prev.some((session) => session.id === id && session.title !== next)) return prev;- return prev.map((session) => (session.id === id ? { ...session, title: next } : session));- });- }- const openSessionRef = useRef(openSession);-- function closeSession(id: string) {- const current = sessionsRef.current;- const index = current.findIndex((session) => session.id === id);- if (index === -1) return;- const next = current.filter((session) => session.id !== id);- if (id === activeSessionId) {- const neighbor = current[index - 1] ?? current[index + 1];- const neighborId = neighbor?.id ?? '';- setActiveSessionId(neighborId);- if (neighborId !== '') queueMicrotask(() => focusTerminalSession(neighborId));- }- setSessions(next);- if (next.length === 0) {- onVisibleChange(false);- editorRegionRef.current?.focus();- }- }- const closeActiveRef = useRef(() => {});-- useEffect(() => {- openSessionRef.current = openSession;- activeSessionIdRef.current = activeSessionId;- sessionsRef.current = sessions;- closeActiveRef.current = () => {- if (activeSessionId !== '') closeSession(activeSessionId);- };- });+ const xtermBackground = xtermThemeForMode(resolvedTheme).background;const [initialHeightPx] = useState(() => getInitialTerminalHeight());const heightPxRef = useRef(initialHeightPx);@@ -156,109 +57,15 @@ export function TerminalDock({[],);- useEffect(() => {- if (!rehydrationSettled) return;-- const wasVisible = prevVisibleRef.current;- prevVisibleRef.current = visible;-- if (launch != null && launch.nonce !== lastHandledLaunchNonceRef.current) {- lastHandledLaunchNonceRef.current = launch.nonce;- openSessionRef.current(launch);- return;- }- if (visible && !wasVisible && sessions.length === 0) {- openSessionRef.current(null);- }- }, [visible, launch, sessions.length, rehydrationSettled]);-- useEffect(() => {- if (typeof bridge.terminal?.list !== 'function') return;- if (rehydratedRef.current) return;- rehydratedRef.current = true;- let cancelled = false;- void (async () => {- let survivors: readonly { ptyId: string }[] = [];- try {- survivors = (await bridge.terminal.list()) ?? [];- } catch (err) {- console.error('[terminal] reload session list() failed; cold-starting:', err);- survivors = [];- }- if (cancelled) return;- if (survivors.length > 0) {- const recovered = survivors.map((entry, index) => ({- id: makeSessionId(index + 1),- launch: null,- title: null,- adoptPtyId: entry.ptyId,- }));- sessionCounterRef.current = recovered.length;- setSessions(recovered);- setActiveSessionId(recovered[0]?.id ?? '');- }- setRehydrationSettled(true);- })();- return () => {- cancelled = true;- rehydratedRef.current = false;- };- }, [bridge]);-- useEffect(() => {- return bridge.onMenuAction((action) => {- if (action === 'new-terminal') openSessionRef.current(null);- else if (action === 'kill-terminal') closeActiveRef.current();- });- }, [bridge]);-- useEffect(() => {- function onKeyDown(event: KeyboardEvent) {- if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;- if (!/^[1-9]$/.test(event.key)) return;- const panelEl = document.getElementById(TERMINAL_PANEL_ID);- if (!panelEl?.contains(document.activeElement)) return;- const target = sessionsRef.current[Number(event.key) - 1];- if (target == null) return;- event.preventDefault();- event.stopPropagation();- setActiveSessionId(target.id);- queueMicrotask(() => focusTerminalSession(target.id));- }- window.addEventListener('keydown', onKeyDown, { capture: true });- return () => window.removeEventListener('keydown', onKeyDown, { capture: true });- }, []);-- useEffect(() => {- bridge.editor.notifyViewMenuStateChanged({ terminalLive: sessions.length > 0 });- }, [bridge, sessions.length]);-useEffect(() => {const panel = panelRef.current;if (panel == null) return;- if (visible) {+ if (visible && dockPosition === 'bottom') {panel.resize(`${heightPxRef.current}px`);} else {panel.collapse();}- }, [visible, panelRef]);-- useLayoutEffect(() => {- if (!isCollapsed) return;- const panelEl = document.getElementById(TERMINAL_PANEL_ID);- if (!panelEl?.contains(document.activeElement)) return;- editorRegionRef.current?.focus();- }, [isCollapsed]);-- useEffect(() => {- if (isCollapsed) return;- focusTerminalSession(activeSessionIdRef.current);- }, [isCollapsed]);-- const tabDescriptors = sessions.map((session, index) => ({- id: session.id,- label: session.title ?? t`Terminal ${index + 1}`,- }));+ }, [visible, panelRef, dockPosition]);return (<ResizablePanelGroup@@ -267,10 +74,10 @@ export function TerminalDock({data-dragging={isDragging || undefined}><ResizablePanel minSize="5%" className="flex min-h-0 flex-col">- {/* tabIndex -1 makes this a programmatic focus target for focus-return- on collapse without adding it to the tab order. */}+ {/* tabIndex -1 makes this a programmatic focus target for focus-return on+ collapse without adding it to the tab order. */}<div- ref={editorRegionRef}+ ref={onEditorRegion}tabIndex={-1}className="flex h-full min-h-0 flex-col outline-none">@@ -294,9 +101,9 @@ export function TerminalDock({/><ResizablePanelid={TERMINAL_PANEL_ID}- style={{ backgroundColor: xtermThemeForMode(resolvedTheme).background }}+ style={{ backgroundColor: xtermBackground }}panelRef={panelRef}- defaultSize={visible ? `${initialHeightPx}px` : 0}+ defaultSize={visible && dockPosition === 'bottom' ? `${initialHeightPx}px` : 0}minSize="120px"maxSize="95%"collapsible@@ -320,35 +127,8 @@ export function TerminalDock({'transition-[flex-grow] duration-150 ease-out motion-reduce:transition-none motion-reduce:duration-0',)}>- {sessions.length > 0 ? (- <TerminalTabStrip- sessions={tabDescriptors}- activeSessionId={activeSessionId}- onSelect={setActiveSessionId}- onTabActivate={(id) => queueMicrotask(() => focusTerminalSession(id))}- onNew={() => openSession(null)}- onClose={closeSession}- className="h-full"- >- {sessions.map((session) => (- <TabsContent- key={session.id}- value={session.id}- forceMount- data-terminal-session={session.id}- className="m-0 flex min-h-0 flex-1 flex-col overflow-hidden data-[state=inactive]:hidden"- >- <TerminalGate- bridge={bridge}- launch={session.launch}- adoptPtyId={session.adoptPtyId}- onTitleChange={(title) => setSessionTitle(session.id, title)}- onClose={() => closeSession(session.id)}- />- </TabsContent>- ))}- </TerminalTabStrip>- ) : null}+ {/* Mount point for the session host's stable host div when bottom-docked. */}+ <div ref={onBottomContainer} className="flex min-h-0 flex-1 flex-col overflow-hidden" /></ResizablePanel></ResizablePanelGroup>);diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsxnew file mode 100644index 000000000..3bc7855b0--- /dev/null+++ b/packages/app/src/components/TerminalSessionsHost.tsx@@ -0,0 +1,272 @@+import { useLingui } from '@lingui/react/macro';+import { useEffect, useLayoutEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { TabsContent } from '@/components/ui/tabs';+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import type { TerminalDockPosition } from '@/lib/terminal-dock-store';+import type { TerminalLaunchIntent } from './EditorPane';+import { TerminalGate } from './TerminalGate';+import { TerminalTabStrip } from './TerminalTabStrip';++/** A concurrent terminal session the host keeps as a tab. `id` is a stable+ * client-side identity (not the async PTY id — the session resolves its own PTY+ * on mount). `launch` is the one-shot intent the session writes once it is live;+ * 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. */+interface TerminalSessionDescriptor {+ readonly id: string;+ readonly launch: TerminalLaunchIntent | null;+ readonly title: string | null;+ readonly adoptPtyId: string | null;+}++function makeSessionId(counter: number): string {+ return `terminal-session-${counter}`;+}++/** Move focus into a session's terminal. xterm routes keystrokes through its+ * helper textarea, so focusing it is equivalent to term.focus(). No-ops when+ * the textarea has not mounted yet (xterm mounts asynchronously). */+function focusTerminalSession(id: string) {+ if (id === '') return;+ document+ .querySelector<HTMLElement>(`[data-terminal-session="${id}"] .xterm-helper-textarea`)+ ?.focus();+}++interface TerminalSessionsHostProps {+ readonly bridge: OkDesktopBridge;+ /** Controlled visibility. The host reflects this and reports close-last back+ * through {@link onVisibleChange}; it never owns it. */+ readonly visible: boolean;+ readonly onVisibleChange: (visible: boolean) => void;+ readonly launch?: TerminalLaunchIntent | null;+ readonly container: HTMLElement | null;+ readonly isShowing: boolean;+ readonly onRequestEditorFocus: () => void;+ /** Current dock position — passed to the tab strip's dock-toggle + collapse+ * controls so their icons/labels reflect where the terminal lives. */+ readonly dockPosition: TerminalDockPosition;+ readonly onToggleDock: () => void;+}++export function TerminalSessionsHost({+ bridge,+ visible,+ onVisibleChange,+ launch = null,+ container,+ isShowing,+ onRequestEditorFocus,+ dockPosition,+ onToggleDock,+}: TerminalSessionsHostProps) {+ const { t } = useLingui();++ const [hostEl] = useState<HTMLDivElement | null>(() => {+ if (typeof document === 'undefined') return null;+ const el = document.createElement('div');+ el.className = 'flex min-h-0 flex-1 flex-col overflow-hidden';+ return el;+ });++ useLayoutEffect(() => {+ if (hostEl == null || container == null) return;+ if (hostEl.parentElement !== container) container.appendChild(hostEl);+ }, [hostEl, container]);++ const canRehydrate = typeof bridge.terminal?.list === 'function';++ const [sessions, setSessions] = useState<readonly TerminalSessionDescriptor[]>(() =>+ !canRehydrate && visible+ ? [{ id: makeSessionId(1), launch, title: null, adoptPtyId: null }]+ : [],+ );+ const [activeSessionId, setActiveSessionId] = useState(() =>+ !canRehydrate && visible ? makeSessionId(1) : '',+ );+ const [rehydrationSettled, setRehydrationSettled] = useState(!canRehydrate);+ const rehydratedRef = useRef(false);+ const activeSessionIdRef = useRef(activeSessionId);+ const sessionsRef = useRef(sessions);+ const sessionCounterRef = useRef(!canRehydrate && visible ? 1 : 0);+ const lastHandledLaunchNonceRef = useRef<number | null>(visible && launch ? launch.nonce : null);+ const prevVisibleRef = useRef(visible);++ function openSession(launchForSession: TerminalLaunchIntent | null) {+ sessionCounterRef.current += 1;+ const id = makeSessionId(sessionCounterRef.current);+ setSessions((prev) => [+ ...prev,+ { id, launch: launchForSession, title: null, adoptPtyId: null },+ ]);+ setActiveSessionId(id);+ }++ function setSessionTitle(id: string, title: string) {+ const next = title.trim() === '' ? null : title.trim();+ setSessions((prev) => {+ if (!prev.some((session) => session.id === id && session.title !== next)) return prev;+ return prev.map((session) => (session.id === id ? { ...session, title: next } : session));+ });+ }+ const openSessionRef = useRef(openSession);++ function closeSession(id: string) {+ const current = sessionsRef.current;+ const index = current.findIndex((session) => session.id === id);+ if (index === -1) return;+ const next = current.filter((session) => session.id !== id);+ if (id === activeSessionId) {+ const neighbor = current[index - 1] ?? current[index + 1];+ const neighborId = neighbor?.id ?? '';+ setActiveSessionId(neighborId);+ if (neighborId !== '') queueMicrotask(() => focusTerminalSession(neighborId));+ }+ setSessions(next);+ if (next.length === 0) {+ onVisibleChange(false);+ onRequestEditorFocus();+ }+ }+ const closeActiveRef = useRef(() => {});++ useEffect(() => {+ openSessionRef.current = openSession;+ activeSessionIdRef.current = activeSessionId;+ sessionsRef.current = sessions;+ closeActiveRef.current = () => {+ if (activeSessionId !== '') closeSession(activeSessionId);+ };+ });++ useEffect(() => {+ if (!rehydrationSettled) return;++ const wasVisible = prevVisibleRef.current;+ prevVisibleRef.current = visible;++ if (launch != null && launch.nonce !== lastHandledLaunchNonceRef.current) {+ lastHandledLaunchNonceRef.current = launch.nonce;+ openSessionRef.current(launch);+ return;+ }+ if (visible && !wasVisible && sessions.length === 0) {+ openSessionRef.current(null);+ }+ }, [visible, launch, sessions.length, rehydrationSettled]);++ useEffect(() => {+ if (typeof bridge.terminal?.list !== 'function') return;+ if (rehydratedRef.current) return;+ rehydratedRef.current = true;+ let cancelled = false;+ void (async () => {+ let survivors: readonly { ptyId: string }[] = [];+ try {+ survivors = (await bridge.terminal.list()) ?? [];+ } catch (err) {+ console.error('[terminal] reload session list() failed; cold-starting:', err);+ survivors = [];+ }+ if (cancelled) return;+ if (survivors.length > 0) {+ const recovered = survivors.map((entry, index) => ({+ id: makeSessionId(index + 1),+ launch: null,+ title: null,+ adoptPtyId: entry.ptyId,+ }));+ sessionCounterRef.current = recovered.length;+ setSessions(recovered);+ setActiveSessionId(recovered[0]?.id ?? '');+ }+ setRehydrationSettled(true);+ })();+ return () => {+ cancelled = true;+ rehydratedRef.current = false;+ };+ }, [bridge]);++ useEffect(() => {+ return bridge.onMenuAction((action) => {+ if (action === 'new-terminal') openSessionRef.current(null);+ else if (action === 'kill-terminal') closeActiveRef.current();+ });+ }, [bridge]);++ useEffect(() => {+ function onKeyDown(event: KeyboardEvent) {+ if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;+ if (!/^[1-9]$/.test(event.key)) return;+ if (hostEl == null || !hostEl.contains(document.activeElement)) return;+ const target = sessionsRef.current[Number(event.key) - 1];+ if (target == null) return;+ event.preventDefault();+ event.stopPropagation();+ setActiveSessionId(target.id);+ queueMicrotask(() => focusTerminalSession(target.id));+ }+ window.addEventListener('keydown', onKeyDown, { capture: true });+ return () => window.removeEventListener('keydown', onKeyDown, { capture: true });+ }, [hostEl]);++ useEffect(() => {+ bridge.editor.notifyViewMenuStateChanged({ terminalLive: sessions.length > 0 });+ }, [bridge, sessions.length]);++ useLayoutEffect(() => {+ if (isShowing || visible) return;+ if (hostEl == null || !hostEl.contains(document.activeElement)) return;+ onRequestEditorFocus();+ }, [isShowing, visible, hostEl, onRequestEditorFocus]);++ useEffect(() => {+ if (!isShowing) return;+ focusTerminalSession(activeSessionIdRef.current);+ }, [isShowing]);++ const tabDescriptors = sessions.map((session, index) => ({+ id: session.id,+ label: session.title ?? t`Terminal ${index + 1}`,+ }));++ const sessionViews =+ sessions.length > 0 ? (+ <TerminalTabStrip+ sessions={tabDescriptors}+ activeSessionId={activeSessionId}+ onSelect={setActiveSessionId}+ onTabActivate={(id) => queueMicrotask(() => focusTerminalSession(id))}+ onNew={() => openSession(null)}+ onClose={closeSession}+ dockPosition={dockPosition}+ onToggleDock={onToggleDock}+ onCollapse={() => onVisibleChange(false)}+ className="h-full"+ >+ {sessions.map((session) => (+ <TabsContent+ key={session.id}+ value={session.id}+ forceMount+ data-terminal-session={session.id}+ className="m-0 flex min-h-0 flex-1 flex-col overflow-hidden data-[state=inactive]:hidden"+ >+ <TerminalGate+ bridge={bridge}+ launch={session.launch}+ adoptPtyId={session.adoptPtyId}+ onTitleChange={(title) => setSessionTitle(session.id, title)}+ onClose={() => closeSession(session.id)}+ />+ </TabsContent>+ ))}+ </TerminalTabStrip>+ ) : null;++ return hostEl != null ? createPortal(sessionViews, hostEl) : null;+}diff --git a/packages/app/src/components/TerminalTabStrip.dom.test.tsx b/packages/app/src/components/TerminalTabStrip.dom.test.tsxindex 68631846b..5d27c08d2 100644--- a/packages/app/src/components/TerminalTabStrip.dom.test.tsx+++ b/packages/app/src/components/TerminalTabStrip.dom.test.tsx@@ -13,11 +13,14 @@ const SESSIONS: readonly TerminalTabDescriptor[] = [function renderStrip(props?: {sessions?: readonly TerminalTabDescriptor[];activeSessionId?: string;+ dockPosition?: 'bottom' | 'right';}) {const onSelect = mock((_id: string) => {});const onTabActivate = mock((_id: string) => {});const onNew = mock(() => {});const onClose = mock((_id: string) => {});+ const onToggleDock = mock(() => {});+ const onCollapse = mock(() => {});render(<TooltipProvider><TerminalTabStrip@@ -27,10 +30,13 @@ function renderStrip(props?: {onTabActivate={onTabActivate}onNew={onNew}onClose={onClose}+ dockPosition={props?.dockPosition ?? 'bottom'}+ onToggleDock={onToggleDock}+ onCollapse={onCollapse}/></TooltipProvider>,);- return { onSelect, onTabActivate, onNew, onClose };+ return { onSelect, onTabActivate, onNew, onClose, onToggleDock, onCollapse };}describe('TerminalTabStrip', () => {@@ -120,9 +126,43 @@ describe('TerminalTabStrip', () => {expect(onNew).not.toHaveBeenCalled();});+ test('the dock-toggle reports onToggleDock and labels the resulting position', async () => {+ const user = userEvent.setup();+ const bottom = renderStrip({ dockPosition: 'bottom' });+ const toRight = screen.getByRole('button', { name: 'Dock terminal to the right' });+ await user.click(toRight);+ expect(bottom.onToggleDock).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole('button', { name: 'Dock terminal to the bottom' })).toBeNull();+ cleanup();++ const right = renderStrip({ dockPosition: 'right' });+ const toBottom = screen.getByRole('button', { name: 'Dock terminal to the bottom' });+ await user.click(toBottom);+ expect(right.onToggleDock).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole('button', { name: 'Dock terminal to the right' })).toBeNull();+ });++ test('the collapse control reports onCollapse and never onClose/onNew', async () => {+ const user = userEvent.setup();+ const { onCollapse, onClose, onNew } = renderStrip();++ await user.click(screen.getByRole('button', { name: 'Collapse terminal' }));++ expect(onCollapse).toHaveBeenCalledTimes(1);+ expect(onClose).not.toHaveBeenCalled();+ expect(onNew).not.toHaveBeenCalled();+ });++ test('no drag-to-dock grip is rendered (dragging was removed)', () => {+ renderStrip();+ expect(screen.queryByRole('button', { name: 'Drag to dock the terminal' })).toBeNull();+ });+test('every icon-only control exposes an accessible name', () => {renderStrip();expect(screen.getByRole('button', { name: 'New terminal' })).toBeDefined();+ expect(screen.getByRole('button', { name: 'Dock terminal to the right' })).toBeDefined();+ expect(screen.getByRole('button', { name: 'Collapse terminal' })).toBeDefined();for (const label of ['Terminal 1', 'Terminal 2', 'Terminal 3']) {expect(screen.getByRole('button', { name: `Close ${label}` })).toBeDefined();}diff --git a/packages/app/src/components/TerminalTabStrip.tsx b/packages/app/src/components/TerminalTabStrip.tsxindex f7b87efb7..843369902 100644--- a/packages/app/src/components/TerminalTabStrip.tsx+++ b/packages/app/src/components/TerminalTabStrip.tsx@@ -1,9 +1,17 @@import { Trans, useLingui } from '@lingui/react/macro';-import { PlusIcon, XIcon } from 'lucide-react';+import {+ ChevronDownIcon,+ ChevronRightIcon,+ PanelBottomIcon,+ PanelRightIcon,+ PlusIcon,+ XIcon,+} from 'lucide-react';import type { ReactNode } from 'react';import { Button } from '@/components/ui/button';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';export interface TerminalTabDescriptor {@@ -18,6 +26,11 @@ interface TerminalTabStripProps {readonly onTabActivate?: (id: string) => void;readonly onNew: () => void;readonly onClose: (id: string) => void;+ /** Where the terminal is currently docked — drives the dock-toggle + collapse+ * button icons/labels. */+ readonly dockPosition: TerminalDockPosition;+ readonly onToggleDock: () => void;+ readonly onCollapse: () => void;readonly children?: ReactNode;readonly className?: string;}@@ -29,10 +42,14 @@ export function TerminalTabStrip({onTabActivate,onNew,onClose,+ dockPosition,+ onToggleDock,+ onCollapse,children,className,}: TerminalTabStripProps) {const { t } = useLingui();+ const rightDocked = dockPosition === 'right';return (<Tabsvalue={activeSessionId}@@ -51,7 +68,7 @@ export function TerminalTabStrip({<divkey={session.id}className={cn(- 'group flex shrink-0 items-center rounded-md pr-0.5 transition-colors',+ 'group flex shrink-0 cursor-default items-center rounded-md pr-0.5 transition-colors',isActive ? 'bg-muted' : 'hover:bg-muted/50',)}>@@ -90,7 +107,7 @@ export function TerminalTabStrip({variant="ghost"size="icon-xs"aria-label={t`New terminal`}- className="shrink-0 text-muted-foreground hover:text-foreground"+ className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"onClick={onNew}><PlusIcon aria-hidden="true" />@@ -100,6 +117,56 @@ export function TerminalTabStrip({<Trans>New terminal</Trans></TooltipContent></Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={+ rightDocked ? t`Dock terminal to the bottom` : t`Dock terminal to the right`+ }+ className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"+ onClick={onToggleDock}+ >+ {rightDocked ? (+ <PanelBottomIcon aria-hidden="true" />+ ) : (+ <PanelRightIcon aria-hidden="true" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={8}>+ {rightDocked ? (+ <Trans>Dock terminal to the bottom</Trans>+ ) : (+ <Trans>Dock terminal to the right</Trans>+ )}+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={t`Collapse terminal`}+ className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"+ onClick={onCollapse}+ >+ {/* Chevron points the way the panel slides shut: down for the bottom+ dock, right for the right column. */}+ {rightDocked ? (+ <ChevronRightIcon aria-hidden="true" />+ ) : (+ <ChevronDownIcon aria-hidden="true" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={8}>+ <Trans>Collapse terminal</Trans>+ </TooltipContent>+ </Tooltip></div>{children}</Tabs>diff --git a/packages/app/src/lib/terminal-dock-store.test.ts b/packages/app/src/lib/terminal-dock-store.test.tsnew file mode 100644index 000000000..3a6116cda--- /dev/null+++ b/packages/app/src/lib/terminal-dock-store.test.ts@@ -0,0 +1,58 @@+import { describe, expect, test } from 'bun:test';+import {+ DEFAULT_TERMINAL_DOCK,+ type DockStorage,+ readTerminalDock,+ TERMINAL_DOCK_KEY,+ writeTerminalDock,+} from './terminal-dock-store';++function memoryStorage(initial?: string): DockStorage & { value: string | null } {+ return {+ value: initial ?? null,+ getItem(key) {+ return key === TERMINAL_DOCK_KEY ? this.value : null;+ },+ setItem(key, value) {+ if (key === TERMINAL_DOCK_KEY) this.value = value;+ },+ };+}++describe('terminal-dock-store', () => {+ test('defaults to right when nothing is stored', () => {+ expect(readTerminalDock(memoryStorage())).toBe('right');+ expect(DEFAULT_TERMINAL_DOCK).toBe('right');+ });++ test('round-trips a bottom dock position', () => {+ const s = memoryStorage();+ writeTerminalDock('bottom', s);+ expect(s.value).toBe('bottom');+ expect(readTerminalDock(s)).toBe('bottom');+ });++ test('round-trips a right dock position', () => {+ const s = memoryStorage('bottom');+ writeTerminalDock('right', s);+ expect(readTerminalDock(s)).toBe('right');+ });++ test('coerces an unknown/corrupted stored value to the right default', () => {+ expect(readTerminalDock(memoryStorage('sideways'))).toBe('right');+ expect(readTerminalDock(memoryStorage(''))).toBe('right');+ });++ test('falls back to the default when storage throws', () => {+ const throwing: DockStorage = {+ getItem() {+ throw new Error('SecurityError');+ },+ setItem() {+ throw new Error('SecurityError');+ },+ };+ expect(readTerminalDock(throwing)).toBe('right');+ expect(() => writeTerminalDock('bottom', throwing)).not.toThrow();+ });+});diff --git a/packages/app/src/lib/terminal-dock-store.ts b/packages/app/src/lib/terminal-dock-store.tsnew file mode 100644index 000000000..af59e7d54--- /dev/null+++ b/packages/app/src/lib/terminal-dock-store.ts@@ -0,0 +1,39 @@+export const TERMINAL_DOCK_KEY = 'ok-terminal-dock-v1';++export type TerminalDockPosition = 'bottom' | 'right';++export const DEFAULT_TERMINAL_DOCK: TerminalDockPosition = 'right';++export interface DockStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++function coerce(raw: string | null): TerminalDockPosition {+ return raw === 'bottom' ? 'bottom' : 'right';+}++export function readTerminalDock(storage?: DockStorage): TerminalDockPosition {+ try {+ const s = storage ?? localStorage;+ return coerce(s.getItem(TERMINAL_DOCK_KEY));+ } catch {+ return DEFAULT_TERMINAL_DOCK;+ }+}++export function writeTerminalDock(position: TerminalDockPosition, storage?: DockStorage): void {+ try {+ const s = storage ?? localStorage;+ s.setItem(TERMINAL_DOCK_KEY, position);+ } catch {}+}++export function getInitialTerminalDock(): TerminalDockPosition {+ try {+ if (typeof localStorage === 'undefined') return DEFAULT_TERMINAL_DOCK;+ return readTerminalDock();+ } catch {+ return DEFAULT_TERMINAL_DOCK;+ }+}diff --git a/packages/app/src/lib/terminal-width-store.test.ts b/packages/app/src/lib/terminal-width-store.test.tsnew file mode 100644index 000000000..5c31abc31--- /dev/null+++ b/packages/app/src/lib/terminal-width-store.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test } from 'bun:test';+import {+ DEFAULT_TERMINAL_WIDTH,+ MAX_TERMINAL_WIDTH,+ MIN_TERMINAL_WIDTH,+ readTerminalWidth,+ TERMINAL_WIDTH_KEY,+ type TerminalWidthStorage,+ writeTerminalWidth,+} from './terminal-width-store.ts';++function memoryStorage(initial: Record<string, string> = {}): TerminalWidthStorage {+ const data = new Map(Object.entries(initial));+ return {+ getItem(key) {+ return data.get(key) ?? null;+ },+ setItem(key, value) {+ data.set(key, value);+ },+ };+}++describe('readTerminalWidth', () => {+ test('absent key returns default', () => {+ expect(readTerminalWidth(memoryStorage())).toBe(DEFAULT_TERMINAL_WIDTH);+ });++ test('valid stored width is returned', () => {+ const s = memoryStorage({ [TERMINAL_WIDTH_KEY]: '640' });+ expect(readTerminalWidth(s)).toBe(640);+ });++ test('width below floor is clamped to MIN', () => {+ const s = memoryStorage({ [TERMINAL_WIDTH_KEY]: '200' });+ expect(readTerminalWidth(s)).toBe(MIN_TERMINAL_WIDTH);+ });++ test('width above ceiling is clamped to MAX', () => {+ const s = memoryStorage({ [TERMINAL_WIDTH_KEY]: '9999' });+ expect(readTerminalWidth(s)).toBe(MAX_TERMINAL_WIDTH);+ });++ test('non-numeric value falls back to default', () => {+ const s = memoryStorage({ [TERMINAL_WIDTH_KEY]: 'not a number' });+ expect(readTerminalWidth(s)).toBe(DEFAULT_TERMINAL_WIDTH);+ });++ test('empty string falls back to default', () => {+ const s = memoryStorage({ [TERMINAL_WIDTH_KEY]: '' });+ expect(readTerminalWidth(s)).toBe(DEFAULT_TERMINAL_WIDTH);+ });++ test('floating-point string is truncated by parseInt', () => {+ const s = memoryStorage({ [TERMINAL_WIDTH_KEY]: '640.6' });+ expect(readTerminalWidth(s)).toBe(640);+ });+});++describe('writeTerminalWidth', () => {+ test('writes a clamped integer to storage', () => {+ const s = memoryStorage();+ writeTerminalWidth(640, s);+ expect(s.getItem(TERMINAL_WIDTH_KEY)).toBe('640');+ });++ test('clamps to MIN on write below floor', () => {+ const s = memoryStorage();+ writeTerminalWidth(100, s);+ expect(s.getItem(TERMINAL_WIDTH_KEY)).toBe(String(MIN_TERMINAL_WIDTH));+ });++ test('clamps to MAX on write above ceiling', () => {+ const s = memoryStorage();+ writeTerminalWidth(9999, s);+ expect(s.getItem(TERMINAL_WIDTH_KEY)).toBe(String(MAX_TERMINAL_WIDTH));+ });++ test('rounds floating-point input before write', () => {+ const s = memoryStorage();+ writeTerminalWidth(640.7, s);+ expect(s.getItem(TERMINAL_WIDTH_KEY)).toBe('641');+ });++ test('quota-exceeded throw is swallowed (in-memory only)', () => {+ const throwing: TerminalWidthStorage = {+ getItem() {+ return null;+ },+ setItem() {+ throw new Error('QuotaExceededError');+ },+ };+ expect(() => writeTerminalWidth(640, throwing)).not.toThrow();+ });+});diff --git a/packages/app/src/lib/terminal-width-store.ts b/packages/app/src/lib/terminal-width-store.tsnew file mode 100644index 000000000..d1d7884ab--- /dev/null+++ b/packages/app/src/lib/terminal-width-store.ts@@ -0,0 +1,46 @@+export const TERMINAL_WIDTH_KEY = 'ok-terminal-width-v1';++export const DEFAULT_TERMINAL_WIDTH = 480;+export const MIN_TERMINAL_WIDTH = 320;+export const MAX_TERMINAL_WIDTH = 900;++export interface TerminalWidthStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++function clamp(px: number): number {+ if (!Number.isFinite(px)) return DEFAULT_TERMINAL_WIDTH;+ if (px < MIN_TERMINAL_WIDTH) return MIN_TERMINAL_WIDTH;+ if (px > MAX_TERMINAL_WIDTH) return MAX_TERMINAL_WIDTH;+ return Math.round(px);+}++export function readTerminalWidth(storage?: TerminalWidthStorage): number {+ try {+ const s = storage ?? localStorage;+ const raw = s.getItem(TERMINAL_WIDTH_KEY);+ if (raw == null) return DEFAULT_TERMINAL_WIDTH;+ const parsed = Number.parseInt(raw, 10);+ if (!Number.isFinite(parsed)) return DEFAULT_TERMINAL_WIDTH;+ return clamp(parsed);+ } catch {+ return DEFAULT_TERMINAL_WIDTH;+ }+}++export function writeTerminalWidth(px: number, storage?: TerminalWidthStorage): void {+ try {+ const s = storage ?? localStorage;+ s.setItem(TERMINAL_WIDTH_KEY, String(clamp(px)));+ } catch {}+}++export function getInitialTerminalWidth(): number {+ try {+ if (typeof localStorage === 'undefined') return DEFAULT_TERMINAL_WIDTH;+ return readTerminalWidth();+ } catch {+ return DEFAULT_TERMINAL_WIDTH;+ }+}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 2a6a6be2f..510089b03 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -965,6 +965,7 @@"Q7W-mC": ["Same folder as current file"],"Q8A-U_": ["Connected to"],"QDZbvN": [["diffDays"], "d ago"],+ "QNxpRm": ["Dock terminal to the right"],"QOINDn": ["empty"],"QQghPu": ["Install in Claude Desktop"],"QR5SP1": ["created template"],@@ -1106,6 +1107,7 @@"VU3Nrn": ["Missing"],"VUijjF": ["Embed an image with optional alt text."],"VYd_YA": ["Open an existing project folder from disk."],+ "VZGGPK": ["Collapse terminal"],"VZGh8G": ["Fold, unfold, fold all, or unfold all source ranges."],"VZSBXL": ["Semantic ranking activates the first time an agent runs a search."],"V_6bJ4": ["Terminal settings not loaded yet — try again in a moment."],@@ -1871,6 +1873,7 @@"rZVMkf": ["Visual editor replace input focused"],"rageVb": ["Custom HTML with a live preview pane (sandboxed iframe)."],"rdU729": ["Layout"],+ "rf6x3F": ["Dock terminal to the bottom"],"rfFpcF": ["Remove ", ["chip"]],"rgPqOw": ["Convert the current block to a paragraph."],"riqekz": ["Suggestion menu navigation"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 8e6c95af7..128ff9475 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1249,6 +1249,10 @@ msgstr "Collapse burst {burstNumber} diff"msgid "Collapse graph"msgstr "Collapse graph"+#: src/components/TerminalTabStrip.tsx+msgid "Collapse terminal"+msgstr "Collapse terminal"+#: src/editor/slash-command/component-items.tsxmsgid "Collapsible section with a clickable summary."msgstr "Collapsible section with a clickable summary."@@ -2134,6 +2138,14 @@ msgstr "Do you want to permanently delete instead?"msgid "Doc mention suggestions"msgstr "Doc mention suggestions"+#: src/components/TerminalTabStrip.tsx+msgid "Dock terminal to the bottom"+msgstr "Dock terminal to the bottom"++#: src/components/TerminalTabStrip.tsx+msgid "Dock terminal to the right"+msgstr "Dock terminal to the right"+#: src/components/HelpPopover.tsxmsgid "Docs"msgstr "Docs"@@ -6139,7 +6151,7 @@ msgid "Terminal"msgstr "Terminal"#. placeholder {0}: index + 1-#: src/components/TerminalDock.tsx+#: 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 e56121e63..bf4924d40 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -965,6 +965,7 @@"Q7W-mC": ["Śàḿē ƒōĺďēŕ àś ćũŕŕēńţ ƒĩĺē"],"Q8A-U_": ["Ćōńńēćţēď ţō"],"QDZbvN": [["diffDays"], "ď àĝō"],+ "QNxpRm": ["Ďōćķ ţēŕḿĩńàĺ ţō ţĥē ŕĩĝĥţ"],"QOINDn": ["ēḿƥţŷ"],"QQghPu": ["Ĩńśţàĺĺ ĩń Ćĺàũďē Ďēśķţōƥ"],"QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],@@ -1106,6 +1107,7 @@"VU3Nrn": ["Ḿĩśśĩńĝ"],"VUijjF": ["Ēḿƀēď àń ĩḿàĝē ŵĩţĥ ōƥţĩōńàĺ àĺţ ţēxţ."],"VYd_YA": ["Ōƥēń àń ēxĩśţĩńĝ ƥŕōĴēćţ ƒōĺďēŕ ƒŕōḿ ďĩśķ."],+ "VZGGPK": ["Ćōĺĺàƥśē ţēŕḿĩńàĺ"],"VZGh8G": ["Ƒōĺď, ũńƒōĺď, ƒōĺď àĺĺ, ōŕ ũńƒōĺď àĺĺ śōũŕćē ŕàńĝēś."],"VZSBXL": ["Śēḿàńţĩć ŕàńķĩńĝ àćţĩvàţēś ţĥē ƒĩŕśţ ţĩḿē àń àĝēńţ ŕũńś à śēàŕćĥ."],"V_6bJ4": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ĺōàďēď ŷēţ — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],@@ -1871,6 +1873,7 @@"rZVMkf": ["Vĩśũàĺ ēďĩţōŕ ŕēƥĺàćē ĩńƥũţ ƒōćũśēď"],"rageVb": ["Ćũśţōḿ ĤŢḾĹ ŵĩţĥ à ĺĩvē ƥŕēvĩēŵ ƥàńē (śàńďƀōxēď ĩƒŕàḿē)."],"rdU729": ["Ĺàŷōũţ"],+ "rf6x3F": ["Ďōćķ ţēŕḿĩńàĺ ţō ţĥē ƀōţţōḿ"],"rfFpcF": ["Ŕēḿōvē ", ["chip"]],"rgPqOw": ["Ćōńvēŕţ ţĥē ćũŕŕēńţ ƀĺōćķ ţō à ƥàŕàĝŕàƥĥ."],"riqekz": ["Śũĝĝēśţĩōń ḿēńũ ńàvĩĝàţĩōń"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 1c57c1629..9f8f2dac2 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1244,6 +1244,10 @@ msgstr ""msgid "Collapse graph"msgstr ""+#: src/components/TerminalTabStrip.tsx+msgid "Collapse terminal"+msgstr ""+#: src/editor/slash-command/component-items.tsxmsgid "Collapsible section with a clickable summary."msgstr ""@@ -2129,6 +2133,14 @@ msgstr ""msgid "Doc mention suggestions"msgstr ""+#: src/components/TerminalTabStrip.tsx+msgid "Dock terminal to the bottom"+msgstr ""++#: src/components/TerminalTabStrip.tsx+msgid "Dock terminal to the right"+msgstr ""+#: src/components/HelpPopover.tsxmsgid "Docs"msgstr ""@@ -6134,7 +6146,7 @@ msgid "Terminal"msgstr ""#. placeholder {0}: index + 1-#: src/components/TerminalDock.tsx+#: src/components/TerminalSessionsHost.tsxmsgid "Terminal {0}"msgstr ""diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex 8a4f02547..de52d016d 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -170,6 +170,16 @@ async function waitForStatus(page: Page, status: string, timeoutMs = 20_000): Pr});}+/** Ensure the terminal is bottom-docked. The default dock is the right column, so+ * the bottom-panel assertions (`#terminal-dock-panel`) first flip it down via the+ * tab strip's dock-toggle button (which reads "Dock terminal to the bottom" while+ * right-docked). A no-op if it is already bottom-docked. */+async function ensureBottomDock(page: Page): Promise<void> {+ const toBottom = page.getByRole('button', { name: 'Dock terminal to the bottom' });+ if (await toBottom.count()) await toBottom.click();+ await expect(page.locator('#terminal-dock-panel')).toBeVisible({ timeout: 10_000 });+}+async function typeInTerminal(page: Page, text: string): Promise<void> {await page.locator('section[aria-label="Terminal"] .xterm').click();await page.keyboard.type(text);@@ -311,6 +321,79 @@ test.describe('Docked terminal — live Electron', () => {.toContain('OK_E2E_MARKER_123');});+ test('terminal tab strip exposes dock-toggle + collapse buttons and no drag grip', async ({+ captureStderrFor,+ }) => {+ const s = seed('dock-controls', { consent: true });+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s, { restrictPath: true });+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);+ await waitForStatus(page, 'running', 25_000);+ await expect(page.getByRole('button', { name: /Dock terminal to the/ })).toBeVisible({+ timeout: 10_000,+ });+ await expect(page.getByRole('button', { name: 'Collapse terminal' })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Drag to dock the terminal' })).toHaveCount(0);+ });++ test('movable dock — the dock-toggle button moves the terminal between bottom and right', async ({+ captureStderrFor,+ }) => {+ const s = seed('dock-move', { consent: true });+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s, { restrictPath: true });+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);+ await waitForStatus(page, 'running', 25_000);++ await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({+ timeout: 10_000,+ });++ await page.getByRole('button', { name: 'Dock terminal to the bottom' }).click();+ await expect(page.locator('#terminal-dock-panel section[aria-label="Terminal"]')).toBeVisible({+ timeout: 10_000,+ });++ await page.getByRole('button', { name: 'Dock terminal to the right' }).click();+ await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({+ timeout: 10_000,+ });+ });++ test('movable dock — preserves the same live terminal session across moves', async ({+ captureStderrFor,+ }) => {+ const s = seed('dock-parity', { consent: true });+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s, { restrictPath: true });+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);+ await waitForStatus(page, 'running', 25_000);++ const xterm = page.locator('section[aria-label="Terminal"] .xterm');+ await xterm.evaluate((el) => {+ (el as HTMLElement).dataset.parityTag = 'OK_PARITY_TAG';+ });+ await page.getByRole('button', { name: 'Dock terminal to the bottom' }).click();+ await expect+ .poll(+ () =>+ page.evaluate(+ () =>+ document+ .querySelector<HTMLElement>('.xterm[data-parity-tag="OK_PARITY_TAG"]')+ ?.closest('#terminal-dock-panel') != null,+ ),+ { timeout: 10_000 },+ )+ .toBe(true);+ });+test('QA-020 panel exposes region + screen-reader mode + AA contrast', async ({captureStderrFor,}) => {@@ -365,6 +448,7 @@ test.describe('Docked terminal — live Electron', () => {const page = await findEditorWindow(app);await openTerminal(app, page);await waitForStatus(page, 'running', 25_000);+ await ensureBottomDock(page);await page.locator('section[aria-label="Terminal"] .xterm').click();await clickViewTerminalItem(app);@@ -389,6 +473,7 @@ test.describe('Docked terminal — live Electron', () => {const page = await findEditorWindow(app);await openTerminal(app, page);await waitForStatus(page, 'running', 25_000);+ await ensureBottomDock(page);const heightBefore = await page.locator('#terminal-dock-panel')