Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): docked terminal in-panel tabs (multi-session) (#1994)

serafin-garcia912f5b9ab89d
diff --git a/.changeset/terminal-multi-session-tabs.md b/.changeset/terminal-multi-session-tabs.md
new file mode 100644
index 000000000..e5dad6e2f
--- /dev/null
+++ b/.changeset/terminal-multi-session-tabs.md
@@ -0,0 +1,14 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+The docked terminal now supports **multiple concurrent sessions as tabs**. Run an agent in one tab while you run `git`, a build, or a second shell in another — no more waiting for one session to free up or alt-tabbing to an external terminal.
+
+- A tab strip in the dock header lists open sessions with a `+` New Terminal affordance, a per-tab close (×), and an active indicator. Each tab is its own login shell at the project root.
+- Sessions are fully isolated: a flood or a crash in one tab pauses or restarts only that tab — output stays byte-exact with no cross-tab interleave, and backpressure is accounted per session.
+- Tab lifecycle follows the VS Code / Zed model: closing the active tab activates a neighbor, closing the last tab collapses the dock and returns focus to the editor, and hiding the dock (⌘J) keeps every session alive (hide is not kill).
+- "Open in terminal" always opens a fresh tab and runs `claude` there once — it never interrupts a tab you're already using.
+- The Terminal menu's New/Kill Terminal and a ⌘-number tab-switch shortcut operate on tabs; the tab strip is keyboard- and screen-reader-navigable (tablist roles, arrow-key movement, focus-on-close).
+- Each session keeps 10,000 lines of scrollback.
+
+Under the hood, all of a window's sessions are multiplexed through one terminal host process (matching VS Code's shared-host model), so per-window memory stays flat regardless of tab count. The security posture is unchanged: terminals remain human-only and default-on, and no new IPC surface is added. Split panes and per-tab shell/cwd selection are deliberately not included yet.
diff --git a/packages/app/package.json b/packages/app/package.json
index 88710db78..578b5779d 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -43,7 +43,7 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "415 kB",
+ "limit": "420 kB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index 165187ded..31b3227d2 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -240,6 +240,24 @@ describe('EditorPane terminal dock wiring', () => {
expect(dock().getAttribute('data-launch-nonce')).toBe('none');
});
+ test('desktop: a distinct Open-in-terminal after a hide gets a fresh, monotonic nonce', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ const { requestTerminalLaunch } = await import('./handoff/terminal-launch-events');
+ await renderEditorPane();
+
+ const dock = () => screen.getByTestId('terminal-dock');
+
+ act(() => requestTerminalLaunch('first'));
+ expect(dock().getAttribute('data-launch-nonce')).toBe('1');
+
+ act(() => desk.dispatchMenuAction('toggle-terminal'));
+ expect(dock().getAttribute('data-launch-nonce')).toBe('none');
+
+ act(() => requestTerminalLaunch('second'));
+ expect(dock().getAttribute('data-launch-nonce')).toBe('2');
+ });
+
test('desktop: new-terminal menu action opens the dock and stays open on repeat (not a toggle)', async () => {
const desk = makeOkDesktopStub();
(window as { okDesktop?: unknown }).okDesktop = desk.stub;
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index a869bd280..ea679db87 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -1,5 +1,5 @@
import { useLingui } from '@lingui/react/macro';
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { TagDialog } from '@/editor/components/TagDialog';
import { useDocumentContext } from '@/editor/DocumentContext';
@@ -51,6 +51,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
const desktopBridge = typeof window !== 'undefined' ? (window.okDesktop ?? null) : null;
const [terminalVisible, setTerminalVisible] = useState(false);
const [terminalLaunch, setTerminalLaunch] = useState<TerminalLaunchIntent | null>(null);
+ const launchNonceRef = useRef(0);
const syncStatus = useGitSyncStatus();
const { projectLocalConfig, projectLocalSynced } = useConfigContext();
@@ -105,7 +106,8 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
useEffect(() => {
return subscribeToTerminalLaunchRequests((prompt) => {
setTerminalVisible(true);
- setTerminalLaunch((prev) => ({ prompt, nonce: (prev?.nonce ?? 0) + 1 }));
+ launchNonceRef.current += 1;
+ setTerminalLaunch({ prompt, nonce: launchNonceRef.current });
});
}, []);
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
index 899a4a6f3..a858a40d5 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.dom.test.tsx
@@ -1,15 +1,13 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
-import { act, cleanup, fireEvent, 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 } from 'react';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
const TERMINAL_PANEL_ID = 'terminal-dock-panel';
-type Size = { asPercentage: number; inPixels: number };
// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props, asserted structurally
let terminalPanelProps: Record<string, any> | null = null;
-// biome-ignore lint/suspicious/noExplicitAny: captured TerminalGate props (onClose), asserted structurally
-let lastTerminalPanelProps: Record<string, any> | null = null;
-let written: number[] = [];
const panelHandle = {
collapse: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
@@ -53,17 +51,37 @@ mock.module('@/components/ui/resizable', () => ({
mock.module('./TerminalGate', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
- TerminalGate: (props: any) => {
- lastTerminalPanelProps = props;
- return <span data-testid="terminal-panel" className="xterm-helper-textarea" tabIndex={-1} />;
+ TerminalGate: ({ bridge, launch }: any) => {
+ const ptyIdRef = useRef<string | null>(null);
+ const cancelledRef = useRef(false);
+ useEffect(() => {
+ cancelledRef.current = false;
+ void Promise.resolve(bridge?.terminal?.create?.({ cols: 80, rows: 24 })).then(
+ (result: { ok?: boolean; ptyId?: string } | undefined) => {
+ if (!result?.ok || result.ptyId == null) return;
+ if (cancelledRef.current) bridge?.terminal?.kill?.(result.ptyId);
+ else ptyIdRef.current = result.ptyId;
+ },
+ );
+ return () => {
+ cancelledRef.current = true;
+ if (ptyIdRef.current != null) bridge?.terminal?.kill?.(ptyIdRef.current);
+ };
+ }, [bridge]);
+ return (
+ <span
+ data-testid="terminal-session"
+ data-launch={launch?.nonce ?? 'none'}
+ className="xterm-helper-textarea"
+ tabIndex={-1}
+ />
+ );
},
}));
mock.module('@/lib/terminal-height-store', () => ({
getInitialTerminalHeight: () => 240,
- writeTerminalHeight: (px: number) => {
- written.push(px);
- },
+ writeTerminalHeight: () => {},
}));
const { TerminalDock } = await import('./TerminalDock');
@@ -71,6 +89,12 @@ const { TerminalDock } = await import('./TerminalDock');
function makeBridge() {
const menuHandlers: Array<(action: string) => void> = [];
const viewMenuPushes: Array<{ terminalLive?: boolean }> = [];
+ let ptyCounter = 0;
+ const create = mock(async () => {
+ ptyCounter += 1;
+ return { ok: true as const, ptyId: `pty-${ptyCounter}` };
+ });
+ const kill = mock(async (_id: string) => {});
const bridge = {
onMenuAction(cb: (action: string) => void) {
menuHandlers.push(cb);
@@ -84,9 +108,12 @@ function makeBridge() {
viewMenuPushes.push(state);
},
},
+ terminal: { create, kill },
} as unknown as OkDesktopBridge;
return {
bridge,
+ create,
+ kill,
viewMenuPushes,
dispatchMenuAction(action: string) {
for (const cb of menuHandlers) cb(action);
@@ -94,35 +121,56 @@ function makeBridge() {
};
}
-function renderDock(visible: boolean) {
+function renderDock(visible: boolean, launch?: { prompt: string; nonce: number } | null) {
const onVisibleChange = mock((_v: boolean) => {});
- const { bridge, viewMenuPushes, dispatchMenuAction } = makeBridge();
- const ui = (v: boolean) => (
- <TerminalDock bridge={bridge} visible={v} onVisibleChange={onVisibleChange}>
+ const { bridge, create, kill, viewMenuPushes, dispatchMenuAction } = makeBridge();
+ const ui = (v: boolean, l?: { prompt: string; nonce: number } | null) => (
+ <TerminalDock bridge={bridge} visible={v} onVisibleChange={onVisibleChange} launch={l ?? null}>
<div data-testid="editor-child" />
</TerminalDock>
);
- const utils = render(ui(visible));
+ const utils = render(ui(visible, launch));
return {
...utils,
onVisibleChange,
+ create,
+ kill,
viewMenuPushes,
dispatchMenuAction,
- rerender: (v: boolean) => utils.rerender(ui(v)),
+ rerender: (v: boolean, l?: { prompt: string; nonce: number } | null) =>
+ utils.rerender(ui(v, l)),
};
}
+function sessionPanels(): HTMLElement[] {
+ return Array.from(document.querySelectorAll<HTMLElement>('[data-terminal-session]'));
+}
+
+function activePanelId(): string | null {
+ const active = document.querySelector<HTMLElement>(
+ '[data-terminal-session][data-state="active"]',
+ );
+ return active?.getAttribute('data-terminal-session') ?? null;
+}
+
+function launchNonceOf(panelId: string | null): string | null {
+ if (panelId === null) return null;
+ return (
+ document
+ .querySelector(`[data-terminal-session="${panelId}"] [data-testid="terminal-session"]`)
+ ?.getAttribute('data-launch') ?? null
+ );
+}
+
function editorRegion(): HTMLElement {
const region = screen.getByTestId('editor-child').parentElement;
if (region == null) throw new Error('editor region not found');
return region;
}
-describe('TerminalDock', () => {
+describe('TerminalDock multi-session', () => {
beforeEach(() => {
terminalPanelProps = null;
- lastTerminalPanelProps = null;
- written = [];
panelHandle.collapse.mockClear();
panelHandle.resize.mockClear();
panelHandle.expand.mockClear();
@@ -132,155 +180,422 @@ describe('TerminalDock', () => {
cleanup();
});
- test('wraps the editor in a vertical group with a collapsible bottom terminal panel', () => {
- renderDock(false);
-
- expect(screen.getByTestId('editor-child')).toBeTruthy();
- expect(screen.getByTestId('rrp-group').getAttribute('data-orientation')).toBe('vertical');
- expect(screen.getByTestId('terminal-resize-handle')).toBeTruthy();
-
- expect(terminalPanelProps?.collapsible).toBe(true);
- expect(terminalPanelProps?.collapsedSize).toBe(0);
- expect(terminalPanelProps?.minSize).toBe('120px');
- expect(terminalPanelProps?.maxSize).toBe('50%');
- expect(terminalPanelProps?.defaultSize).toBe(0);
- expect(terminalPanelProps?.inert).toBe(true);
- });
-
- test('does not mount the terminal (no PTY) until first opened, then keeps it mounted on hide', () => {
+ test('mounts no session until first opened, then keeps the session mounted on hide', () => {
const view = renderDock(false);
- expect(screen.queryByTestId('terminal-panel')).toBeNull();
+ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);
act(() => view.rerender(true));
- expect(screen.getByTestId('terminal-panel')).toBeTruthy();
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
act(() => view.rerender(false));
- expect(screen.getByTestId('terminal-panel')).toBeTruthy();
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
});
- test('opening restores the persisted height; hiding collapses the panel', () => {
+ test('opening the dock creates a session and spawns its PTY', () => {
const view = renderDock(false);
- panelHandle.resize.mockClear();
- panelHandle.collapse.mockClear();
+ expect(view.create).not.toHaveBeenCalled();
act(() => view.rerender(true));
- expect(panelHandle.resize).toHaveBeenCalledWith('240px');
- act(() => view.rerender(false));
- expect(panelHandle.collapse).toHaveBeenCalledTimes(1);
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ expect(view.create).toHaveBeenCalledTimes(1);
});
- test('reflects collapsed state via inert as the panel opens and closes', () => {
+ test('the new-terminal control adds a session, activates it, and spawns its PTY', async () => {
+ const user = userEvent.setup();
const view = renderDock(true);
- expect(terminalPanelProps?.inert).toBeFalsy();
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ const firstActive = activePanelId();
- act(() => view.rerender(false));
- expect(terminalPanelProps?.inert).toBe(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
+ expect(activePanelId()).not.toBe(firstActive);
+ expect(view.create).toHaveBeenCalledTimes(2);
});
- test('persists height only on user drag, never on an imperative open', async () => {
- const view = renderDock(false);
+ test('all sessions stay mounted with exactly one active', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(3);
+ const tabpanels = screen.getAllByRole('tabpanel', { hidden: true });
+ expect(tabpanels).toHaveLength(3);
+ expect(document.querySelectorAll('[data-terminal-session][data-state="active"]')).toHaveLength(
+ 1,
+ );
+ });
- act(() => view.rerender(true));
- expect(written).toEqual([]);
+ test('switching tabs changes the active session without unmounting the others', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ const secondActive = activePanelId();
+
+ await user.click(screen.getByRole('tab', { name: 'Terminal 1' }));
+
+ expect(activePanelId()).not.toBe(secondActive);
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
+ });
+
+ test('typing target stays scoped: the active panel is the only one shown', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
- fireEvent.pointerDown(screen.getByTestId('terminal-resize-handle'));
- act(() => terminalPanelProps?.onResize?.({ asPercentage: 35, inPixels: 300 } as Size));
- await waitFor(() => expect(written).toContain(300));
- fireEvent.pointerUp(window);
+ expect(sessionPanels()).toHaveLength(2);
+ const activeCount = document.querySelectorAll(
+ '[data-terminal-session][data-state="active"]',
+ ).length;
+ expect(activeCount).toBe(1);
});
- test('drag-collapsing the panel reports the hidden state to the parent', () => {
+ test('selecting a tab moves focus to that session', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ const second = activePanelId();
+
+ await user.click(screen.getByRole('tab', { name: 'Terminal 1' }));
+ const first = activePanelId();
+ expect(first).not.toBe(second);
+
+ const focusSink = document.querySelector<HTMLElement>(
+ `[data-terminal-session="${first}"] .xterm-helper-textarea`,
+ );
+ expect(document.activeElement).toBe(focusSink);
+ });
+
+ test('closing a non-active tab removes only it and leaves the active one running', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ const activeBefore = activePanelId();
+
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
+
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ expect(activePanelId()).toBe(activeBefore);
+ });
+
+ test("closing a tab reaps only that session's PTY and leaves the others alive", async () => {
+ const user = userEvent.setup();
const view = renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await waitFor(() => expect(view.create).toHaveBeenCalledTimes(2));
+ expect(view.kill).not.toHaveBeenCalled();
- fireEvent.pointerDown(screen.getByTestId('terminal-resize-handle'));
- act(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 } as Size));
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
- fireEvent.pointerUp(window);
+ await waitFor(() => expect(view.kill).toHaveBeenCalledWith('pty-1'));
+ expect(view.kill).not.toHaveBeenCalledWith('pty-2');
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ });
+
+ test('closing the active tab activates its left neighbor', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('tab', { name: 'Terminal 2' }));
+ const middle = activePanelId();
+
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 2' }));
+
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
+ const nowActive = activePanelId();
+ expect(nowActive).not.toBe(middle);
+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(
+ 'true',
+ );
+ });
+
+ test('closing the active leftmost tab activates its right neighbor', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('tab', { name: 'Terminal 1' }));
+ const closedId = activePanelId();
+ const rightNeighborId =
+ sessionPanels()
+ .map((el) => el.getAttribute('data-terminal-session'))
+ .find((id) => id !== closedId) ?? null;
+
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
+
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ expect(activePanelId()).toBe(rightNeighborId);
+ });
+
+ test('closing the active tab moves focus into the surviving neighbor', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('tab', { name: 'Terminal 2' }));
+
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 2' }));
+
+ const nowActive = activePanelId();
+ const focusSink = document.querySelector<HTMLElement>(
+ `[data-terminal-session="${nowActive}"] .xterm-helper-textarea`,
+ );
+ await waitFor(() => expect(document.activeElement).toBe(focusSink));
});
- test('returns focus to the editor when the terminal collapses (no keyboard strand)', () => {
+ test('closing the last tab collapses the dock and returns focus to the editor', async () => {
+ const user = userEvent.setup();
const view = renderDock(true);
- const term = screen.getByTestId('terminal-panel');
- act(() => term.focus());
- expect(document.getElementById(TERMINAL_PANEL_ID)?.contains(document.activeElement)).toBe(true);
+ act(() => screen.getByTestId('terminal-session').focus());
- act(() => view.rerender(false));
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
+ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);
+ expect(view.onVisibleChange).toHaveBeenCalledWith(false);
expect(document.activeElement).toBe(editorRegion());
});
- test('focuses the terminal on reveal so the user can type immediately', () => {
+ test('hiding the dock preserves every session and keeps the last-active tab on reopen', async () => {
+ const user = userEvent.setup();
const view = renderDock(true);
- const term = screen.getByTestId('terminal-panel');
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('tab', { name: 'Terminal 2' }));
+ const activeBeforeHide = activePanelId();
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(3);
act(() => view.rerender(false));
- expect(document.activeElement).toBe(editorRegion());
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(3);
+ expect(view.kill).not.toHaveBeenCalled();
act(() => view.rerender(true));
- expect(document.activeElement).toBe(term);
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(3);
+ expect(activePanelId()).toBe(activeBeforeHide);
+ expect(screen.getByRole('tab', { name: 'Terminal 2' }).getAttribute('aria-selected')).toBe(
+ 'true',
+ );
});
- test('does not pass an Escape handler to the gate — Escape reaches the shell, ⌘J is the exit', () => {
- renderDock(true);
- screen.getByTestId('terminal-panel'); // mounted
+ test('a launch intent opens a session carrying that intent', () => {
+ const view = renderDock(false);
+ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);
+
+ act(() => view.rerender(true, { prompt: 'work on docs', nonce: 7 }));
- expect(lastTerminalPanelProps?.onEscape).toBeUndefined();
+ const session = screen.getByTestId('terminal-session');
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ expect(session.getAttribute('data-launch')).toBe('7');
});
- test('the "Close terminal" affordance collapses the dock and returns focus to the editor', () => {
+ test('cold-start with visible=true seeds exactly one session carrying the launch intent', () => {
+ renderDock(true, { prompt: 'work on docs', nonce: 9 });
+ const sessions = screen.getAllByTestId('terminal-session');
+ expect(sessions).toHaveLength(1);
+ expect(sessions[0]?.getAttribute('data-launch')).toBe('9');
+ });
+
+ test('a launch while a tab is running opens a NEW tab and leaves the running one untouched', () => {
const view = renderDock(true);
- act(() => screen.getByTestId('terminal-panel').focus());
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ const runningId = activePanelId();
+ expect(launchNonceOf(runningId)).toBe('none');
- act(() => lastTerminalPanelProps?.onClose?.());
+ act(() => view.rerender(true, { prompt: 'work on docs', nonce: 1 }));
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
- expect(document.activeElement).toBe(editorRegion());
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
+ const launchedId = activePanelId();
+ expect(launchedId).not.toBe(runningId);
+ expect(launchNonceOf(launchedId)).toBe('1');
+ expect(launchNonceOf(runningId)).toBe('none');
});
- test('the trash/kill affordance unmounts the terminal, hides the dock, and returns focus', () => {
+ test('distinct launch nonces each open their own tab', () => {
const view = renderDock(true);
- act(() => screen.getByTestId('terminal-panel').focus());
- act(() => lastTerminalPanelProps?.onKill?.());
+ act(() => view.rerender(true, { prompt: 'a', nonce: 1 }));
+ act(() => view.rerender(true, { prompt: 'b', nonce: 2 }));
- expect(screen.queryByTestId('terminal-panel')).toBeNull();
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
- expect(document.activeElement).toBe(editorRegion());
- expect(view.viewMenuPushes.at(-1)).toEqual({ terminalLive: false });
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(3);
});
- test('reopening after a kill spawns a fresh terminal — unlike collapse, the session is gone', () => {
+ test('a repeated launch with the same nonce does not open a second tab', () => {
const view = renderDock(true);
- act(() => lastTerminalPanelProps?.onKill?.());
- act(() => view.rerender(false));
- expect(screen.queryByTestId('terminal-panel')).toBeNull();
+ act(() => view.rerender(true, { prompt: 'a', nonce: 1 }));
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
- act(() => view.rerender(true));
- expect(screen.getByTestId('terminal-panel')).toBeTruthy();
+ act(() => view.rerender(true, { prompt: 'a', nonce: 1 }));
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
});
- test('the Terminal menu "Kill Terminal" action unmounts the terminal and hides the dock', () => {
+ test('the Terminal menu "New Terminal" action adds a tab and activates it', () => {
const view = renderDock(true);
- expect(screen.getByTestId('terminal-panel')).toBeTruthy();
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ const firstActive = activePanelId();
+
+ act(() => view.dispatchMenuAction('new-terminal'));
+
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
+ expect(activePanelId()).not.toBe(firstActive);
+ expect(view.create).toHaveBeenCalledTimes(2);
+ });
+
+ test('the Terminal menu "Kill Terminal" action closes the active tab', async () => {
+ const user = userEvent.setup();
+ const view = renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);
act(() => view.dispatchMenuAction('kill-terminal'));
- expect(screen.queryByTestId('terminal-panel')).toBeNull();
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
- expect(view.viewMenuPushes.at(-1)).toEqual({ terminalLive: false });
+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
+ });
+
+ test('Cmd+number jumps to the matching tab while the terminal is focused', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ const panels = sessionPanels();
+ const thirdSink = panels[2]?.querySelector<HTMLElement>('.xterm-helper-textarea');
+ act(() => thirdSink?.focus());
+ expect(activePanelId()).toBe(panels[2]?.getAttribute('data-terminal-session'));
+
+ const event = new KeyboardEvent('keydown', {
+ key: '1',
+ metaKey: true,
+ cancelable: true,
+ bubbles: true,
+ });
+ act(() => {
+ window.dispatchEvent(event);
+ });
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(
+ 'true',
+ );
+ expect(activePanelId()).toBe(panels[0]?.getAttribute('data-terminal-session'));
+ });
+
+ test('Cmd+number for a tab that does not exist is left for the shell', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ const panels = sessionPanels();
+ act(() => panels[1]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());
+ const before = activePanelId();
+
+ const event = new KeyboardEvent('keydown', {
+ key: '5',
+ metaKey: true,
+ cancelable: true,
+ bubbles: true,
+ });
+ act(() => {
+ window.dispatchEvent(event);
+ });
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(activePanelId()).toBe(before);
+ });
+
+ test('Cmd+number is ignored when focus is outside the terminal dock', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ await user.click(screen.getByRole('tab', { name: 'Terminal 1' }));
+ const before = activePanelId();
+
+ act(() => editorRegion().focus());
+ const event = new KeyboardEvent('keydown', {
+ key: '2',
+ metaKey: true,
+ cancelable: true,
+ bubbles: true,
+ });
+ act(() => {
+ window.dispatchEvent(event);
+ });
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(activePanelId()).toBe(before);
+ });
+
+ test('a non-chord keystroke is not intercepted so it reaches the active shell', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+ const before = activePanelId();
+ act(() => sessionPanels()[0]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());
+
+ const escapeEvent = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ cancelable: true,
+ bubbles: true,
+ });
+ const digitEvent = new KeyboardEvent('keydown', {
+ key: '1',
+ cancelable: true,
+ bubbles: true,
+ });
+ act(() => {
+ window.dispatchEvent(escapeEvent);
+ window.dispatchEvent(digitEvent);
+ });
+
+ expect(escapeEvent.defaultPrevented).toBe(false);
+ expect(digitEvent.defaultPrevented).toBe(false);
+ expect(activePanelId()).toBe(before);
});
- test('reports terminal liveness to the View menu — true once mounted, false after a kill', () => {
+ test('reports terminal liveness — true once a session exists, false after the last closes', async () => {
+ const user = userEvent.setup();
const view = renderDock(false);
expect(view.viewMenuPushes.at(-1)).toEqual({ terminalLive: false });
act(() => view.rerender(true));
expect(view.viewMenuPushes.at(-1)).toEqual({ terminalLive: true });
- act(() => view.dispatchMenuAction('kill-terminal'));
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
expect(view.viewMenuPushes.at(-1)).toEqual({ terminalLive: false });
});
+
+ test('wires each tab to its panel via accessible tablist/tabpanel relationships', async () => {
+ const user = userEvent.setup();
+ renderDock(true);
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+
+ const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });
+ const tabs = within(tablist).getAllByRole('tab');
+ expect(tabs).toHaveLength(2);
+ for (const tab of tabs) {
+ const panelId = tab.getAttribute('aria-controls');
+ expect(panelId).toBeTruthy();
+ expect(document.getElementById(panelId ?? '')).not.toBeNull();
+ }
+ });
+
+ test('persists the bottom panel config (collapsible, sized, inert when hidden)', () => {
+ renderDock(false);
+ expect(terminalPanelProps?.collapsible).toBe(true);
+ expect(terminalPanelProps?.collapsedSize).toBe(0);
+ expect(terminalPanelProps?.minSize).toBe('120px');
+ expect(terminalPanelProps?.maxSize).toBe('50%');
+ expect(terminalPanelProps?.defaultSize).toBe(0);
+ expect(terminalPanelProps?.inert).toBe(true);
+ });
+
+ test('focuses the active session on reveal so the user can type immediately', () => {
+ const view = renderDock(true);
+ const session = screen.getByTestId('terminal-session');
+
+ act(() => view.rerender(false));
+ expect(document.activeElement).toBe(editorRegion());
+
+ act(() => view.rerender(true));
+ expect(document.activeElement).toBe(session);
+ });
});
diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsx
index 1ba5fb5bc..1a6940d2b 100644
--- a/packages/app/src/components/TerminalDock.tsx
+++ b/packages/app/src/components/TerminalDock.tsx
@@ -1,14 +1,42 @@
+import { useLingui } from '@lingui/react/macro';
+import { useTheme } from 'next-themes';
import { type ReactNode, useEffect, useLayoutEffect, 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 { 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. */
+interface TerminalSessionDescriptor {
+ readonly id: string;
+ readonly launch: TerminalLaunchIntent | 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;
@@ -24,10 +52,57 @@ export function TerminalDock({
onVisibleChange,
launch = null,
}: TerminalDockProps) {
+ const { t } = useLingui();
+ const { resolvedTheme } = useTheme();
const panelRef = usePanelRef();
const editorRegionRef = useRef<HTMLDivElement | null>(null);
const [isCollapsed, setIsCollapsed] = useState(!visible);
- const [mounted, setMounted] = useState(visible);
+
+ const [sessions, setSessions] = useState<readonly TerminalSessionDescriptor[]>(() =>
+ visible ? [{ id: makeSessionId(1), launch }] : [],
+ );
+ const [activeSessionId, setActiveSessionId] = useState(() => (visible ? makeSessionId(1) : ''));
+ const activeSessionIdRef = useRef(activeSessionId);
+ const sessionsRef = useRef(sessions);
+ const sessionCounterRef = useRef(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 }]);
+ setActiveSessionId(id);
+ }
+ 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 [initialHeightPx] = useState(() => getInitialTerminalHeight());
const heightPxRef = useRef(initialHeightPx);
@@ -56,29 +131,46 @@ export function TerminalDock({
);
useEffect(() => {
- if (visible) setMounted(true);
- }, [visible]);
-
- function killTerminal() {
- setMounted(false);
- onVisibleChange(false);
- editorRegionRef.current?.focus();
- }
+ const wasVisible = prevVisibleRef.current;
+ prevVisibleRef.current = visible;
- const killTerminalRef = useRef(killTerminal);
- useEffect(() => {
- killTerminalRef.current = killTerminal;
- });
+ 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]);
useEffect(() => {
return bridge.onMenuAction((action) => {
- if (action === 'kill-terminal') killTerminalRef.current();
+ if (action === 'new-terminal') openSessionRef.current(null);
+ else if (action === 'kill-terminal') closeActiveRef.current();
});
}, [bridge]);
useEffect(() => {
- bridge.editor.notifyViewMenuStateChanged({ terminalLive: mounted });
- }, [bridge, mounted]);
+ 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;
@@ -97,12 +189,16 @@ export function TerminalDock({
editorRegionRef.current?.focus();
}, [isCollapsed]);
- useLayoutEffect(() => {
+ useEffect(() => {
if (isCollapsed) return;
- const panelEl = document.getElementById(TERMINAL_PANEL_ID);
- panelEl?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus();
+ focusTerminalSession(activeSessionIdRef.current);
}, [isCollapsed]);
+ const tabDescriptors = sessions.map((session, index) => ({
+ id: session.id,
+ label: t`Terminal ${index + 1}`,
+ }));
+
return (
<ResizablePanelGroup
orientation="vertical"
@@ -137,6 +233,7 @@ export function TerminalDock({
/>
<ResizablePanel
id={TERMINAL_PANEL_ID}
+ style={{ backgroundColor: xtermThemeForMode(resolvedTheme).background }}
panelRef={panelRef}
defaultSize={visible ? `${initialHeightPx}px` : 0}
minSize="120px"
@@ -162,16 +259,32 @@ export function TerminalDock({
'transition-[flex-grow] duration-150 ease-out motion-reduce:transition-none motion-reduce:duration-0',
)}
>
- {mounted ? (
- <TerminalGate
- bridge={bridge}
- launch={launch}
- onClose={() => {
- onVisibleChange(false);
- editorRegionRef.current?.focus();
- }}
- onKill={killTerminal}
- />
+ {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}
+ onClose={() => closeSession(session.id)}
+ />
+ </TabsContent>
+ ))}
+ </TerminalTabStrip>
) : null}
</ResizablePanel>
</ResizablePanelGroup>
diff --git a/packages/app/src/components/TerminalGate.dom.test.tsx b/packages/app/src/components/TerminalGate.dom.test.tsx
index 471b4c7c0..b17e075a3 100644
--- a/packages/app/src/components/TerminalGate.dom.test.tsx
+++ b/packages/app/src/components/TerminalGate.dom.test.tsx
@@ -70,15 +70,13 @@ describe('TerminalGate', () => {
expect(notice()).toBeNull();
});
- test('forwards onClose, onKill, and the launch intent to the mounted terminal panel', async () => {
+ test('forwards onClose and the launch intent to the mounted terminal panel', async () => {
const onClose = mock(() => {});
- const onKill = mock(() => {});
const launch = { prompt: 'work on docs/notes', nonce: 1 };
consentState = { enabled: null, synced: true };
- render(<TerminalGate bridge={bridge} onClose={onClose} onKill={onKill} launch={launch} />);
+ render(<TerminalGate bridge={bridge} onClose={onClose} launch={launch} />);
await screen.findByTestId('terminal-panel');
expect(lastPanelProps?.onClose).toBe(onClose);
- expect(lastPanelProps?.onKill).toBe(onKill);
expect(lastPanelProps?.launch).toBe(launch);
});
diff --git a/packages/app/src/components/TerminalGate.tsx b/packages/app/src/components/TerminalGate.tsx
index c50d2c94e..5cbbb075c 100644
--- a/packages/app/src/components/TerminalGate.tsx
+++ b/packages/app/src/components/TerminalGate.tsx
@@ -14,11 +14,10 @@ const TerminalPanel = lazy(() =>
interface TerminalGateProps {
readonly bridge: OkDesktopBridge;
readonly onClose?: () => void;
- readonly onKill?: () => void;
readonly launch?: TerminalLaunchIntent | null;
}
-export function TerminalGate({ bridge, onClose, onKill, launch = null }: TerminalGateProps) {
+export function TerminalGate({ bridge, onClose, launch = null }: TerminalGateProps) {
const { enabled, synced } = useTerminalConsentState();
const writer = useTerminalEnabledWriter();
const { t } = useLingui();
@@ -47,13 +46,7 @@ export function TerminalGate({ bridge, onClose, onKill, launch = null }: Termina
}}
>
<Suspense fallback={<div className="h-full w-full bg-background" aria-hidden="true" />}>
- <TerminalPanel
- bridge={bridge}
- className="h-full"
- onClose={onClose}
- onKill={onKill}
- launch={launch}
- />
+ <TerminalPanel bridge={bridge} className="h-full" onClose={onClose} launch={launch} />
</Suspense>
</ErrorBoundary>
);
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index c41bf40a8..f380b06bc 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -146,6 +146,7 @@ describe('TerminalPanel', () => {
expect(lastTerm?.options.screenReaderMode).toBe(true);
expect(lastTerm?.options.minimumContrastRatio).toBe(4.5);
expect(lastTerm?.unicode.activeVersion).toBe('11');
+ expect(lastTerm?.options.scrollback).toBe(10000);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
expect(terminal.create).toHaveBeenCalledWith({ cols: 80, rows: 24 });
@@ -441,23 +442,6 @@ describe('TerminalPanel', () => {
expect(screen.getByRole('alert')).toBeTruthy();
});
- test('renders a kill control with an accessible name that invokes onKill when clicked', async () => {
- const onKill = mock(() => {});
- const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
- render(<TerminalPanel bridge={bridge} onKill={onKill} />);
-
- const kill = await screen.findByRole('button', { name: 'Kill Terminal' });
- fireEvent.click(kill);
- expect(onKill).toHaveBeenCalledTimes(1);
- });
-
- test('omits the kill control when no onKill is provided', async () => {
- const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
- render(<TerminalPanel bridge={bridge} />);
- await waitFor(() => expect(lastTerm).not.toBeNull());
- expect(screen.queryByRole('button', { name: 'Kill Terminal' })).toBeNull();
- });
-
test('constructs xterm with the palette for the resolved app theme', async () => {
mockResolvedTheme = 'light';
const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
@@ -492,4 +476,52 @@ describe('TerminalPanel', () => {
expect(terminal.create).toHaveBeenCalledTimes(1);
expect(terminal.kill).not.toHaveBeenCalled();
});
+
+ test('restarting one session spawns a fresh PTY for it without disturbing a sibling', async () => {
+ const exitSubs: Array<(m: OkPtyExit) => void> = [];
+ let created = 0;
+ const create = mock(async () => {
+ created += 1;
+ return { ok: true as const, ptyId: `pty-${created}` };
+ });
+ const kill = mock(async (_id: string) => {});
+ const terminal = {
+ create,
+ input: mock(() => {}),
+ resize: mock(() => {}),
+ kill,
+ drain: mock(() => {}),
+ onData: mock(() => mock(() => {})),
+ onExit: mock((cb: (m: OkPtyExit) => void) => {
+ exitSubs.push(cb);
+ return mock(() => {});
+ }),
+ claudePreflight: mock(async () => WIRED),
+ rewireClaudeMcp: mock(async () => WIRED),
+ };
+ const bridge = {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge;
+ const pushExit = (m: OkPtyExit) => {
+ for (const f of exitSubs) f(m);
+ };
+
+ render(
+ <>
+ <TerminalPanel bridge={bridge} />
+ <TerminalPanel bridge={bridge} />
+ </>,
+ );
+ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));
+
+ act(() => pushExit({ ptyId: 'pty-1', exitCode: 1, signal: null }));
+ expect(screen.getAllByRole('alert')).toHaveLength(1);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Restart terminal' }));
+ await waitFor(() => expect(create).toHaveBeenCalledTimes(3));
+
+ expect(kill).not.toHaveBeenCalledWith('pty-2');
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ });
});
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index a3d4b44d2..603a76e9c 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -7,10 +7,8 @@ import { Unicode11Addon } from '@xterm/addon-unicode11';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { WebglAddon } from '@xterm/addon-webgl';
import { Terminal } from '@xterm/xterm';
-import { Trash2 } from 'lucide-react';
import { useTheme } from 'next-themes';
import { useEffect, useRef, useState } from 'react';
-import { Button } from '@/components/ui/button';
import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { cn } from '@/lib/utils';
import { ClaudeReadinessBanner } from './ClaudeReadinessBanner';
@@ -25,7 +23,6 @@ interface TerminalPanelProps {
readonly bridge: OkDesktopBridge;
readonly className?: string;
readonly onClose?: () => void;
- readonly onKill?: () => void;
readonly onExit?: (info: { readonly exitCode: number; readonly signal: number | null }) => void;
readonly launch?: TerminalLaunchIntent | null;
}
@@ -34,7 +31,6 @@ export function TerminalPanel({
bridge,
className,
onClose,
- onKill,
onExit,
launch = null,
}: TerminalPanelProps) {
@@ -47,21 +43,8 @@ export function TerminalPanel({
style={{ backgroundColor: xtermThemeForMode(resolvedTheme).background }}
className={cn('relative flex h-full w-full flex-col overflow-hidden', className)}
>
- {onKill ? (
- <div className="flex shrink-0 items-center justify-end px-1.5 py-1">
- <Button
- size="icon"
- variant="ghost"
- aria-label={t`Kill Terminal`}
- className="size-6 text-muted-foreground hover:text-foreground"
- onClick={onKill}
- >
- <Trash2 aria-hidden="true" className="size-4" />
- </Button>
- </div>
- ) : null}
{/* Positioning context for the session's absolute exit/refusal notices, so
- they cover the canvas area and not the kill control above. */}
+ they cover the canvas area. */}
<div className="relative min-h-0 flex-1">
<TerminalSession
key={restartKey}
@@ -127,6 +110,7 @@ function TerminalSession({
cursorBlink: true,
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, monospace',
fontSize: 13,
+ scrollback: 10000,
theme: xtermThemeForMode(initialResolvedThemeRef.current),
});
termRef.current = term;
@@ -139,9 +123,16 @@ function TerminalSession({
term.open(container);
try {
- term.loadAddon(new WebglAddon());
+ const webgl = new WebglAddon();
+ webgl.onContextLoss(() => {
+ console.warn('[terminal] WebGL context lost, falling back to DOM renderer');
+ webgl.dispose();
+ });
+ term.loadAddon(webgl);
} catch (err) {
- console.warn('[terminal] WebGL addon failed, using DOM renderer:', err);
+ const expected = err instanceof Error && /webgl2?|context/i.test(err.message);
+ const log = expected ? console.warn : console.error;
+ log('[terminal] WebGL addon failed, using DOM renderer:', err);
}
fit.fit();
@@ -151,6 +142,7 @@ function TerminalSession({
try {
result = await bridge.terminal.create({ cols: term.cols, rows: term.rows });
} catch (err) {
+ console.error('[terminal] create() failed:', err);
if (cancelled) return;
setExitInfo({
exitCode: 1,
diff --git a/packages/app/src/components/TerminalTabStrip.dom.test.tsx b/packages/app/src/components/TerminalTabStrip.dom.test.tsx
new file mode 100644
index 000000000..f1cc4cead
--- /dev/null
+++ b/packages/app/src/components/TerminalTabStrip.dom.test.tsx
@@ -0,0 +1,127 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { type TerminalTabDescriptor, TerminalTabStrip } from './TerminalTabStrip';
+
+const SESSIONS: readonly TerminalTabDescriptor[] = [
+ { id: 's1', label: 'Terminal 1' },
+ { id: 's2', label: 'Terminal 2' },
+ { id: 's3', label: 'Terminal 3' },
+];
+
+function renderStrip(props?: {
+ sessions?: readonly TerminalTabDescriptor[];
+ activeSessionId?: string;
+}) {
+ const onSelect = mock((_id: string) => {});
+ const onTabActivate = mock((_id: string) => {});
+ const onNew = mock(() => {});
+ const onClose = mock((_id: string) => {});
+ render(
+ <TerminalTabStrip
+ sessions={props?.sessions ?? SESSIONS}
+ activeSessionId={props?.activeSessionId ?? 's1'}
+ onSelect={onSelect}
+ onTabActivate={onTabActivate}
+ onNew={onNew}
+ onClose={onClose}
+ />,
+ );
+ return { onSelect, onTabActivate, onNew, onClose };
+}
+
+describe('TerminalTabStrip', () => {
+ afterEach(() => cleanup());
+
+ test('renders one tab per session inside a labeled tablist', () => {
+ renderStrip();
+ const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });
+ const tabs = within(tablist).getAllByRole('tab');
+ expect(tabs.map((tab) => tab.textContent)).toEqual(['Terminal 1', 'Terminal 2', 'Terminal 3']);
+ });
+
+ test('marks the active session as selected and leaves others unselected', () => {
+ renderStrip({ activeSessionId: 's2' });
+ expect(screen.getByRole('tab', { name: 'Terminal 2' }).getAttribute('aria-selected')).toBe(
+ 'true',
+ );
+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(
+ 'false',
+ );
+ expect(screen.getByRole('tab', { name: 'Terminal 3' }).getAttribute('aria-selected')).toBe(
+ 'false',
+ );
+ });
+
+ test('is fully controlled: clicking a tab reports onSelect without changing its own selection', async () => {
+ const user = userEvent.setup();
+ const { onSelect } = renderStrip({ activeSessionId: 's1' });
+
+ await user.click(screen.getByRole('tab', { name: 'Terminal 2' }));
+
+ expect(onSelect).toHaveBeenCalledWith('s2');
+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(
+ 'true',
+ );
+ expect(screen.getByRole('tab', { name: 'Terminal 2' }).getAttribute('aria-selected')).toBe(
+ 'false',
+ );
+ });
+
+ test('reports onTabActivate with the session id on click, but not on arrow-key nav', async () => {
+ const user = userEvent.setup();
+ const { onTabActivate } = renderStrip({ activeSessionId: 's1' });
+
+ await user.click(screen.getByRole('tab', { name: 'Terminal 2' }));
+ expect(onTabActivate).toHaveBeenCalledWith('s2');
+
+ onTabActivate.mockClear();
+ act(() => screen.getByRole('tab', { name: 'Terminal 2' }).focus());
+ await user.keyboard('{ArrowRight}');
+ expect(onTabActivate).not.toHaveBeenCalled();
+ });
+
+ test('arrow-key navigation reports the next session via onSelect', async () => {
+ const user = userEvent.setup();
+ const { onSelect } = renderStrip({ activeSessionId: 's1' });
+ const first = screen.getByRole('tab', { name: 'Terminal 1' });
+
+ act(() => {
+ first.focus();
+ });
+ expect(document.activeElement).toBe(first);
+ await user.keyboard('{ArrowRight}');
+
+ expect(onSelect).toHaveBeenCalledWith('s2');
+ });
+
+ test('the new-terminal control reports onNew and never onSelect', async () => {
+ const user = userEvent.setup();
+ const { onNew, onSelect } = renderStrip();
+
+ await user.click(screen.getByRole('button', { name: 'New Terminal' }));
+
+ expect(onNew).toHaveBeenCalledTimes(1);
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ test('a tab close control reports onClose with that session id only', async () => {
+ const user = userEvent.setup();
+ const { onClose, onSelect, onNew } = renderStrip({ activeSessionId: 's1' });
+
+ await user.click(screen.getByRole('button', { name: 'Close Terminal 2' }));
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onClose).toHaveBeenCalledWith('s2');
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onNew).not.toHaveBeenCalled();
+ });
+
+ test('every icon-only control exposes an accessible name', () => {
+ renderStrip();
+ expect(screen.getByRole('button', { name: 'New 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.tsx
new file mode 100644
index 000000000..36da633b0
--- /dev/null
+++ b/packages/app/src/components/TerminalTabStrip.tsx
@@ -0,0 +1,96 @@
+import { useLingui } from '@lingui/react/macro';
+import { 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 { cn } from '@/lib/utils';
+
+export interface TerminalTabDescriptor {
+ readonly id: string;
+ readonly label: string;
+}
+
+interface TerminalTabStripProps {
+ readonly sessions: readonly TerminalTabDescriptor[];
+ readonly activeSessionId: string;
+ readonly onSelect: (id: string) => void;
+ readonly onTabActivate?: (id: string) => void;
+ readonly onNew: () => void;
+ readonly onClose: (id: string) => void;
+ readonly children?: ReactNode;
+ readonly className?: string;
+}
+
+export function TerminalTabStrip({
+ sessions,
+ activeSessionId,
+ onSelect,
+ onTabActivate,
+ onNew,
+ onClose,
+ children,
+ className,
+}: TerminalTabStripProps) {
+ const { t } = useLingui();
+ return (
+ <Tabs
+ value={activeSessionId}
+ onValueChange={onSelect}
+ className={cn('flex min-h-0 min-w-0 flex-1 flex-col', className)}
+ >
+ <div className="flex shrink-0 flex-row items-center gap-1 px-1.5 py-1">
+ <TabsList
+ variant="line"
+ aria-label={t`Terminal sessions`}
+ className="flex h-auto min-w-0 flex-1 items-center justify-start gap-0.5 overflow-x-auto bg-transparent p-0 [scrollbar-width:none]"
+ >
+ {sessions.map((session) => {
+ const isActive = session.id === activeSessionId;
+ return (
+ <div
+ key={session.id}
+ className={cn(
+ 'flex shrink-0 items-center rounded-md pr-0.5 transition-colors',
+ isActive ? 'bg-muted' : 'hover:bg-muted/50',
+ )}
+ >
+ <TabsTrigger
+ value={session.id}
+ onClick={() => onTabActivate?.(session.id)}
+ className="h-7 flex-none rounded-md px-2 text-xs"
+ >
+ <span className="max-w-40 truncate">{session.label}</span>
+ </TabsTrigger>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t`Close ${session.label}`}
+ tabIndex={isActive ? 0 : -1}
+ className="text-muted-foreground hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ onClose(session.id);
+ }}
+ >
+ <XIcon aria-hidden="true" />
+ </Button>
+ </div>
+ );
+ })}
+ </TabsList>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t`New Terminal`}
+ className="shrink-0 text-muted-foreground hover:text-foreground"
+ onClick={onNew}
+ >
+ <PlusIcon aria-hidden="true" />
+ </Button>
+ </div>
+ {children}
+ </Tabs>
+ );
+}
diff --git a/packages/app/src/components/ui/tabs.tsx b/packages/app/src/components/ui/tabs.tsx
new file mode 100644
index 000000000..3596d6602
--- /dev/null
+++ b/packages/app/src/components/ui/tabs.tsx
@@ -0,0 +1,78 @@
+import { cva, type VariantProps } from 'class-variance-authority';
+import { Tabs as TabsPrimitive } from 'radix-ui';
+import type * as React from 'react';
+
+import { cn } from '@/lib/utils';
+
+function Tabs({
+ className,
+ orientation = 'horizontal',
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Root>) {
+ return (
+ <TabsPrimitive.Root
+ data-slot="tabs"
+ data-orientation={orientation}
+ className={cn('group/tabs flex gap-2 data-horizontal:flex-col', className)}
+ {...props}
+ />
+ );
+}
+
+const tabsListVariants = cva(
+ 'group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none',
+ {
+ variants: {
+ variant: {
+ default: 'bg-muted',
+ line: 'gap-1 bg-transparent',
+ },
+ },
+ defaultVariants: {
+ variant: 'default',
+ },
+ },
+);
+
+function TabsList({
+ className,
+ variant = 'default',
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {
+ return (
+ <TabsPrimitive.List
+ data-slot="tabs-list"
+ data-variant={variant}
+ className={cn(tabsListVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
+
+function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
+ return (
+ <TabsPrimitive.Trigger
+ data-slot="tabs-trigger"
+ className={cn(
+ "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ 'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',
+ 'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',
+ 'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
+ return (
+ <TabsPrimitive.Content
+ data-slot="tabs-content"
+ className={cn('flex-1 text-sm outline-none', className)}
+ {...props}
+ />
+ );
+}
+
+export { Tabs, TabsContent, TabsList, TabsTrigger, tabsListVariants };
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index f1d6b0c48..7191fe22a 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -70,6 +70,7 @@
"1EcCom": [["keyName"], " value"],
"1GhYxC": ["of ", ["totalPages"]],
"1HBhDS": ["Checking out files"],
+ "1MGRQl": ["Terminal sessions"],
"1QfxQT": ["Dismiss"],
"1RluQD": ["Show replace"],
"1TNIig": ["Open"],
@@ -197,7 +198,6 @@
"5Tk8Fb": ["Loading files"],
"5WDhAk": ["Link to a page or external URL."],
"5ZB7XC": ["File drop zone"],
- "5_j-DA": ["Kill Terminal"],
"5gr_ev": [
"Becomes the document's content when someone creates a doc from this template. Type <0>",
["dateToken"],
@@ -803,6 +803,7 @@
"ONPvOb": ["Loading agent activity"],
"ONgEZF": ["Loading headings for ", ["pageTarget"]],
"OTF92M": ["Label <0>(optional display text)</0>"],
+ "OVjNeX": ["Terminal ", ["0"]],
"OX2Neh": ["Inline code"],
"OYnx7O": ["Path cannot start with \"/\""],
"OdmsFg": ["Failed to delete item"],
@@ -1099,6 +1100,7 @@
"). Other files and writers are unaffected."
],
"ZBt4rI": ["Instruction for the AI"],
+ "ZBxvV3": ["New Terminal"],
"ZLQol-": ["You can turn this on later in <0>Settings → Sync</0>."],
"ZNK2Tq": ["root"],
"ZQLDTl": ["created folder"],
@@ -1581,6 +1583,7 @@
"Git identity isn't set — commits use a default author. Set yours so teammates see your name."
],
"nskygk": ["Choose agent"],
+ "nzHlj8": ["Close ", ["0"]],
"nzaV6Q": ["Page thumbnails"],
"o2yoFu": ["Reveal in Finder, No workspace"],
"o49mDZ": ["Loading timeline history"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index fee5414a4..89c4fc1f7 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1072,6 +1072,11 @@ msgstr "Cloning..."
msgid "Close"
msgstr "Close"
+#. placeholder {0}: session.label
+#: src/components/TerminalTabStrip.tsx
+msgid "Close {0}"
+msgstr "Close {0}"
+
#: src/components/EditorTabs.tsx
msgid "Close {accessibleLabel}"
msgstr "Close {accessibleLabel}"
@@ -3062,10 +3067,6 @@ msgstr "Key ending in {keyHint}"
msgid "Keyboard shortcuts available in the editor and workspace."
msgstr "Keyboard shortcuts available in the editor and workspace."
-#: src/components/TerminalPanel.tsx
-msgid "Kill Terminal"
-msgstr "Kill Terminal"
-
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Label <0>(optional display text)</0>"
msgstr "Label <0>(optional display text)</0>"
@@ -3545,6 +3546,10 @@ msgstr "New tab"
msgid "New template"
msgstr "New template"
+#: src/components/TerminalTabStrip.tsx
+msgid "New Terminal"
+msgstr "New Terminal"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr "Next match"
@@ -5550,6 +5555,11 @@ msgstr "Templates available"
msgid "Terminal"
msgstr "Terminal"
+#. placeholder {0}: index + 1
+#: src/components/TerminalDock.tsx
+msgid "Terminal {0}"
+msgstr "Terminal {0}"
+
#: src/components/TerminalRefusalNotice.tsx
msgid "Terminal access isn't enabled for this project."
msgstr "Terminal access isn't enabled for this project."
@@ -5562,6 +5572,10 @@ msgstr "Terminal disabled"
msgid "Terminal failed to load"
msgstr "Terminal failed to load"
+#: src/components/TerminalTabStrip.tsx
+msgid "Terminal sessions"
+msgstr "Terminal sessions"
+
#: src/components/settings/TerminalSection.tsx
#: src/components/TerminalGate.tsx
msgid "Terminal settings not loaded yet — try again in a moment."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 87b7326a1..d61c9ca25 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -70,6 +70,7 @@
"1EcCom": [["keyName"], " vàĺũē"],
"1GhYxC": ["ōƒ ", ["totalPages"]],
"1HBhDS": ["Ćĥēćķĩńĝ ōũţ ƒĩĺēś"],
+ "1MGRQl": ["Ţēŕḿĩńàĺ śēśśĩōńś"],
"1QfxQT": ["Ďĩśḿĩśś"],
"1RluQD": ["Śĥōŵ ŕēƥĺàćē"],
"1TNIig": ["Ōƥēń"],
@@ -197,7 +198,6 @@
"5Tk8Fb": ["Ĺōàďĩńĝ ƒĩĺēś"],
"5WDhAk": ["Ĺĩńķ ţō à ƥàĝē ōŕ ēxţēŕńàĺ ŨŔĹ."],
"5ZB7XC": ["Ƒĩĺē ďŕōƥ źōńē"],
- "5_j-DA": ["Ķĩĺĺ Ţēŕḿĩńàĺ"],
"5gr_ev": [
"ßēćōḿēś ţĥē ďōćũḿēńţ'ś ćōńţēńţ ŵĥēń śōḿēōńē ćŕēàţēś à ďōć ƒŕōḿ ţĥĩś ţēḿƥĺàţē. Ţŷƥē <0>",
["dateToken"],
@@ -803,6 +803,7 @@
"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],
"ONgEZF": ["Ĺōàďĩńĝ ĥēàďĩńĝś ƒōŕ ", ["pageTarget"]],
"OTF92M": ["Ĺàƀēĺ <0>(ōƥţĩōńàĺ ďĩśƥĺàŷ ţēxţ)</0>"],
+ "OVjNeX": ["Ţēŕḿĩńàĺ ", ["0"]],
"OX2Neh": ["Ĩńĺĩńē ćōďē"],
"OYnx7O": ["Ƥàţĥ ćàńńōţ śţàŕţ ŵĩţĥ \"/\""],
"OdmsFg": ["Ƒàĩĺēď ţō ďēĺēţē ĩţēḿ"],
@@ -1099,6 +1100,7 @@
"). Ōţĥēŕ ƒĩĺēś àńď ŵŕĩţēŕś àŕē ũńàƒƒēćţēď."
],
"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],
+ "ZBxvV3": ["Ńēŵ Ţēŕḿĩńàĺ"],
"ZLQol-": ["Ŷōũ ćàń ţũŕń ţĥĩś ōń ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],
"ZNK2Tq": ["ŕōōţ"],
"ZQLDTl": ["ćŕēàţēď ƒōĺďēŕ"],
@@ -1581,6 +1583,7 @@
"Ĝĩţ ĩďēńţĩţŷ ĩśń'ţ śēţ — ćōḿḿĩţś ũśē à ďēƒàũĺţ àũţĥōŕ. Śēţ ŷōũŕś śō ţēàḿḿàţēś śēē ŷōũŕ ńàḿē."
],
"nskygk": ["Ćĥōōśē àĝēńţ"],
+ "nzHlj8": ["Ćĺōśē ", ["0"]],
"nzaV6Q": ["Ƥàĝē ţĥũḿƀńàĩĺś"],
"o2yoFu": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, Ńō ŵōŕķśƥàćē"],
"o49mDZ": ["Ĺōàďĩńĝ ţĩḿēĺĩńē ĥĩśţōŕŷ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 65001188f..650600e9f 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1067,6 +1067,11 @@ msgstr ""
msgid "Close"
msgstr ""
+#. placeholder {0}: session.label
+#: src/components/TerminalTabStrip.tsx
+msgid "Close {0}"
+msgstr ""
+
#: src/components/EditorTabs.tsx
msgid "Close {accessibleLabel}"
msgstr ""
@@ -3057,10 +3062,6 @@ msgstr ""
msgid "Keyboard shortcuts available in the editor and workspace."
msgstr ""
-#: src/components/TerminalPanel.tsx
-msgid "Kill Terminal"
-msgstr ""
-
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Label <0>(optional display text)</0>"
msgstr ""
@@ -3540,6 +3541,10 @@ msgstr ""
msgid "New template"
msgstr ""
+#: src/components/TerminalTabStrip.tsx
+msgid "New Terminal"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr ""
@@ -5545,6 +5550,11 @@ msgstr ""
msgid "Terminal"
msgstr ""
+#. placeholder {0}: index + 1
+#: src/components/TerminalDock.tsx
+msgid "Terminal {0}"
+msgstr ""
+
#: src/components/TerminalRefusalNotice.tsx
msgid "Terminal access isn't enabled for this project."
msgstr ""
@@ -5557,6 +5567,10 @@ msgstr ""
msgid "Terminal failed to load"
msgstr ""
+#: src/components/TerminalTabStrip.tsx
+msgid "Terminal sessions"
+msgstr ""
+
#: src/components/settings/TerminalSection.tsx
#: src/components/TerminalGate.tsx
msgid "Terminal settings not loaded yet — try again in a moment."
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 786b921d9..00d083494 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -219,7 +219,11 @@ import {
DEFAULT_PTY_ROWS,
type PtyUtilityLike,
} from './terminal-manager.ts';
-import { recordShellExit, recordTerminalSession } from './terminal-telemetry.ts';
+import {
+ recordConcurrentSessions,
+ recordShellExit,
+ recordTerminalSession,
+} from './terminal-telemetry.ts';
import { applyThemeApplied } from './theme-applied-handler.ts';
import { applyThemeSource, isOkThemeSource } from './theme-handler.ts';
import {
@@ -1489,6 +1493,7 @@ function registerIpcHandlers() {
logger: { warn: (data) => getLogger('terminal').warn(data, 'unexpected pty-host message') },
recordShellExit,
recordTerminalSession,
+ recordConcurrentSessions,
});
terminalReaper = terminalManager;
diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.ts
index 93ea091dc..0aec91c9d 100644
--- a/packages/desktop/src/main/terminal-manager.ts
+++ b/packages/desktop/src/main/terminal-manager.ts
@@ -26,6 +26,7 @@ export interface TerminalManagerDeps {
logger?: { warn: (o: Record<string, unknown>) => void };
recordShellExit?: (info: { crashed: boolean }) => void;
recordTerminalSession?: () => void;
+ recordConcurrentSessions?: (info: { count: number }) => void;
}
interface TerminalCreateRequest {
@@ -45,10 +46,7 @@ type CreateResult =
| { readonly ok: true; readonly ptyId: string }
| { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };
-interface PtyWindowHandle {
- webContents: SendableWebContents;
- utility: PtyUtilityLike;
- ptyId: string | null;
+interface SessionState {
outbound: string;
flushToken: TimerToken | null;
pendingBytes: number;
@@ -56,6 +54,12 @@ interface PtyWindowHandle {
commandRan: boolean;
}
+interface PtyWindowHandle {
+ webContents: SendableWebContents;
+ utility: PtyUtilityLike;
+ sessions: Map<string, SessionState>;
+}
+
const DEFAULT_COALESCE_MS = 12;
const DEFAULT_HIGH_WATER = 1024 * 1024;
const DEFAULT_LOW_WATER = 256 * 1024;
@@ -99,7 +103,12 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
function safeKillUtility(handle: PtyWindowHandle): void {
try {
handle.utility.kill();
- } catch {}
+ } catch (err) {
+ const code = (err as { code?: string } | null)?.code;
+ if (code !== 'ESRCH') {
+ deps.logger?.warn({ event: 'terminal-manager-kill-failed', code: code ?? 'unknown' });
+ }
+ }
}
function pushData(handle: PtyWindowHandle, ptyId: string, data: string): void {
@@ -115,31 +124,32 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
deps.sendExit(handle.webContents, payload);
}
- function flush(windowId: number): void {
+ function flush(windowId: number, ptyId: string): void {
const handle = handles.get(windowId);
- if (!handle) return;
- handle.flushToken = null;
+ const session = handle?.sessions.get(ptyId);
+ if (!handle || !session) return;
+ session.flushToken = null;
if (handle.webContents.isDestroyed?.()) return;
- if (handle.outbound.length === 0 || handle.ptyId === null) return;
- const chunk = handle.outbound;
- handle.outbound = '';
- pushData(handle, handle.ptyId, chunk);
- handle.pendingBytes += chunk.length;
- if (!handle.paused && handle.pendingBytes > highWater) {
- handle.utility.postMessage({ type: 'pause', ptyId: handle.ptyId });
- handle.paused = true;
+ if (session.outbound.length === 0) return;
+ const chunk = session.outbound;
+ session.outbound = '';
+ pushData(handle, ptyId, chunk);
+ session.pendingBytes += chunk.length;
+ if (!session.paused && session.pendingBytes > highWater) {
+ handle.utility.postMessage({ type: 'pause', ptyId });
+ session.paused = true;
}
}
- function scheduleFlush(windowId: number, handle: PtyWindowHandle): void {
- if (handle.flushToken !== null) return;
- handle.flushToken = deps.setTimer(() => flush(windowId), coalesceMs);
+ function scheduleFlush(windowId: number, ptyId: string, session: SessionState): void {
+ if (session.flushToken !== null) return;
+ session.flushToken = deps.setTimer(() => flush(windowId, ptyId), coalesceMs);
}
- function clearFlush(handle: PtyWindowHandle): void {
- if (handle.flushToken !== null) {
- deps.clearTimer(handle.flushToken);
- handle.flushToken = null;
+ function clearFlush(session: SessionState): void {
+ if (session.flushToken !== null) {
+ deps.clearTimer(session.flushToken);
+ session.flushToken = null;
}
}
@@ -169,19 +179,20 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
deps.logger?.warn({ event: 'pty-host-unexpected-message', windowId });
return;
}
- if (handle.ptyId === null || message.ptyId !== handle.ptyId) return;
+ const session = handle.sessions.get(message.ptyId);
+ if (!session) return;
switch (message.type) {
case 'data':
- handle.outbound += message.data;
- scheduleFlush(windowId, handle);
+ session.outbound += message.data;
+ scheduleFlush(windowId, message.ptyId, session);
break;
case 'exit': {
- clearFlush(handle);
- flush(windowId);
const { ptyId } = message;
- maybeRecordSession(handle);
- resetPty(handle);
+ clearFlush(session);
+ flush(windowId, ptyId);
+ maybeRecordSession(session);
+ handle.sessions.delete(ptyId);
deps.recordShellExit?.({ crashed: false });
pushExit(handle, {
ptyId,
@@ -192,7 +203,8 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
}
case 'spawn-error': {
const { ptyId } = message;
- resetPty(handle);
+ clearFlush(session);
+ handle.sessions.delete(ptyId);
deps.recordShellExit?.({ crashed: true });
pushExit(handle, { ptyId, exitCode: 1, signal: null, error: message.message });
break;
@@ -203,11 +215,14 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
function onUtilityExit(windowId: number, code: number | null): void {
const handle = handles.get(windowId);
if (!handle) return;
- const ptyId = handle.ptyId;
- clearFlush(handle);
handles.delete(windowId);
- if (ptyId !== null) {
- maybeRecordSession(handle);
+ for (const [ptyId, session] of handle.sessions) {
+ clearFlush(session);
+ if (session.outbound.length > 0) {
+ pushData(handle, ptyId, session.outbound);
+ session.outbound = '';
+ }
+ maybeRecordSession(session);
deps.recordShellExit?.({ crashed: true });
pushExit(handle, {
ptyId,
@@ -216,19 +231,12 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
error: 'terminal host exited',
});
}
+ handle.sessions.clear();
}
- function resetPty(handle: PtyWindowHandle): void {
- handle.ptyId = null;
- handle.outbound = '';
- handle.pendingBytes = 0;
- handle.paused = false;
- handle.commandRan = false;
- }
-
- function maybeRecordSession(handle: PtyWindowHandle): void {
- if (!handle.commandRan) return;
- handle.commandRan = false;
+ function maybeRecordSession(session: SessionState): void {
+ if (!session.commandRan) return;
+ session.commandRan = false;
deps.recordTerminalSession?.();
}
@@ -242,12 +250,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
const handle: PtyWindowHandle = {
webContents: req.webContents,
utility,
- ptyId: null,
- outbound: '',
- flushToken: null,
- pendingBytes: 0,
- paused: false,
- commandRan: false,
+ sessions: new Map(),
};
handles.set(req.windowId, handle);
utility.on('message', (raw) => onUtilityMessage(req.windowId, raw));
@@ -260,9 +263,14 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
if (req.projectRoot === null) return { ok: false, reason: 'no-project' };
const handle = ensureHandle(req);
const ptyId = deps.newPtyId();
- clearFlush(handle);
- resetPty(handle);
- handle.ptyId = ptyId;
+ handle.sessions.set(ptyId, {
+ outbound: '',
+ flushToken: null,
+ pendingBytes: 0,
+ paused: false,
+ commandRan: false,
+ });
+ deps.recordConcurrentSessions?.({ count: handle.sessions.size });
handle.utility.postMessage({
type: 'create',
ptyId,
@@ -275,14 +283,15 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
input(req): void {
const handle = handles.get(req.windowId);
- if (!handle || handle.ptyId !== req.ptyId) return;
- if (!handle.commandRan && containsCommandSubmit(req.data)) handle.commandRan = true;
+ const session = handle?.sessions.get(req.ptyId);
+ if (!handle || !session) return;
+ if (!session.commandRan && containsCommandSubmit(req.data)) session.commandRan = true;
handle.utility.postMessage({ type: 'input', ptyId: req.ptyId, data: req.data });
},
resize(req): void {
const handle = handles.get(req.windowId);
- if (!handle || handle.ptyId !== req.ptyId) return;
+ if (!handle?.sessions.has(req.ptyId)) return;
handle.utility.postMessage({
type: 'resize',
ptyId: req.ptyId,
@@ -293,33 +302,38 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
kill(req): void {
const handle = handles.get(req.windowId);
- if (!handle || handle.ptyId !== req.ptyId) return;
+ if (!handle?.sessions.has(req.ptyId)) return;
handle.utility.postMessage({ type: 'kill', ptyId: req.ptyId });
},
drain(req): void {
const handle = handles.get(req.windowId);
- if (!handle || handle.ptyId !== req.ptyId) return;
- handle.pendingBytes = Math.max(0, handle.pendingBytes - req.bytes);
- if (handle.paused && handle.pendingBytes < lowWater) {
+ const session = handle?.sessions.get(req.ptyId);
+ if (!handle || !session) return;
+ session.pendingBytes = Math.max(0, session.pendingBytes - req.bytes);
+ if (session.paused && session.pendingBytes < lowWater) {
handle.utility.postMessage({ type: 'resume', ptyId: req.ptyId });
- handle.paused = false;
+ session.paused = false;
}
},
killForWindow(windowId): void {
const handle = handles.get(windowId);
if (!handle) return;
- clearFlush(handle);
- maybeRecordSession(handle);
+ for (const session of handle.sessions.values()) {
+ clearFlush(session);
+ maybeRecordSession(session);
+ }
handles.delete(windowId);
safeKillUtility(handle);
},
killAll(): void {
for (const handle of handles.values()) {
- clearFlush(handle);
- maybeRecordSession(handle);
+ for (const session of handle.sessions.values()) {
+ clearFlush(session);
+ maybeRecordSession(session);
+ }
safeKillUtility(handle);
}
handles.clear();
diff --git a/packages/desktop/src/main/terminal-telemetry.ts b/packages/desktop/src/main/terminal-telemetry.ts
index f23a51a15..2021ac856 100644
--- a/packages/desktop/src/main/terminal-telemetry.ts
+++ b/packages/desktop/src/main/terminal-telemetry.ts
@@ -11,3 +11,11 @@ export function recordShellExit(info: { crashed: boolean }): void {
export function recordTerminalSession(): void {
withSpanSync('ok.desktop.terminalSession', {}, () => undefined);
}
+
+export function recordConcurrentSessions(info: { count: number }): void {
+ withSpanSync(
+ 'ok.desktop.terminalConcurrentSessions',
+ { attributes: { 'ok.desktop.concurrent_sessions': info.count } },
+ () => undefined,
+ );
+}
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
index 62bceb169..4a9d5303c 100644
--- a/packages/desktop/src/utility/pty-host.ts
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -99,10 +99,27 @@ export interface SetupPtyHostDeps {
function asIncomingMessage(raw: unknown): PtyHostIncomingMessage | null {
if (typeof raw !== 'object' || raw === null) return null;
- const { type, ptyId } = raw as { type?: unknown; ptyId?: unknown };
- if (typeof type !== 'string') return null;
- if (typeof ptyId !== 'string' || ptyId.length === 0) return null;
- return raw as PtyHostIncomingMessage;
+ const m = raw as Record<string, unknown>;
+ if (typeof m.type !== 'string') return null;
+ if (typeof m.ptyId !== 'string' || m.ptyId.length === 0) return null;
+ switch (m.type) {
+ case 'create':
+ return typeof m.cwd === 'string' && typeof m.cols === 'number' && typeof m.rows === 'number'
+ ? (raw as PtyHostIncomingMessage)
+ : null;
+ case 'input':
+ return typeof m.data === 'string' ? (raw as PtyHostIncomingMessage) : null;
+ case 'resize':
+ return typeof m.cols === 'number' && typeof m.rows === 'number'
+ ? (raw as PtyHostIncomingMessage)
+ : null;
+ case 'kill':
+ case 'pause':
+ case 'resume':
+ return raw as PtyHostIncomingMessage;
+ default:
+ return null;
+ }
}
export interface PtyHostHandle {
@@ -130,7 +147,7 @@ export function buildShellEnv(
export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
const env = deps.env ?? (process.env as Record<string, string | undefined>);
- let active: { ptyId: string; pty: PtyProcessLike } | null = null;
+ const sessions = new Map<string, PtyProcessLike>();
function post(message: PtyHostOutgoingMessage): void {
deps.parentPort?.postMessage(message);
@@ -139,13 +156,20 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
function safeKill(pty: PtyProcessLike): void {
try {
pty.kill();
- } catch {}
+ } catch (err) {
+ const code = (err as { code?: string } | null)?.code;
+ if (code !== 'ESRCH') {
+ deps.logger?.warn({ event: 'pty-host-reap-failed', code: code ?? 'unknown' });
+ }
+ }
}
function handleCreate(message: PtyCreateMessage): void {
- if (active) {
- safeKill(active.pty);
- active = null;
+ const { ptyId } = message;
+ const stale = sessions.get(ptyId);
+ if (stale) {
+ safeKill(stale);
+ sessions.delete(ptyId);
}
const shell = resolveShell(env, message.shell);
const shellEnv = buildShellEnv(env);
@@ -160,38 +184,39 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
encoding: 'utf8',
});
} catch (err) {
- post({ type: 'spawn-error', ptyId: message.ptyId, message: (err as Error).message });
+ const message = err instanceof Error ? err.message : String(err);
+ post({ type: 'spawn-error', ptyId, message });
return;
}
- const { ptyId } = message;
- active = { ptyId, pty };
+ sessions.set(ptyId, pty);
pty.onData((data) => {
- if (active?.ptyId === ptyId) post({ type: 'data', ptyId, data });
+ if (sessions.get(ptyId) === pty) post({ type: 'data', ptyId, data });
});
pty.onExit(({ exitCode, signal }) => {
- if (active?.ptyId === ptyId) active = null;
+ if (sessions.get(ptyId) === pty) sessions.delete(ptyId);
post({ type: 'exit', ptyId, exitCode, signal: signal ?? null });
});
}
function handleInput(message: PtyInputMessage): void {
- if (active?.ptyId === message.ptyId) active.pty.write(message.data);
+ sessions.get(message.ptyId)?.write(message.data);
}
function handleResize(message: PtyResizeMessage): void {
- if (active?.ptyId === message.ptyId) active.pty.resize(message.cols, message.rows);
+ sessions.get(message.ptyId)?.resize(message.cols, message.rows);
}
function handleKill(message: PtyKillMessage): void {
- if (active?.ptyId === message.ptyId) safeKill(active.pty);
+ const pty = sessions.get(message.ptyId);
+ if (pty) safeKill(pty);
}
function handlePause(message: PtyPauseMessage): void {
- if (active?.ptyId === message.ptyId) active.pty.pause();
+ sessions.get(message.ptyId)?.pause();
}
function handleResume(message: PtyResumeMessage): void {
- if (active?.ptyId === message.ptyId) active.pty.resume();
+ sessions.get(message.ptyId)?.resume();
}
deps.parentPort?.on('message', (event) => {
@@ -230,10 +255,8 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
return {
killActive(): void {
- if (active) {
- safeKill(active.pty);
- active = null;
- }
+ for (const pty of sessions.values()) safeKill(pty);
+ sessions.clear();
},
};
}
@@ -269,7 +292,7 @@ if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {
try {
({ spawn } = await import('node-pty'));
} catch (err) {
- const message = (err as Error).message;
+ const message = err instanceof Error ? err.message : String(err);
parentPort.on('message', (event) => {
const msg = asIncomingMessage(event.data);
if (msg?.type === 'create') {
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
index 7fa080c3e..1f256fdbd 100644
--- a/packages/desktop/tests/main/terminal-manager.test.ts
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -340,6 +340,21 @@ describe('createTerminalManager — exit + crash surfacing', () => {
expect(h.forked).toHaveLength(2);
});
+ test('flushes a session buffered output before its exit on a host crash', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'last gasp' });
+ h.forked[0]?.emitExit(1);
+ expect(h.sent.map((s) => s.channel)).toEqual(['ok:pty:data', 'ok:pty:exit']);
+ expect(h.dataPayloads()).toEqual(['last gasp']);
+ });
+
test('ignores a malformed host message without crashing or sending', () => {
const h = makeManager();
h.mgr.create({
@@ -437,7 +452,7 @@ describe('createTerminalManager — destroyed-window guard', () => {
});
});
-describe('createTerminalManager — lifecycle reap (US-005 hooks)', () => {
+describe('createTerminalManager — lifecycle reap', () => {
test('killForWindow kills the host, deletes it, and silences its exit event', () => {
const h = makeManager();
h.mgr.create({
@@ -564,13 +579,15 @@ class ThrowingUtility {
}
}
-describe('createTerminalManager — telemetry (US-013)', () => {
+describe('createTerminalManager — telemetry', () => {
function makeTelemetryManager() {
const shellExits: Array<{ crashed: boolean }> = [];
const sessions: true[] = [];
+ const concurrent: Array<{ count: number }> = [];
const h = makeManager({
recordShellExit: (info) => shellExits.push(info),
recordTerminalSession: () => sessions.push(true),
+ recordConcurrentSessions: (info) => concurrent.push(info),
});
const start = (windowId: number): void => {
h.mgr.create({
@@ -581,7 +598,7 @@ describe('createTerminalManager — telemetry (US-013)', () => {
rows: 24,
});
};
- return { ...h, shellExits, sessions, start };
+ return { ...h, shellExits, sessions, concurrent, start };
}
test('a clean shell exit emits a non-crash shell-exit; no session without a command', () => {
@@ -672,6 +689,236 @@ describe('createTerminalManager — telemetry (US-013)', () => {
expect(h.sessions).toHaveLength(1);
expect(h.shellExits).toEqual([{ crashed: false }, { crashed: false }]);
});
+
+ test('a window-close reap counts every concurrent session that ran a command', () => {
+ const h = makeTelemetryManager();
+ h.start(1); // pty-1
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ }); // pty-2
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'a\r' });
+ h.mgr.input({ windowId: 1, ptyId: 'pty-2', data: 'b\r' });
+ h.mgr.killForWindow(1);
+ expect(h.sessions).toHaveLength(2);
+ expect(h.shellExits).toEqual([]);
+ });
+
+ test('a host crash emits a crashed shell-exit per session and counts only the ones that ran a command', () => {
+ const h = makeTelemetryManager();
+ h.start(1); // pty-1
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ }); // pty-2
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'a\r' }); // only pty-1 ran a command
+ h.forked[0]?.emitExit(1);
+ expect(h.shellExits).toEqual([{ crashed: true }, { crashed: true }]);
+ expect(h.sessions).toHaveLength(1);
+ });
+
+ test('each create emits the concurrency signal with the window’s live session count', () => {
+ const h = makeTelemetryManager();
+ h.start(1); // window 1 now has 1 session
+ h.start(1); // window 1 now has 2 sessions
+ expect(h.concurrent.map((c) => c.count)).toEqual([1, 2]);
+ });
+
+ test('concurrency is counted per window independently', () => {
+ const h = makeTelemetryManager();
+ h.start(1); // w1 -> 1
+ h.start(1); // w1 -> 2
+ h.start(2); // w2 -> 1 (a separate window's host, not the running total)
+ expect(h.concurrent.map((c) => c.count)).toEqual([1, 2, 1]);
+ });
+
+ test('a create reaching a concurrency level again after an exit re-emits that level', () => {
+ const h = makeTelemetryManager();
+ h.start(1); // -> 1
+ h.start(1); // -> 2
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null }); // back to 1
+ h.start(1); // a fresh tab brings the window back to 2 concurrent
+ expect(h.concurrent.map((c) => c.count)).toEqual([1, 2, 2]);
+ });
+
+ test('a refused create (no project) emits no concurrency signal', () => {
+ const h = makeTelemetryManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: null,
+ cols: 80,
+ rows: 24,
+ });
+ expect(h.concurrent).toEqual([]);
+ });
+
+ test('a session exit does not emit a concurrency signal (it marks concurrency reached on open)', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.start(1);
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ h.mgr.killForWindow(1);
+ expect(h.concurrent.map((c) => c.count)).toEqual([1, 2]);
+ });
+
+ test('the concurrency signal carries only the bounded count — command input never leaks into it', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'secret --token=abc\r' });
+ h.start(1);
+ expect(h.concurrent.every((c) => Object.keys(c).join(',') === 'count')).toBe(true);
+ expect(h.concurrent.map((c) => c.count)).toEqual([1, 2]);
+ });
+});
+
+describe('createTerminalManager — concurrent sessions', () => {
+ function twoSessions(over?: Partial<TerminalManagerDeps>) {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20, ...over });
+ const wc = makeWebContents();
+ const a = h.mgr.create({
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const b = h.mgr.create({
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ return { h, a, b };
+ }
+ const dataFor = (h: ReturnType<typeof makeManager>, ptyId: string): string[] =>
+ h.sent
+ .filter((s) => s.channel === 'ok:pty:data' && s.payload.ptyId === ptyId)
+ .map((s) => s.payload.data as string);
+
+ test('a second create adds a session over the same host without killing the first', () => {
+ const { h, a, b } = twoSessions();
+ expect(a).toEqual({ ok: true, ptyId: 'pty-1' });
+ expect(b).toEqual({ ok: true, ptyId: 'pty-2' });
+ expect(h.forked).toHaveLength(1);
+ const posted = h.forked[0]?.posted ?? [];
+ expect(posted).toContainEqual({
+ type: 'create',
+ ptyId: 'pty-1',
+ cwd: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(posted).toContainEqual({
+ type: 'create',
+ ptyId: 'pty-2',
+ cwd: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(posted.filter((m) => m.type === 'kill')).toEqual([]);
+ });
+
+ test('input routes to the addressed session only', () => {
+ const { h } = twoSessions();
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'in-A\r' });
+ h.mgr.input({ windowId: 1, ptyId: 'pty-2', data: 'in-B\r' });
+ const posted = h.forked[0]?.posted ?? [];
+ expect(posted).toContainEqual({ type: 'input', ptyId: 'pty-1', data: 'in-A\r' });
+ expect(posted).toContainEqual({ type: 'input', ptyId: 'pty-2', data: 'in-B\r' });
+ });
+
+ test("each session's output renders only in its own tab", () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'alpha' });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-2', data: 'beta' });
+ h.runTimers();
+ expect(dataFor(h, 'pty-1')).toEqual(['alpha']);
+ expect(dataFor(h, 'pty-2')).toEqual(['beta']);
+ });
+
+ test('a flood in one session pauses only that session; the other keeps flushing', () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-2', data: 'y'.repeat(10) });
+ h.runTimers();
+ const posted = h.forked[0]?.posted ?? [];
+ expect(posted).toContainEqual({ type: 'pause', ptyId: 'pty-1' });
+ expect(posted).not.toContainEqual({ type: 'pause', ptyId: 'pty-2' });
+ expect(dataFor(h, 'pty-2')).toEqual(['y'.repeat(10)]);
+ });
+
+ test('drain resumes only the session that fell below the low-water mark', () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-2', data: 'y'.repeat(150) });
+ h.runTimers();
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'pause', ptyId: 'pty-1' });
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'pause', ptyId: 'pty-2' });
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-1', bytes: 140 }); // 150 - 140 = 10 < 20
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-2' });
+ });
+
+ test('a paused session never leaks its pause latch to a sibling', () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers(); // pty-1 pauses; pty-2 was never paused
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-2', bytes: 5 });
+ expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-2' });
+ });
+
+ test('an exit in one session leaves the other running', () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.exits()).toContainEqual({ ptyId: 'pty-1', exitCode: 0, signal: null });
+ const before = h.forked[0]?.posted.length ?? 0;
+ h.mgr.input({ windowId: 1, ptyId: 'pty-2', data: 'alive\r' });
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'ghost\r' });
+ expect(h.forked[0]?.posted.length).toBe(before + 1);
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'input', ptyId: 'pty-2', data: 'alive\r' });
+ });
+
+ test("one session's flood and pause do not disturb a sibling's exit accounting", () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers(); // pty-1 paused
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-2', exitCode: 0, signal: null });
+ expect(h.exits()).toContainEqual({ ptyId: 'pty-2', exitCode: 0, signal: null });
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-1', bytes: 150 });
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ });
+
+ test('a host crash surfaces an exit on every live session in the window', () => {
+ const { h } = twoSessions();
+ h.forked[0]?.emitExit(7);
+ expect(h.exits()).toContainEqual({
+ ptyId: 'pty-1',
+ exitCode: 7,
+ signal: null,
+ error: 'terminal host exited',
+ });
+ expect(h.exits()).toContainEqual({
+ ptyId: 'pty-2',
+ exitCode: 7,
+ signal: null,
+ error: 'terminal host exited',
+ });
+ });
+
+ test('killForWindow reaps a multi-session window with a single host kill', () => {
+ const { h } = twoSessions();
+ h.mgr.killForWindow(1);
+ expect(h.forked).toHaveLength(1);
+ expect(h.forked[0]?.killed).toBe(1);
+ });
});
describe('clampPtyDimension', () => {
diff --git a/packages/desktop/tests/main/terminal-telemetry.test.ts b/packages/desktop/tests/main/terminal-telemetry.test.ts
index 600d58b11..6f81c4e9d 100644
--- a/packages/desktop/tests/main/terminal-telemetry.test.ts
+++ b/packages/desktop/tests/main/terminal-telemetry.test.ts
@@ -18,7 +18,7 @@ mock.module('@inkeep/open-knowledge-server', () => ({
},
}));
-const { recordShellExit, recordTerminalSession } = await import(
+const { recordConcurrentSessions, recordShellExit, recordTerminalSession } = await import(
'../../src/main/terminal-telemetry.ts'
);
@@ -59,3 +59,22 @@ describe('recordTerminalSession — count-only marker', () => {
expect(capturedCalls[0]?.options?.attributes ?? {}).toEqual({});
});
});
+
+describe('recordConcurrentSessions — count-only concurrency signal', () => {
+ beforeEach(() => {
+ capturedCalls.length = 0;
+ });
+
+ test('emits ok.desktop.terminalConcurrentSessions carrying the live session count', () => {
+ recordConcurrentSessions({ count: 3 });
+ expect(capturedCalls).toHaveLength(1);
+ expect(capturedCalls[0]?.name).toBe('ok.desktop.terminalConcurrentSessions');
+ expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.desktop.concurrent_sessions': 3 });
+ });
+
+ test('the only attribute is the bounded count — no ptyId / path / command content leaks', () => {
+ recordConcurrentSessions({ count: 2 });
+ const attrs = capturedCalls[0]?.options?.attributes ?? {};
+ expect(Object.keys(attrs)).toEqual(['ok.desktop.concurrent_sessions']);
+ });
+});
diff --git a/packages/desktop/tests/utility/pty-flood.harness.ts b/packages/desktop/tests/utility/pty-flood.harness.ts
index 6403f30b1..baba18775 100644
--- a/packages/desktop/tests/utility/pty-flood.harness.ts
+++ b/packages/desktop/tests/utility/pty-flood.harness.ts
@@ -60,6 +60,8 @@ function assert(condition: boolean, message: string): void {
class InProcessBridge implements PtyUtilityLike {
pauseCount = 0;
resumeCount = 0;
+ private readonly pausesByPty = new Map<string, number>();
+ private readonly resumesByPty = new Map<string, number>();
private hostHandler: ((event: { data: unknown }) => void) | null = null;
private readonly msgSubs: Array<(message: unknown) => void> = [];
private readonly exitSubs: Array<(code: number | null) => void> = [];
@@ -81,11 +83,24 @@ class InProcessBridge implements PtyUtilityLike {
}
postMessage(message: PtyHostIncomingMessage): void {
- if (message.type === 'pause') this.pauseCount += 1;
- else if (message.type === 'resume') this.resumeCount += 1;
+ if (message.type === 'pause') {
+ this.pauseCount += 1;
+ this.pausesByPty.set(message.ptyId, (this.pausesByPty.get(message.ptyId) ?? 0) + 1);
+ } else if (message.type === 'resume') {
+ this.resumeCount += 1;
+ this.resumesByPty.set(message.ptyId, (this.resumesByPty.get(message.ptyId) ?? 0) + 1);
+ }
this.hostHandler?.({ data: message });
}
+ pauseCountFor(ptyId: string): number {
+ return this.pausesByPty.get(ptyId) ?? 0;
+ }
+
+ resumeCountFor(ptyId: string): number {
+ return this.resumesByPty.get(ptyId) ?? 0;
+ }
+
on(event: 'message', cb: (message: unknown) => void): void;
on(event: 'exit', cb: (code: number | null) => void): void;
on(event: 'message' | 'exit', cb: (arg: never) => void): void {
@@ -268,6 +283,349 @@ const MAX_HEARTBEAT_GAP_MS = (() => {
return Number.isFinite(override) && override > 0 ? override : 500;
})();
+const UNIT_A = '日本語🎉αβγ';
+const UNIT_B = '한국어🚀ΔΣΩ';
+const UNIT_ACTIVE = '中文🌟λμν';
+const SENTINEL_A = '__OKFLOOD_A_42__';
+const SENTINEL_A_CMD = '__OKFLOOD_A_$((6*7))__';
+const SENTINEL_B = '__OKFLOOD_B_42__';
+const SENTINEL_B_CMD = '__OKFLOOD_B_$((6*7))__';
+const SENTINEL_ACTIVE = '__OKFLOOD_ACTIVE_42__';
+const SENTINEL_ACTIVE_CMD = '__OKFLOOD_ACTIVE_$((6*7))__';
+const HIDDEN_MARKER = 'HIDDEN_FLOOD_LINE';
+
+interface SessionRuntime {
+ readonly ptyId: string;
+ readonly sentinel: string;
+ readonly accumulate: boolean;
+ readonly drainMode: 'immediate' | 'metered';
+ readonly meterUnitsPerTick: number;
+ drainEnabled: boolean;
+ readonly chunks: string[];
+ totalPushed: number;
+ totalAcked: number;
+ pushCount: number;
+ tail: string;
+ sawFirstByte: boolean;
+ sawSentinel: boolean;
+}
+
+interface AddSessionSpec {
+ sentinel: string;
+ drainMode: 'immediate' | 'metered';
+ /** Keep the full received stream (default true). Hidden floods set false so an
+ * unbounded `yes` stream doesn't accumulate gigabytes of chunks. */
+ accumulate?: boolean;
+ meterUnitsPerTick?: number;
+}
+
+interface MultiSessionRig {
+ readonly bridge: InProcessBridge;
+ readonly tmp: string;
+ addSession(spec: AddSessionSpec): SessionRuntime;
+ input(session: SessionRuntime, data: string): void;
+ inFlight(session: SessionRuntime): number;
+ received(session: SessionRuntime): string;
+ cleanup(): void;
+}
+
+const activeRigCleanups = new Set<() => void>();
+
+function reapActiveRigs(): void {
+ for (const cleanup of activeRigCleanups) {
+ try {
+ cleanup();
+ } catch {}
+ }
+}
+
+function writeFloodFile(tmp: string, name: string, unit: string, units: number): string {
+ const file = join(tmp, name);
+ writeFileSync(file, unit.repeat(units), 'utf8');
+ return file;
+}
+
+function createMultiSessionRig(opts: {
+ highWaterBytes: number;
+ lowWaterBytes: number;
+ meterTickMs?: number;
+}): MultiSessionRig {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-multi-')));
+ const bridge = new InProcessBridge(spawn, { ...process.env });
+ const sessions = new Map<string, SessionRuntime>();
+ const webContents: SendableWebContents = { send: () => {}, isDestroyed: () => false };
+ let idCounter = 0;
+
+ let manager!: TerminalManager;
+ const ackBytes = (session: SessionRuntime, n: number): void => {
+ session.totalAcked += n;
+ manager.drain({ windowId: 1, ptyId: session.ptyId, bytes: n });
+ };
+
+ manager = createTerminalManager({
+ forkPtyHost: () => bridge,
+ sendData: (_wc, payload) => {
+ const session = sessions.get(payload.ptyId);
+ if (!session) return;
+ session.totalPushed += payload.data.length;
+ session.pushCount += 1;
+ session.sawFirstByte = true;
+ if (session.accumulate) {
+ session.chunks.push(payload.data);
+ session.tail = (session.tail + payload.data).slice(-256);
+ if (
+ !session.sawSentinel &&
+ session.sentinel.length > 0 &&
+ session.tail.includes(session.sentinel)
+ ) {
+ session.sawSentinel = true;
+ }
+ }
+ if (session.drainEnabled && session.drainMode === 'immediate') {
+ const n = payload.data.length;
+ queueMicrotask(() => ackBytes(session, n));
+ }
+ },
+ sendExit: () => {},
+ newPtyId: () => `mpty-${idCounter++}`,
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>),
+ coalesceMs: COALESCE_MS,
+ highWaterBytes: opts.highWaterBytes,
+ lowWaterBytes: opts.lowWaterBytes,
+ });
+
+ const meterMs = opts.meterTickMs ?? 20;
+ const pump = setInterval(() => {
+ for (const session of sessions.values()) {
+ if (session.drainMode !== 'metered' || !session.drainEnabled) continue;
+ const available = session.totalPushed - session.totalAcked;
+ if (available <= 0) continue;
+ ackBytes(session, Math.min(session.meterUnitsPerTick, available));
+ }
+ }, meterMs);
+
+ let cleaned = false;
+ const cleanup = (): void => {
+ if (cleaned) return;
+ cleaned = true;
+ clearInterval(pump);
+ for (const session of sessions.values()) {
+ try {
+ manager.kill({ windowId: 1, ptyId: session.ptyId });
+ } catch {}
+ }
+ bridge.reap();
+ activeRigCleanups.delete(cleanup);
+ try {
+ rmSync(tmp, { recursive: true, force: true });
+ } catch {}
+ };
+ activeRigCleanups.add(cleanup);
+
+ return {
+ bridge,
+ tmp,
+ addSession(spec): SessionRuntime {
+ const result = manager.create({
+ windowId: 1,
+ webContents,
+ projectRoot: tmp,
+ cols: 80,
+ rows: 24,
+ });
+ if (!result.ok) throw new Error(`create rejected: ${result.reason}`);
+ const session: SessionRuntime = {
+ ptyId: result.ptyId,
+ sentinel: spec.sentinel,
+ accumulate: spec.accumulate ?? true,
+ drainMode: spec.drainMode,
+ meterUnitsPerTick: spec.meterUnitsPerTick ?? 131072,
+ drainEnabled: spec.drainMode === 'immediate',
+ chunks: [],
+ totalPushed: 0,
+ totalAcked: 0,
+ pushCount: 0,
+ tail: '',
+ sawFirstByte: false,
+ sawSentinel: false,
+ };
+ sessions.set(session.ptyId, session);
+ return session;
+ },
+ input(session, data): void {
+ manager.input({ windowId: 1, ptyId: session.ptyId, data });
+ },
+ inFlight(session): number {
+ return session.totalPushed - session.totalAcked;
+ },
+ received(session): string {
+ return session.chunks.join('');
+ },
+ cleanup,
+ };
+}
+
+async function runTwoSessionIsolation(): Promise<void> {
+ const UNITS_A = 200_000;
+ const UNITS_B = 20_000;
+ const highWater = 256 * 1024;
+ const rig = createMultiSessionRig({ highWaterBytes: highWater, lowWaterBytes: 64 * 1024 });
+ try {
+ const fileA = writeFloodFile(rig.tmp, 'flood-a.txt', UNIT_A, UNITS_A);
+ const fileB = writeFloodFile(rig.tmp, 'flood-b.txt', UNIT_B, UNITS_B);
+ const a = rig.addSession({ sentinel: SENTINEL_A, drainMode: 'metered' });
+ const b = rig.addSession({ sentinel: SENTINEL_B, drainMode: 'immediate' });
+
+ await waitFor(() => a.sawFirstByte && b.sawFirstByte, 'both shell prompts', 15000);
+
+ rig.input(a, `cat '${fileA}'; echo ${SENTINEL_A_CMD}\r`);
+ await waitFor(() => rig.bridge.pauseCountFor(a.ptyId) > 0, "A's backpressure to engage", 20000);
+
+ rig.input(b, `cat '${fileB}'; echo ${SENTINEL_B_CMD}\r`);
+ await waitFor(() => b.sawSentinel, 'B to complete while A is held paused', 60000);
+
+ assert(
+ rig.bridge.resumeCountFor(a.ptyId) === 0,
+ 'A resumed before being drained — its backpressure did not actually hold',
+ );
+ const bPauses = rig.bridge.pauseCountFor(b.ptyId);
+ assert(
+ bPauses === 0,
+ `pause state leaked across sessions: B paused ${bPauses}x under A's flood`,
+ );
+
+ const bRecv = rig.received(b);
+ const bUnits = countOccurrences(bRecv, UNIT_B);
+ assert(bUnits === UNITS_B, `B byte corruption: ${bUnits} units delivered, expected ${UNITS_B}`);
+ assert(!bRecv.includes('�'), 'U+FFFD in session B (split multibyte sequence)');
+ assert(
+ countOccurrences(bRecv, UNIT_A) === 0,
+ "cross-session interleave: A's content reached B",
+ );
+
+ a.drainEnabled = true;
+ await waitFor(() => a.sawSentinel, 'A to complete after draining', 60000);
+ const aRecv = rig.received(a);
+ const aUnits = countOccurrences(aRecv, UNIT_A);
+ assert(aUnits === UNITS_A, `A byte corruption: ${aUnits} units delivered, expected ${UNITS_A}`);
+ assert(!aRecv.includes('�'), 'U+FFFD in session A (split multibyte sequence)');
+ assert(
+ countOccurrences(aRecv, UNIT_B) === 0,
+ "cross-session interleave: B's content reached A",
+ );
+ assert(rig.bridge.resumeCountFor(a.ptyId) >= 1, 'A never resumed after draining');
+ console.log(
+ ` A: units=${UNITS_A} pauses=${rig.bridge.pauseCountFor(a.ptyId)} resumes=${rig.bridge.resumeCountFor(a.ptyId)} | B: units=${UNITS_B} pauses=${bPauses} (done while A paused)`,
+ );
+ } finally {
+ rig.cleanup();
+ }
+}
+
+async function runNWayAggregate(): Promise<void> {
+ const HIDDEN_COUNT = 3;
+ const ACTIVE_UNITS = 20_000; // < high-water: the active tab must never self-pause
+ const highWater = 256 * 1024;
+ const rig = createMultiSessionRig({ highWaterBytes: highWater, lowWaterBytes: 64 * 1024 });
+
+ let lastBeat = 0;
+ let maxGap = 0;
+ let beats = 0;
+ let measuring = false;
+ const heartbeat = setInterval(() => {
+ const now = Date.now();
+ if (measuring && lastBeat > 0) {
+ const gap = now - lastBeat;
+ if (gap > maxGap) maxGap = gap;
+ beats += 1;
+ }
+ lastBeat = now;
+ }, 10);
+
+ try {
+ const activeFile = writeFloodFile(rig.tmp, 'active.txt', UNIT_ACTIVE, ACTIVE_UNITS);
+ const active = rig.addSession({ sentinel: SENTINEL_ACTIVE, drainMode: 'immediate' });
+ const hidden: SessionRuntime[] = [];
+ for (let i = 0; i < HIDDEN_COUNT; i += 1) {
+ hidden.push(rig.addSession({ sentinel: '', drainMode: 'immediate', accumulate: false }));
+ }
+
+ await waitFor(
+ () => active.sawFirstByte && hidden.every((h) => h.sawFirstByte),
+ 'all shell prompts',
+ 15000,
+ );
+
+ for (const h of hidden) rig.input(h, `yes '${HIDDEN_MARKER}'\r`);
+ await sleep(250); // let the hidden floods ramp to steady state
+
+ lastBeat = Date.now();
+ measuring = true;
+ rig.input(active, `cat '${activeFile}'; echo ${SENTINEL_ACTIVE_CMD}\r`);
+ await waitFor(() => active.sawSentinel, 'active flood completion under aggregate load', 30000);
+ await sleep(1000); // keep sampling the sustained aggregate after the round-trip
+ measuring = false;
+ const maxGapUnderLoad = maxGap;
+
+ const activeRecv = rig.received(active);
+ const activeUnits = countOccurrences(activeRecv, UNIT_ACTIVE);
+ assert(
+ activeUnits === ACTIVE_UNITS,
+ `active byte corruption: ${activeUnits} units delivered, expected ${ACTIVE_UNITS}`,
+ );
+ assert(!activeRecv.includes('�'), 'U+FFFD in the active stream under aggregate load');
+ assert(
+ !activeRecv.includes(HIDDEN_MARKER),
+ 'cross-session interleave: a hidden flood reached the active stream',
+ );
+ assert(beats > 0, 'event loop frozen under aggregate hidden floods');
+ assert(
+ rig.bridge.pauseCountFor(active.ptyId) === 0,
+ 'the active tab self-paused — pause state may be shared, or its flood exceeded high-water',
+ );
+ assert(
+ maxGapUnderLoad < MAX_HEARTBEAT_GAP_MS,
+ `active starved: max heartbeat gap ${maxGapUnderLoad}ms >= ${MAX_HEARTBEAT_GAP_MS}ms under ${HIDDEN_COUNT} hidden floods`,
+ );
+
+ for (const h of hidden) h.drainEnabled = false;
+ await waitFor(
+ () => hidden.every((h) => rig.bridge.pauseCountFor(h.ptyId) > 0),
+ 'every hidden flood to pause under the fallback',
+ 20000,
+ );
+ await sleep(300); // let in-flight coalesce buffers drain after the pause
+ const pushedAfterPause = new Map(hidden.map((h) => [h.ptyId, h.totalPushed]));
+ await sleep(400);
+ let idx = 0;
+ for (const h of hidden) {
+ const delta = h.totalPushed - (pushedAfterPause.get(h.ptyId) ?? 0);
+ assert(
+ delta < highWater,
+ `fallback did not stop hidden session ${idx}: +${delta} code units after pausing`,
+ );
+ const inFlight = rig.inFlight(h);
+ assert(
+ inFlight < 4 * 1024 * 1024,
+ `hidden session ${idx} in-flight unbounded after pause: ${inFlight} code units`,
+ );
+ idx += 1;
+ }
+ assert(
+ rig.bridge.pauseCountFor(active.ptyId) === 0,
+ 'the active tab paused when only hidden tabs were throttled',
+ );
+ const aggregateInFlight = hidden.reduce((sum, h) => sum + rig.inFlight(h), 0);
+ console.log(
+ ` hidden=${HIDDEN_COUNT} active=${ACTIVE_UNITS} maxGapUnderLoad=${maxGapUnderLoad}ms beats=${beats} aggregateInFlight=${aggregateInFlight}`,
+ );
+ } finally {
+ clearInterval(heartbeat);
+ rig.cleanup();
+ }
+}
+
async function main(): Promise<void> {
ensureSpawnHelperExecutable();
@@ -327,18 +685,28 @@ async function main(): Promise<void> {
);
});
+ await scenario('two concurrent sessions isolate backpressure and bytes', runTwoSessionIsolation);
+ await scenario(
+ 'hidden floods stay bounded and keep the active session responsive',
+ runNWayAggregate,
+ );
+
const failed = results.filter((r) => !r.ok).length;
console.log(`HARNESS_RESULT ok=${results.length - failed} fail=${failed}`);
process.exit(failed === 0 ? 0 : 1);
}
const hardTimeout = setTimeout(() => {
+ reapActiveRigs();
console.log('HARNESS_RESULT ok=0 fail=1 :: hard timeout');
process.exit(1);
}, 120000);
hardTimeout.unref();
+process.on('exit', reapActiveRigs);
+
void main().catch((err) => {
+ reapActiveRigs();
console.log(`HARNESS_RESULT ok=0 fail=1 :: ${(err as Error).message}`);
process.exit(1);
});
diff --git a/packages/desktop/tests/utility/pty-flood.test.ts b/packages/desktop/tests/utility/pty-flood.test.ts
index f8a19a3ba..ced943f9c 100644
--- a/packages/desktop/tests/utility/pty-flood.test.ts
+++ b/packages/desktop/tests/utility/pty-flood.test.ts
@@ -4,7 +4,7 @@ const NODE = Bun.which('node');
const HARNESS = new URL('./pty-flood.harness.ts', import.meta.url).pathname;
describe('PTY flood — backpressure + UTF-8 integrity (Node runtime)', () => {
- test('a sustained multibyte flood stays responsive, bounds in-flight via pause/resume, and delivers bytes uncorrupted', () => {
+ test('sustained multibyte floods stay responsive, bound in-flight via pause/resume, deliver bytes uncorrupted, and isolate concurrent sessions', () => {
if (!NODE) {
throw new Error(
'node was not found on PATH but is required (package engines: >=24) to drive the real-PTY flood — node-pty produces no output under Bun',
@@ -15,6 +15,6 @@ describe('PTY flood — backpressure + UTF-8 integrity (Node runtime)', () => {
if (proc.exitCode !== 0) {
throw new Error(`flood harness failed (exit ${proc.exitCode}):\n${output}`);
}
- expect(output).toContain('HARNESS_RESULT ok=2 fail=0');
+ expect(output).toContain('HARNESS_RESULT ok=4 fail=0');
}, 120_000);
});
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index b66c32bf4..7fbcad66e 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -200,6 +200,20 @@ describe('setupPtyHost — streaming', () => {
expect(pty.killCount).toBe(1);
});
+ test('logs a reap-failed warning when kill throws a non-ESRCH error', () => {
+ const pty = makeFakePty();
+ pty.kill = () => {
+ throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' });
+ };
+ const warnings: Record<string, unknown>[] = [];
+ const h = makeHarness({ pty, logger: { warn: (o) => warnings.push(o) } });
+ h.fire(CREATE());
+ expect(() => h.fire({ type: 'kill', ptyId: 'p1' })).not.toThrow();
+ expect(warnings).toContainEqual(
+ expect.objectContaining({ event: 'pty-host-reap-failed', code: 'EPERM' }),
+ );
+ });
+
test('routes pause/resume backpressure to the active pty', () => {
const pty = makeFakePty();
const h = makeHarness({ pty });
@@ -251,6 +265,17 @@ describe('setupPtyHost — containment (AC5: host survives a PTY failure)', () =
]);
});
+ test('a non-Error spawn throw still surfaces a string spawn-error message', () => {
+ const spawn: SpawnPty = () => {
+ throw 'EMFILE: too many open files';
+ };
+ const h = makeHarness({ spawn });
+ h.fire(CREATE());
+ expect(h.posted).toEqual([
+ { type: 'spawn-error', ptyId: 'p1', message: 'EMFILE: too many open files' },
+ ]);
+ });
+
test('the host keeps routing after a spawn failure', () => {
const goodPty = makeFakePty();
let calls = 0;
@@ -303,7 +328,7 @@ describe('setupPtyHost — addressing', () => {
expect(pty.killCount).toBe(1);
});
- test('a second create kills the prior live pty before spawning (supersede/reap)', () => {
+ test('a create reusing a live ptyId reaps the stale shell before replacing it (no orphan)', () => {
const first = makeFakePty();
const second = makeFakePty();
const ptys = [first, second];
@@ -311,20 +336,128 @@ describe('setupPtyHost — addressing', () => {
const spawn: SpawnPty = () => ptys[n++] ?? makeFakePty();
const h = makeHarness({ spawn });
- h.fire(CREATE({ ptyId: 'first' }));
+ h.fire(CREATE({ ptyId: 'dup' }));
expect(first.killCount).toBe(0);
-
- h.fire(CREATE({ ptyId: 'second' }));
+ h.fire(CREATE({ ptyId: 'dup' }));
expect(first.killCount).toBe(1);
second.emitData('alive');
- expect(h.posted).toContainEqual({ type: 'data', ptyId: 'second', data: 'alive' });
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'dup', data: 'alive' });
const before = h.posted.length;
first.emitData('orphan');
expect(h.posted.length).toBe(before);
});
});
+describe('setupPtyHost — concurrent sessions', () => {
+ function makeMultiHarness(ptys: FakePty[]): Harness {
+ let n = 0;
+ const spawn: SpawnPty = () => ptys[n++] ?? makeFakePty();
+ return makeHarness({ spawn });
+ }
+
+ test('a second create with a new id adds a session and leaves the first running', () => {
+ const a = makeFakePty();
+ const b = makeFakePty();
+ const h = makeMultiHarness([a, b]);
+ h.fire(CREATE({ ptyId: 'a' }));
+ h.fire(CREATE({ ptyId: 'b' }));
+ expect(a.killCount).toBe(0);
+ expect(b.killCount).toBe(0);
+ a.emitData('a-still-here');
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'a', data: 'a-still-here' });
+ });
+
+ test('both sessions stream concurrently, each tagged with its own ptyId', () => {
+ const a = makeFakePty();
+ const b = makeFakePty();
+ const h = makeMultiHarness([a, b]);
+ h.fire(CREATE({ ptyId: 'a' }));
+ h.fire(CREATE({ ptyId: 'b' }));
+ a.emitData('from-a');
+ b.emitData('from-b');
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'a', data: 'from-a' });
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'b', data: 'from-b' });
+ });
+
+ test('input/resize/kill/pause/resume each act only on the addressed session', () => {
+ const a = makeFakePty();
+ const b = makeFakePty();
+ const h = makeMultiHarness([a, b]);
+ h.fire(CREATE({ ptyId: 'a' }));
+ h.fire(CREATE({ ptyId: 'b' }));
+
+ h.fire({ type: 'input', ptyId: 'a', data: 'ls\r' });
+ h.fire({ type: 'resize', ptyId: 'b', cols: 100, rows: 30 });
+ h.fire({ type: 'pause', ptyId: 'a' });
+ h.fire({ type: 'resume', ptyId: 'b' });
+ h.fire({ type: 'kill', ptyId: 'a' });
+
+ expect(a.writes).toEqual(['ls\r']);
+ expect(b.writes).toEqual([]);
+ expect(b.resizes).toEqual([[100, 30]]);
+ expect(a.resizes).toEqual([]);
+ expect(a.pauseCount).toBe(1);
+ expect(b.pauseCount).toBe(0);
+ expect(b.resumeCount).toBe(1);
+ expect(a.resumeCount).toBe(0);
+ expect(a.killCount).toBe(1);
+ expect(b.killCount).toBe(0);
+ });
+
+ test('one session exiting removes only its entry and leaves the other running', () => {
+ const a = makeFakePty();
+ const b = makeFakePty();
+ const h = makeMultiHarness([a, b]);
+ h.fire(CREATE({ ptyId: 'a' }));
+ h.fire(CREATE({ ptyId: 'b' }));
+
+ a.emitExit({ exitCode: 0 });
+ expect(h.posted).toContainEqual({ type: 'exit', ptyId: 'a', exitCode: 0, signal: null });
+
+ const before = h.posted.length;
+ a.emitData('straggler');
+ expect(h.posted.length).toBe(before);
+ b.emitData('still-alive');
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'b', data: 'still-alive' });
+
+ h.fire({ type: 'input', ptyId: 'b', data: 'x' });
+ expect(b.writes).toEqual(['x']);
+ });
+
+ test('killActive reaps every session in the map (window/quit reap)', () => {
+ const a = makeFakePty();
+ const b = makeFakePty();
+ const c = makeFakePty();
+ const h = makeMultiHarness([a, b, c]);
+ h.fire(CREATE({ ptyId: 'a' }));
+ h.fire(CREATE({ ptyId: 'b' }));
+ h.fire(CREATE({ ptyId: 'c' }));
+
+ h.handle.killActive();
+ expect(a.killCount).toBe(1);
+ expect(b.killCount).toBe(1);
+ expect(c.killCount).toBe(1);
+
+ h.handle.killActive();
+ expect(a.killCount).toBe(1);
+ expect(b.killCount).toBe(1);
+ expect(c.killCount).toBe(1);
+ });
+
+ test('killActive keeps reaping after one session throws ESRCH (already exited)', () => {
+ const a = makeFakePty();
+ a.killThrows = true;
+ const b = makeFakePty();
+ const h = makeMultiHarness([a, b]);
+ h.fire(CREATE({ ptyId: 'a' }));
+ h.fire(CREATE({ ptyId: 'b' }));
+ expect(() => h.handle.killActive()).not.toThrow();
+ expect(a.killCount).toBe(1);
+ expect(b.killCount).toBe(1);
+ });
+});
+
describe('setupPtyHost — incoming message validation (asIncomingMessage guard)', () => {
function makeLogger() {
const warnings: Array<Record<string, unknown>> = [];