A desktop coding agent with free access to frontier models.
TypeScript
feat(terminal): several terminal tabs per workspace, and no shell outlives its tab
Samrat Talukdarb7a980ef7f41
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex fb18b832..9c18f24c 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -295,7 +295,9 @@ declare global {};browserLogins?: BrowserLoginSyncBridge;terminal?: {- create?: (options: { cwd: string; cols: number; rows: number }) => Promise<{ terminalId: string }>;+ shells?: () => Promise<Array<{ id: string; label: string }>>;+ create?: (options: { cwd: string; cols: number; rows: number; workspaceId?: string; shellId?: string | null }) => Promise<{ terminalId: string; shellId?: string; shellLabel?: string; cwd?: string }>;+ killWorkspace?: (workspaceId: string) => Promise<void>;write?: (terminalId: string, data: string) => Promise<void>;resize?: (terminalId: string, cols: number, rows: number) => Promise<void>;kill?: (terminalId: string) => Promise<void>;diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsxindex 111a5343..2c4c7862 100644--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx@@ -1959,6 +1959,7 @@ export function SessionPage(props: SessionPageProps) {<ResizableHandle /><ResizablePanel defaultSize="280px" minSize="160px" maxSize="55%" className="min-h-0"><TerminalDock+ workspaceId={props.selectedWorkspaceId}workspaceRoot={props.selectedWorkspaceRoot}isRemoteWorkspace={props.selectedWorkspaceDisplay.workspaceType === "remote"}onClose={() => props.onTerminalOpenChange?.(false)}diff --git a/apps/app/src/react-app/domains/session/terminal/terminal-dock.tsx b/apps/app/src/react-app/domains/session/terminal/terminal-dock.tsxindex 92f2e3ab..9b107476 100644--- a/apps/app/src/react-app/domains/session/terminal/terminal-dock.tsx+++ b/apps/app/src/react-app/domains/session/terminal/terminal-dock.tsx@@ -1,126 +1,176 @@/** @jsxImportSource react */-import { useEffect, useRef, useState } from "react";-import { FitAddon } from "@xterm/addon-fit";-import { Terminal } from "@xterm/xterm";+import { useEffect, useRef, useState, type KeyboardEvent } from "react";import "@xterm/xterm/css/xterm.css";-import { X } from "lucide-react";+import { ChevronDown, Plus, X } from "lucide-react";import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import { isElectronRuntime } from "../../../../app/utils";+import { desktopTerminalBridge, showTerminalTab, disposeTerminalTab, useTerminalStatusStore } from "./terminal-runtime";+import { useTerminalTabsStore, type TerminalTab } from "./terminal-tabs-store";type TerminalDockProps = {+ workspaceId: string;workspaceRoot: string;isRemoteWorkspace: boolean;onClose: () => void;};-export function TerminalDock({ workspaceRoot, isRemoteWorkspace, onClose }: TerminalDockProps) {+const NEW_TAB_HINT = "New terminal (Ctrl+Shift+`)";++export function TerminalDock({ workspaceId, workspaceRoot, isRemoteWorkspace, onClose }: TerminalDockProps) {const containerRef = useRef<HTMLDivElement | null>(null);- const terminalIdRef = useRef<string | null>(null);- const terminalRef = useRef<Terminal | null>(null);- const fitRef = useRef<FitAddon | null>(null);- const [status, setStatus] = useState("Starting terminal...");+ const bridge = isElectronRuntime() && !isRemoteWorkspace ? desktopTerminalBridge() : null;+ const unavailable = !isElectronRuntime()+ ? "Terminal is available in the desktop app."+ : isRemoteWorkspace+ ? "Remote workspace terminals are not wired yet."+ : bridge+ ? null+ : "Terminal bridge is unavailable.";++ const entry = useTerminalTabsStore((state) => state.byWorkspace[workspaceId]);+ const newTabRequests = useTerminalTabsStore((state) => state.newTabRequests);+ const statuses = useTerminalStatusStore((state) => state.status);+ const [shells, setShells] = useState<Array<{ id: string; label: string }>>([]);+ const [renaming, setRenaming] = useState<string | null>(null);++ const tabs = entry?.tabs ?? [];+ const active = tabs.find((tab) => tab.id === entry?.activeId) ?? null;+ // The workspace's tabs (restored from the last run), and a first tab when it has none.useEffect(() => {- if (!containerRef.current) return;- if (!isElectronRuntime()) {- setStatus("Terminal is available in the desktop app.");- return;- }- if (isRemoteWorkspace) {- setStatus("Remote workspace terminals are not wired yet.");- return;+ if (unavailable || !workspaceId) return;+ const store = useTerminalTabsStore.getState();+ const current = store.ensure(workspaceId);+ if (!current.tabs.length) {+ store.takeNewTabRequest();+ store.addTab(workspaceId);}+ }, [unavailable, workspaceId]);- const bridge = window.__OMNIRUSH_ELECTRON__?.terminal;- if (!bridge?.create || !bridge.write || !bridge.resize || !bridge.kill || !bridge.onData || !bridge.onExit) {- setStatus("Terminal bridge is unavailable.");- return;- }- const createTerminal = bridge.create;- const writeTerminal = bridge.write;- const resizeTerminal = bridge.resize;- const killTerminal = bridge.kill;- const onTerminalData = bridge.onData;- const onTerminalExit = bridge.onExit;-- let disposed = false;- const fitAddon = new FitAddon();- const terminal = new Terminal({- cursorBlink: true,- convertEol: true,- fontFamily: "'SFMono-Regular', 'Cascadia Code', 'Liberation Mono', Menlo, monospace",- fontSize: 12,- theme: {- background: "#0b0d12",- foreground: "#d7dde8",- cursor: "#ffffff",- selectionBackground: "#334155",- },- });- terminal.loadAddon(fitAddon);- terminal.open(containerRef.current);- terminal.focus();- fitAddon.fit();- terminalRef.current = terminal;- fitRef.current = fitAddon;-- const removeDataListener = onTerminalData(({ terminalId, data }) => {- if (terminalIdRef.current !== terminalId) return;- terminal.write(data);- });- const removeExitListener = onTerminalExit(({ terminalId, exitCode }) => {- if (terminalIdRef.current !== terminalId) return;- setStatus(`Terminal exited${exitCode === null ? "" : ` with code ${exitCode}`}.`);- terminalIdRef.current = null;- });- const inputDisposable = terminal.onData((data) => {- const terminalId = terminalIdRef.current;- if (!terminalId) return;- void writeTerminal(terminalId, data);- });-- const fitAndResize = () => {- fitAddon.fit();- const terminalId = terminalIdRef.current;- if (!terminalId) return;- void resizeTerminal(terminalId, terminal.cols, terminal.rows);- };- const resizeObserver = new ResizeObserver(fitAndResize);- resizeObserver.observe(containerRef.current);-- void createTerminal({ cwd: workspaceRoot, cols: terminal.cols, rows: terminal.rows }).then(({ terminalId }) => {- if (disposed) {- void killTerminal(terminalId);- return;- }- terminalIdRef.current = terminalId;- setStatus(workspaceRoot);- fitAndResize();- }).catch((error) => {- setStatus(error instanceof Error ? error.message : "Could not start terminal.");- });+ // Ctrl+Shift+` asked for a new tab.+ useEffect(() => {+ if (unavailable || !workspaceId || !newTabRequests) return;+ const store = useTerminalTabsStore.getState();+ if (store.takeNewTabRequest()) store.addTab(workspaceId);+ }, [newTabRequests, unavailable, workspaceId]);+ useEffect(() => {+ if (!bridge?.shells) return;+ let cancelled = false;+ void bridge.shells().then((list) => {+ if (!cancelled) setShells(list);+ }).catch(() => undefined);return () => {- disposed = true;- resizeObserver.disconnect();- inputDisposable.dispose();- removeDataListener();- removeExitListener();- const terminalId = terminalIdRef.current;- terminalIdRef.current = null;- if (terminalId) void killTerminal(terminalId);- terminal.dispose();- terminalRef.current = null;- fitRef.current = null;+ cancelled = true;};- }, [isRemoteWorkspace, workspaceRoot]);+ }, [bridge?.shells]);++ // Shows the active tab; the others keep running out of view.+ const activeId = active?.id ?? null;+ const activeShell = active?.shellId ?? null;+ useEffect(() => {+ const container = containerRef.current;+ if (!container || !bridge || !activeId) return;+ return showTerminalTab({ tabId: activeId, container, bridge, workspaceId, cwd: workspaceRoot, shellId: activeShell, focus: !renaming });+ }, [activeId, bridge?.create, workspaceId, workspaceRoot, activeShell]);++ const addTab = (shellId: string | null = null) => {+ useTerminalTabsStore.getState().addTab(workspaceId, shellId);+ };+ const closeTab = (tab: TerminalTab) => {+ disposeTerminalTab(tab.id, bridge);+ const left = useTerminalTabsStore.getState().closeTab(workspaceId, tab.id);+ if (!left) onClose();+ };++ const onKeyDown = (event: KeyboardEvent) => {+ // Ctrl+PageUp / Ctrl+PageDown switch tabs while the terminal has focus.+ if (!event.ctrlKey || event.altKey || event.metaKey) return;+ if (event.key === "PageUp" || event.key === "PageDown") {+ event.preventDefault();+ useTerminalTabsStore.getState().cycle(workspaceId, event.key === "PageDown" ? 1 : -1);+ }+ };++ const status = activeId ? statuses[activeId] : undefined;return (- <section className="flex h-full min-h-0 flex-col border-t border-border bg-[#0b0d12] text-white" aria-label="Terminal">- <header className="flex h-9 shrink-0 items-center justify-between border-b border-white/10 bg-black/35 px-3 text-xs">- <div className="min-w-0 truncate text-white/75">Terminal · {status}</div>- <Button variant="ghost" size="icon-sm" className="text-white/70 hover:bg-white/10 hover:text-white" onClick={onClose}>+ <section+ className="flex h-full min-h-0 flex-col border-t border-border bg-[#0b0d12] text-white"+ aria-label="Terminal"+ onKeyDownCapture={onKeyDown}+ >+ <header className="flex h-9 shrink-0 items-center gap-1 border-b border-white/10 bg-black/35 px-2 text-xs">+ {unavailable ? (+ <div className="min-w-0 flex-1 truncate px-1 text-white/75">Terminal · {unavailable}</div>+ ) : (+ <>+ <div role="tablist" aria-label="Terminal tabs" className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">+ {tabs.map((tab) => (+ <TerminalTabButton+ key={tab.id}+ tab={tab}+ active={tab.id === activeId}+ renaming={renaming === tab.id}+ exited={statuses[tab.id]?.state === "exited"}+ onSelect={() => useTerminalTabsStore.getState().setActive(workspaceId, tab.id)}+ onClose={() => closeTab(tab)}+ onStartRename={() => setRenaming(tab.id)}+ onRename={(name) => {+ useTerminalTabsStore.getState().renameTab(workspaceId, tab.id, name);+ setRenaming(null);+ }}+ onCancelRename={() => setRenaming(null)}+ />+ ))}+ <Button+ variant="ghost"+ size="icon-sm"+ className="shrink-0 text-white/70 hover:bg-white/10 hover:text-white"+ onClick={() => addTab()}+ title={NEW_TAB_HINT}+ aria-label="New terminal"+ >+ <Plus className="size-4" />+ </Button>+ {shells.length > 1 ? (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={(+ <Button+ variant="ghost"+ size="icon-sm"+ className="-ml-1 shrink-0 text-white/70 hover:bg-white/10 hover:text-white"+ aria-label="New terminal with a shell"+ title="New terminal with…"+ >+ <ChevronDown className="size-3.5" />+ </Button>+ )}+ />+ <DropdownMenuContent className="w-48">+ {shells.map((shell) => (+ <DropdownMenuItem key={shell.id} onClick={() => addTab(shell.id)}>+ <span className="truncate">{shell.label}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : null}+ </div>+ <div className="hidden max-w-[40%] shrink truncate px-2 text-white/45 md:block" title={status?.text}>+ {status?.text}+ </div>+ </>+ )}+ <Button variant="ghost" size="icon-sm" className="shrink-0 text-white/70 hover:bg-white/10 hover:text-white" onClick={onClose}><X className="size-4" /><span className="sr-only">Hide terminal</span></Button>@@ -129,3 +179,70 @@ export function TerminalDock({ workspaceRoot, isRemoteWorkspace, onClose }: Term</section>);}++function TerminalTabButton(props: {+ tab: TerminalTab;+ active: boolean;+ renaming: boolean;+ exited: boolean;+ onSelect: () => void;+ onClose: () => void;+ onStartRename: () => void;+ onRename: (name: string) => void;+ onCancelRename: () => void;+}) {+ const [draft, setDraft] = useState(props.tab.name);+ useEffect(() => {+ if (props.renaming) setDraft(props.tab.name);+ }, [props.renaming, props.tab.name]);++ if (props.renaming) {+ return (+ <input+ autoFocus+ aria-label="Terminal name"+ className="h-6 w-32 shrink-0 rounded border border-white/30 bg-black/60 px-1.5 text-xs text-white outline-none"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onFocus={(event) => event.target.select()}+ onBlur={() => props.onRename(draft)}+ onKeyDown={(event) => {+ if (event.key === "Enter") props.onRename(draft);+ if (event.key === "Escape") props.onCancelRename();+ event.stopPropagation();+ }}+ />+ );+ }+ return (+ <div+ role="tab"+ aria-selected={props.active}+ tabIndex={0}+ title={`${props.tab.name} (double-click to rename)`}+ className={`group flex h-6 max-w-44 shrink-0 cursor-default items-center gap-1 rounded pl-2 pr-1 ${props.active ? "bg-white/15 text-white" : "text-white/60 hover:bg-white/10 hover:text-white"}`}+ onClick={props.onSelect}+ onDoubleClick={props.onStartRename}+ onAuxClick={(event) => {+ if (event.button === 1) props.onClose();+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") props.onSelect();+ if (event.key === "F2") props.onStartRename();+ }}+ >+ <span className={`truncate ${props.exited ? "line-through opacity-60" : ""}`}>{props.tab.name}</span>+ <button+ type="button"+ aria-label={`Close ${props.tab.name}`}+ className={`flex size-4 items-center justify-center rounded hover:bg-white/20 ${props.active ? "opacity-80" : "opacity-0 group-hover:opacity-80"}`}+ onClick={(event) => {+ event.stopPropagation();+ props.onClose();+ }}+ >+ <X className="size-3" />+ </button>+ </div>+ );+}diff --git a/apps/app/src/react-app/domains/session/terminal/terminal-runtime.ts b/apps/app/src/react-app/domains/session/terminal/terminal-runtime.tsnew file mode 100644index 00000000..80d541db--- /dev/null+++ b/apps/app/src/react-app/domains/session/terminal/terminal-runtime.ts@@ -0,0 +1,226 @@+// The live side of terminal tabs: one xterm and (once the tab is first shown)+// one desktop shell per tab, kept for the whole app run so hiding the dock+// or switching workspaces never loses a shell or its scrollback. The dock+// only moves a tab's xterm element in and out of view.+import { FitAddon } from "@xterm/addon-fit";+import { Terminal } from "@xterm/xterm";+import { create } from "zustand";+import { useTerminalTabsStore } from "./terminal-tabs-store";++export type TerminalBridge = {+ create: (options: { cwd: string; cols: number; rows: number; workspaceId?: string; shellId?: string | null }) => Promise<{ terminalId: string; shellLabel?: string; cwd?: string }>;+ write: (terminalId: string, data: string) => Promise<void>;+ resize: (terminalId: string, cols: number, rows: number) => Promise<void>;+ kill: (terminalId: string) => Promise<void>;+ onData: (callback: (payload: { terminalId: string; data: string }) => void) => () => void;+ onExit: (callback: (payload: { terminalId: string; exitCode: number | null; signal?: number }) => void) => () => void;+ killWorkspace?: (workspaceId: string) => Promise<void>;+ shells?: () => Promise<Array<{ id: string; label: string }>>;+};++export type TerminalTabStatus = { state: "idle" | "starting" | "running" | "exited" | "error"; text: string };++type Live = {+ term: Terminal;+ fit: FitAddon;+ host: HTMLDivElement;+ opened: boolean;+ terminalId: string | null;+ exited: boolean;+ starting: boolean;+ disposed: boolean;+ options: { workspaceId: string; cwd: string; shellId: string | null };+};++/** Per-tab status line for the dock. */+export const useTerminalStatusStore = create<{ status: Record<string, TerminalTabStatus> }>(() => ({ status: {} }));++function setStatus(tabId: string, status: TerminalTabStatus | null) {+ const next = { ...useTerminalStatusStore.getState().status };+ if (status) next[tabId] = status;+ else delete next[tabId];+ useTerminalStatusStore.setState({ status: next });+}++const live = new Map<string, Live>();+const byTerminalId = new Map<string, string>();+let bridgeListeners: { onData: TerminalBridge["onData"]; off: () => void } | null = null;++function listen(bridge: TerminalBridge) {+ if (bridgeListeners?.onData === bridge.onData) return;+ bridgeListeners?.off();+ const offData = bridge.onData(({ terminalId, data }) => {+ const tabId = byTerminalId.get(terminalId);+ if (tabId) live.get(tabId)?.term.write(data);+ });+ const offExit = bridge.onExit(({ terminalId, exitCode }) => {+ const tabId = byTerminalId.get(terminalId);+ byTerminalId.delete(terminalId);+ const entry = tabId ? live.get(tabId) : undefined;+ if (!tabId || !entry) return;+ entry.terminalId = null;+ entry.exited = true;+ entry.term.write(`\r\n\x1b[2m[Process exited${exitCode === null ? "" : ` with code ${exitCode}`}. Press Enter to start a new shell.]\x1b[0m\r\n`);+ setStatus(tabId, { state: "exited", text: `Exited${exitCode === null ? "" : ` (${exitCode})`}` });+ });+ bridgeListeners = { onData: bridge.onData, off: () => { offData(); offExit(); } };+}++function makeLive(tabId: string, bridge: TerminalBridge, options: Live["options"]): Live {+ const host = document.createElement("div");+ host.className = "h-full w-full";+ host.dataset.terminalTab = tabId;+ const term = new Terminal({+ cursorBlink: true,+ convertEol: true,+ scrollback: 5000,+ fontFamily: "'SFMono-Regular', 'Cascadia Code', 'Liberation Mono', Menlo, monospace",+ fontSize: 12,+ theme: {+ background: "#0b0d12",+ foreground: "#d7dde8",+ cursor: "#ffffff",+ selectionBackground: "#334155",+ },+ });+ const fit = new FitAddon();+ term.loadAddon(fit);+ const entry: Live = { term, fit, host, opened: false, terminalId: null, exited: false, starting: false, disposed: false, options };+ term.onData((data) => {+ if (entry.terminalId) {+ void bridge.write(entry.terminalId, data);+ return;+ }+ if (entry.exited && (data === "\r" || data === "\n")) {+ entry.exited = false;+ term.clear();+ void start(tabId, bridge);+ }+ });+ live.set(tabId, entry);+ return entry;+}++async function start(tabId: string, bridge: TerminalBridge) {+ const entry = live.get(tabId);+ if (!entry || entry.starting || entry.terminalId || entry.disposed) return;+ entry.starting = true;+ setStatus(tabId, { state: "starting", text: "Starting…" });+ try {+ const { terminalId, shellLabel, cwd } = await bridge.create({+ cwd: entry.options.cwd,+ cols: entry.term.cols,+ rows: entry.term.rows,+ workspaceId: entry.options.workspaceId,+ shellId: entry.options.shellId,+ });+ if (entry.disposed) {+ void bridge.kill(terminalId);+ return;+ }+ entry.terminalId = terminalId;+ byTerminalId.set(terminalId, tabId);+ setStatus(tabId, { state: "running", text: [shellLabel, cwd ?? entry.options.cwd].filter(Boolean).join(" · ") });+ fitTab(tabId, bridge);+ } catch (error) {+ setStatus(tabId, { state: "error", text: error instanceof Error ? error.message : "Could not start the terminal." });+ } finally {+ entry.starting = false;+ }+}++function fitTab(tabId: string, bridge: TerminalBridge) {+ const entry = live.get(tabId);+ if (!entry?.opened || !entry.host.isConnected) return;+ try {+ entry.fit.fit();+ } catch {+ return;+ }+ if (entry.terminalId) void bridge.resize(entry.terminalId, entry.term.cols, entry.term.rows);+}++/**+ * Shows a tab in `container`: creates its xterm on first use and starts its+ * shell (lazily, only for a tab someone looks at). Returns the detach+ * function, which keeps the shell and scrollback for the next show.+ */+export function showTerminalTab(input: {+ tabId: string;+ container: HTMLElement;+ bridge: TerminalBridge;+ workspaceId: string;+ cwd: string;+ shellId: string | null;+ focus?: boolean;+}): () => void {+ const { tabId, container, bridge } = input;+ listen(bridge);+ const entry = live.get(tabId) ?? makeLive(tabId, bridge, { workspaceId: input.workspaceId, cwd: input.cwd, shellId: input.shellId });+ container.appendChild(entry.host);+ if (!entry.opened) {+ entry.term.open(entry.host);+ entry.opened = true;+ }+ fitTab(tabId, bridge);+ if (!entry.terminalId && !entry.exited) void start(tabId, bridge);+ if (input.focus !== false) entry.term.focus();+ const observer = new ResizeObserver(() => fitTab(tabId, bridge));+ observer.observe(container);+ return () => {+ observer.disconnect();+ if (entry.host.parentElement === container) container.removeChild(entry.host);+ };+}++/** Ends a tab's shell and drops its xterm. */+export function disposeTerminalTab(tabId: string, bridge: TerminalBridge | null) {+ const entry = live.get(tabId);+ live.delete(tabId);+ setStatus(tabId, null);+ if (!entry) return;+ entry.disposed = true;+ if (entry.terminalId) {+ byTerminalId.delete(entry.terminalId);+ void bridge?.kill(entry.terminalId);+ }+ entry.host.remove();+ entry.term.dispose();+}++/** Ends every shell of a workspace (it is being removed), including tabs never shown. */+export async function disposeWorkspaceTerminals(workspaceId: string, tabIds: string[], bridge: TerminalBridge | null) {+ for (const tabId of tabIds) disposeTerminalTab(tabId, bridge);+ for (const [tabId, entry] of live) {+ if (entry.options.workspaceId === workspaceId) disposeTerminalTab(tabId, bridge);+ }+ await bridge?.killWorkspace?.(workspaceId);+}++/** Whether a tab has a running shell (for tests and the dock). */+export function terminalTabRunning(tabId: string) {+ return Boolean(live.get(tabId)?.terminalId);+}++/** The desktop's terminal bridge, or null outside the desktop app (or an older preload). */+export function desktopTerminalBridge(): TerminalBridge | null {+ if (typeof window === "undefined") return null;+ const bridge = window.__OMNIRUSH_ELECTRON__?.terminal;+ if (!bridge?.create || !bridge.write || !bridge.resize || !bridge.kill || !bridge.onData || !bridge.onExit) return null;+ return {+ create: bridge.create,+ write: bridge.write,+ resize: bridge.resize,+ kill: bridge.kill,+ onData: bridge.onData,+ onExit: bridge.onExit,+ ...(bridge.killWorkspace ? { killWorkspace: bridge.killWorkspace } : {}),+ ...(bridge.shells ? { shells: bridge.shells } : {}),+ };+}++/** A workspace is being removed: its tabs are forgotten and every shell it had ends. */+export async function closeWorkspaceTerminals(workspaceId: string) {+ const tabIds = useTerminalTabsStore.getState().forgetWorkspace(workspaceId);+ await disposeWorkspaceTerminals(workspaceId, tabIds, desktopTerminalBridge());+}diff --git a/apps/app/src/react-app/domains/session/terminal/terminal-tabs-store.ts b/apps/app/src/react-app/domains/session/terminal/terminal-tabs-store.tsnew file mode 100644index 00000000..8ec19469--- /dev/null+++ b/apps/app/src/react-app/domains/session/terminal/terminal-tabs-store.ts@@ -0,0 +1,192 @@+// Terminal tabs per workspace. The tab list (names, shells, which one is+// active) lives here for the whole app run and is saved to localStorage, so+// a restart brings the same tabs back; their shells start again only when a+// tab is first shown. The shells themselves live in terminal-runtime.ts.+import { create } from "zustand";++export type TerminalTab = {+ id: string;+ name: string;+ /** The shell the tab started with (the desktop's shell list id); null = default. */+ shellId: string | null;+};++export type WorkspaceTerminalTabs = {+ tabs: TerminalTab[];+ activeId: string | null;+ /** Number for the next default tab name ("Terminal 3"). */+ nextNumber: number;+};++type SavedTabs = Record<string, { tabs: Array<{ name: string; shellId: string | null }>; active: number }>;++export const TERMINAL_TABS_STORAGE_KEY = "omnirush.terminal-tabs.v1";+const MAX_NAME_CHARS = 60;++let tabCounter = 0;+const newTabId = () => `tab_${Date.now().toString(36)}_${(tabCounter += 1)}`;++function storage(): Storage | null {+ try {+ return typeof localStorage === "undefined" ? null : localStorage;+ } catch {+ return null;+ }+}++function readSaved(): SavedTabs {+ let parsed: unknown = null;+ try {+ const raw = storage()?.getItem(TERMINAL_TABS_STORAGE_KEY);+ parsed = raw ? JSON.parse(raw) : null;+ } catch {+ return {};+ }+ const saved: SavedTabs = {};+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return saved;+ for (const [workspaceId, value] of Object.entries(parsed)) {+ if (!value || typeof value !== "object" || !Array.isArray(value.tabs)) continue;+ const tabs = value.tabs.flatMap((tab: unknown) => {+ if (!tab || typeof tab !== "object" || !("name" in tab) || typeof tab.name !== "string") return [];+ return [{ name: tab.name, shellId: "shellId" in tab && typeof tab.shellId === "string" ? tab.shellId : null }];+ });+ if (tabs.length) saved[workspaceId] = { tabs, active: "active" in value && typeof value.active === "number" ? value.active : 0 };+ }+ return saved;+}++/** Saves the loaded workspaces' tabs over the saved ones; workspaces not loaded this run keep theirs. */+function writeSaved(byWorkspace: Record<string, WorkspaceTerminalTabs>, forget?: string) {+ const saved = readSaved();+ if (forget) delete saved[forget];+ for (const [workspaceId, entry] of Object.entries(byWorkspace)) {+ if (!entry.tabs.length) {+ delete saved[workspaceId];+ continue;+ }+ saved[workspaceId] = {+ tabs: entry.tabs.map(({ name, shellId }) => ({ name, shellId })),+ active: Math.max(0, entry.tabs.findIndex((tab) => tab.id === entry.activeId)),+ };+ }+ try {+ storage()?.setItem(TERMINAL_TABS_STORAGE_KEY, JSON.stringify(saved));+ } catch {+ // Private mode or a full quota: tabs still work for this run.+ }+}++/** The saved tabs of one workspace, as fresh tab entries (no shell yet). */+function restore(workspaceId: string): WorkspaceTerminalTabs | null {+ const saved = readSaved()[workspaceId];+ if (!saved) return null;+ const tabs = saved.tabs.map((tab) => ({ id: newTabId(), name: cleanName(tab.name) || "Terminal", shellId: tab.shellId }));+ const active = tabs[Math.min(Math.max(0, Math.floor(saved.active)), tabs.length - 1)];+ const numbers = tabs.map((tab) => /^Terminal (\d+)$/.exec(tab.name)?.[1]).filter(Boolean).map(Number);+ return { tabs, activeId: active.id, nextNumber: Math.max(tabs.length, ...numbers) + 1 };+}++export function cleanName(name: string) {+ return name.replace(/\s+/g, " ").trim().slice(0, MAX_NAME_CHARS);+}++type TerminalTabsState = {+ byWorkspace: Record<string, WorkspaceTerminalTabs>;+ /** Pending "new tab" requests from the keyboard shortcut, consumed by the open dock. */+ newTabRequests: number;+ /** The workspace's tabs, restored from the last run on first use. */+ ensure: (workspaceId: string) => WorkspaceTerminalTabs;+ addTab: (workspaceId: string, shellId?: string | null) => TerminalTab;+ /** Removes a tab; returns the tabs left in that workspace. */+ closeTab: (workspaceId: string, tabId: string) => number;+ renameTab: (workspaceId: string, tabId: string, name: string) => void;+ setActive: (workspaceId: string, tabId: string) => void;+ /** Moves the active tab by `step` (wrapping). */+ cycle: (workspaceId: string, step: number) => void;+ /** Forgets a removed workspace's tabs; returns their ids. */+ forgetWorkspace: (workspaceId: string) => string[];+ requestNewTab: () => void;+ takeNewTabRequest: () => boolean;+};++const empty = (): WorkspaceTerminalTabs => ({ tabs: [], activeId: null, nextNumber: 1 });++export const useTerminalTabsStore = create<TerminalTabsState>((set, get) => {+ const update = (workspaceId: string, next: WorkspaceTerminalTabs) => {+ const byWorkspace = { ...get().byWorkspace, [workspaceId]: next };+ set({ byWorkspace });+ writeSaved(byWorkspace);+ };+ const current = (workspaceId: string) => get().ensure(workspaceId);++ return {+ byWorkspace: {},+ newTabRequests: 0,++ ensure(workspaceId) {+ const known = get().byWorkspace[workspaceId];+ if (known) return known;+ const entry = restore(workspaceId) ?? empty();+ set({ byWorkspace: { ...get().byWorkspace, [workspaceId]: entry } });+ return entry;+ },++ addTab(workspaceId, shellId = null) {+ const entry = current(workspaceId);+ const tab = { id: newTabId(), name: `Terminal ${entry.nextNumber}`, shellId };+ update(workspaceId, { tabs: [...entry.tabs, tab], activeId: tab.id, nextNumber: entry.nextNumber + 1 });+ return tab;+ },++ closeTab(workspaceId, tabId) {+ const entry = current(workspaceId);+ const index = entry.tabs.findIndex((tab) => tab.id === tabId);+ if (index < 0) return entry.tabs.length;+ const tabs = entry.tabs.filter((tab) => tab.id !== tabId);+ const activeId = entry.activeId !== tabId ? entry.activeId : (tabs[Math.min(index, tabs.length - 1)]?.id ?? null);+ // Numbering starts over once every tab is closed.+ update(workspaceId, { tabs, activeId, nextNumber: tabs.length ? entry.nextNumber : 1 });+ return tabs.length;+ },++ renameTab(workspaceId, tabId, name) {+ const entry = current(workspaceId);+ const clean = cleanName(name);+ if (!clean) return;+ update(workspaceId, { ...entry, tabs: entry.tabs.map((tab) => (tab.id === tabId ? { ...tab, name: clean } : tab)) });+ },++ setActive(workspaceId, tabId) {+ const entry = current(workspaceId);+ if (entry.activeId === tabId || !entry.tabs.some((tab) => tab.id === tabId)) return;+ update(workspaceId, { ...entry, activeId: tabId });+ },++ cycle(workspaceId, step) {+ const entry = current(workspaceId);+ if (entry.tabs.length < 2) return;+ const index = entry.tabs.findIndex((tab) => tab.id === entry.activeId);+ const next = entry.tabs[(index + step + entry.tabs.length) % entry.tabs.length];+ update(workspaceId, { ...entry, activeId: next.id });+ },++ forgetWorkspace(workspaceId) {+ const entry = get().byWorkspace[workspaceId] ?? restore(workspaceId);+ const byWorkspace = { ...get().byWorkspace };+ delete byWorkspace[workspaceId];+ set({ byWorkspace });+ writeSaved(byWorkspace, workspaceId);+ return entry?.tabs.map((tab) => tab.id) ?? [];+ },++ requestNewTab() {+ set({ newTabRequests: get().newTabRequests + 1 });+ },++ takeNewTabRequest() {+ if (!get().newTabRequests) return false;+ set({ newTabRequests: get().newTabRequests - 1 });+ return true;+ },+ };+});diff --git a/apps/app/src/react-app/shell/route-workspaces.ts b/apps/app/src/react-app/shell/route-workspaces.tsindex ff3ebf71..fa85f13f 100644--- a/apps/app/src/react-app/shell/route-workspaces.ts+++ b/apps/app/src/react-app/shell/route-workspaces.ts@@ -148,7 +148,10 @@ export async function removeRouteWorkspace(input: {workspaceId: string;deleteFromServer: ((workspaceId: string) => Promise<unknown>) | null;forgetOnDesktop: ((workspaceId: string) => Promise<unknown>) | null;+ /** Ends the workspace's terminal shells first: an open shell keeps its folder busy (and locked on Windows). */+ closeTerminals?: ((workspaceId: string) => Promise<unknown>) | null;}): Promise<void> {+ await input.closeTerminals?.(input.workspaceId);if (input.deleteFromServer) {try {await input.deleteFromServer(input.workspaceId);diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex 6de0d20b..e5f23402 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -10,6 +10,7 @@ import {import { useLocation, useNavigate } from "react-router";import { Archive, ArchiveRestore } from "lucide-react";import { toast } from "@/components/ui/sonner";+import { closeWorkspaceTerminals } from "../domains/session/terminal/terminal-runtime";import type { ProviderListResponse } from "@opencode-ai/sdk/v2/client";import { captureAnalyticsEvent, markTaskRunStart } from "@/app/lib/analytics";@@ -2120,6 +2121,7 @@ export function SessionRoute() {workspaceId,deleteFromServer: client ? (id) => client.deleteWorkspace(id) : null,forgetOnDesktop: isDesktopRuntime() ? workspaceForget : null,+ closeTerminals: closeWorkspaceTerminals,});} catch (error) {console.error("[session-route] remove workspace failed", error);diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex f92d701c..28226a19 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -2,6 +2,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Navigate, useLocation, useNavigate, useParams } from "react-router";import { toast } from "@/components/ui/sonner";+import { closeWorkspaceTerminals } from "../domains/session/terminal/terminal-runtime";import {SUGGESTED_PLUGINS,@@ -2195,6 +2196,7 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {workspaceId,deleteFromServer: omnirushClient ? (id) => omnirushClient.deleteWorkspace(id) : null,forgetOnDesktop: isDesktopRuntime() ? workspaceForget : null,+ closeTerminals: closeWorkspaceTerminals,});} catch (error) {console.error("[settings-route] remove workspace failed", error);diff --git a/apps/app/src/react-app/shell/use-shell-shortcuts.ts b/apps/app/src/react-app/shell/use-shell-shortcuts.tsindex daa0e6ce..1874840b 100644--- a/apps/app/src/react-app/shell/use-shell-shortcuts.ts+++ b/apps/app/src/react-app/shell/use-shell-shortcuts.ts@@ -22,6 +22,7 @@ import {type ThinkingModeShortcutDirection,} from "./thinking-mode-shortcut";import { isFavoriteModelShortcut } from "./favorite-model-shortcut";+import { useTerminalTabsStore } from "../domains/session/terminal/terminal-tabs-store";export type UseShellShortcutsInput = {canCreateTask: boolean;@@ -53,6 +54,11 @@ export function useCommandPaletteShortcut(enabled = true) {return { commandPaletteOpen, setCommandPaletteOpen };}+/** Ctrl+Shift+` (the Backquote key, whatever the layout prints on it): a new terminal tab. */+export function isNewTerminalShortcut(event: Pick<KeyboardEvent, "ctrlKey" | "shiftKey" | "altKey" | "metaKey" | "code">) {+ return event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey && event.code === "Backquote";+}+export function useShellShortcuts(input: UseShellShortcutsInput) {const platform = usePlatform();const {@@ -109,6 +115,7 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {// Cmd/Ctrl+N -> new task in selected workspace// Cmd/Ctrl+K -> toggle command palette// Cmd/Ctrl+J -> toggle terminal panel (matches VS Code)+ // Ctrl+Shift+` -> new terminal tab (matches VS Code; Ctrl on macOS too)// Cmd/Ctrl+F -> find in current conversation (handled by session surface)// Cmd/Ctrl+Shift+F -> search every session (titles + messages)// Cmd/Ctrl+T -> next session tab@@ -123,6 +130,13 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {if (!event.repeat) onCycleFavoriteModel?.();return;}+ if (isNewTerminalShortcut(event) && platform.capabilities.terminal) {+ event.preventDefault();+ if (event.repeat) return;+ useTerminalTabsStore.getState().requestNewTab();+ setTerminalOpen(true);+ return;+ }const thinkingModeDirection = getThinkingModeShortcutDirection(event, thinkingModeShortcutOs);if (thinkingModeDirection) {event.preventDefault();diff --git a/apps/app/tests/terminal-tabs-store.test.ts b/apps/app/tests/terminal-tabs-store.test.tsnew file mode 100644index 00000000..0b48be3c--- /dev/null+++ b/apps/app/tests/terminal-tabs-store.test.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, test } from "bun:test";++import { TERMINAL_TABS_STORAGE_KEY, useTerminalTabsStore } from "../src/react-app/domains/session/terminal/terminal-tabs-store";+import { isNewTerminalShortcut } from "../src/react-app/shell/use-shell-shortcuts";+import { removeRouteWorkspace } from "../src/react-app/shell/route-workspaces";++class MemoryStorage {+ data = new Map<string, string>();+ getItem(key: string) { return this.data.get(key) ?? null; }+ setItem(key: string, value: string) { this.data.set(key, value); }+ removeItem(key: string) { this.data.delete(key); }+}++const memory = new MemoryStorage();+Object.defineProperty(globalThis, "localStorage", { value: memory, configurable: true });++const store = () => useTerminalTabsStore.getState();+const names = (workspaceId: string) => store().ensure(workspaceId).tabs.map((tab) => tab.name);+/** A new app run: nothing loaded yet, only what was saved. */+const restart = () => useTerminalTabsStore.setState({ byWorkspace: {}, newTabRequests: 0 });++beforeEach(() => {+ memory.data.clear();+ restart();+});++describe("terminal tabs", () => {+ test("each workspace has its own tabs: new, switch, rename, close", () => {+ const one = store().addTab("ws_a");+ const two = store().addTab("ws_a", "cmd");+ store().addTab("ws_b");+ expect(names("ws_a")).toEqual(["Terminal 1", "Terminal 2"]);+ expect(names("ws_b")).toEqual(["Terminal 1"]);+ expect(store().ensure("ws_a").activeId).toBe(two.id);+ expect(store().ensure("ws_a").tabs[1].shellId).toBe("cmd");++ store().setActive("ws_a", one.id);+ expect(store().ensure("ws_a").activeId).toBe(one.id);+ store().cycle("ws_a", 1);+ expect(store().ensure("ws_a").activeId).toBe(two.id);+ store().cycle("ws_a", 1);+ expect(store().ensure("ws_a").activeId).toBe(one.id);++ store().renameTab("ws_a", one.id, " dev server ");+ expect(names("ws_a")).toEqual(["dev server", "Terminal 2"]);+ store().renameTab("ws_a", one.id, " ");+ expect(names("ws_a")).toEqual(["dev server", "Terminal 2"]);++ // Closing the active tab activates its neighbour; the next new tab keeps counting.+ expect(store().closeTab("ws_a", one.id)).toBe(1);+ expect(store().ensure("ws_a").activeId).toBe(two.id);+ store().addTab("ws_a");+ expect(names("ws_a")).toEqual(["Terminal 2", "Terminal 3"]);+ // Once every tab is closed, numbering starts over.+ for (const tab of store().ensure("ws_a").tabs) store().closeTab("ws_a", tab.id);+ expect(store().ensure("ws_a").activeId).toBeNull();+ store().addTab("ws_a");+ expect(names("ws_a")).toEqual(["Terminal 1"]);+ expect(names("ws_b")).toEqual(["Terminal 1"]);+ });++ test("tab names, shells and the active tab come back after a restart; other workspaces keep theirs", () => {+ const first = store().addTab("ws_a");+ store().addTab("ws_a", "pwsh");+ store().renameTab("ws_a", first.id, "server");+ store().setActive("ws_a", first.id);+ store().addTab("ws_b");++ restart();+ // Touching one workspace saves it without dropping the other's saved tabs.+ store().addTab("ws_b");+ restart();+ const a = store().ensure("ws_a");+ expect(a.tabs.map((tab) => [tab.name, tab.shellId])).toEqual([["server", null], ["Terminal 2", "pwsh"]]);+ expect(a.activeId).toBe(a.tabs[0].id);+ expect(names("ws_b")).toEqual(["Terminal 1", "Terminal 2"]);+ store().addTab("ws_a");+ expect(names("ws_a")).toEqual(["server", "Terminal 2", "Terminal 3"]);+ });++ test("a removed workspace's tabs are forgotten, saved ones too", () => {+ store().addTab("ws_a");+ store().addTab("ws_b");+ restart();+ // ws_a was never loaded in this run.+ expect(store().forgetWorkspace("ws_a")).toHaveLength(1);+ restart();+ expect(names("ws_a")).toEqual([]);+ expect(names("ws_b")).toEqual(["Terminal 1"]);+ expect(Object.keys(JSON.parse(memory.getItem(TERMINAL_TABS_STORAGE_KEY) ?? "{}"))).toEqual(["ws_b"]);+ });++ test("broken saved data is ignored", () => {+ memory.setItem(TERMINAL_TABS_STORAGE_KEY, "{not json");+ expect(names("ws_a")).toEqual([]);+ memory.setItem(TERMINAL_TABS_STORAGE_KEY, JSON.stringify({ ws_a: { tabs: [{ name: 5 }, { name: "ok", shellId: 3 }], active: 9 } }));+ restart();+ const a = store().ensure("ws_a");+ expect(a.tabs.map((tab) => [tab.name, tab.shellId])).toEqual([["ok", null]]);+ expect(a.activeId).toBe(a.tabs[0].id);+ });++ test("the new-terminal shortcut is Ctrl+Shift+` and queues one tab per press", () => {+ const key = { ctrlKey: true, shiftKey: true, altKey: false, metaKey: false, code: "Backquote" };+ expect(isNewTerminalShortcut(key)).toBe(true);+ expect(isNewTerminalShortcut({ ...key, shiftKey: false })).toBe(false);+ expect(isNewTerminalShortcut({ ...key, metaKey: true })).toBe(false);+ expect(isNewTerminalShortcut({ ...key, code: "KeyT" })).toBe(false);+ store().requestNewTab();+ expect(store().takeNewTabRequest()).toBe(true);+ expect(store().takeNewTabRequest()).toBe(false);+ });++ test("removing a workspace ends its terminals before the server removes the folder", async () => {+ const order: string[] = [];+ await removeRouteWorkspace({+ workspaceId: "ws_1",+ closeTerminals: async (id) => { order.push(`terminals ${id}`); },+ deleteFromServer: async (id) => { order.push(`server ${id}`); },+ forgetOnDesktop: async (id) => { order.push(`desktop ${id}`); },+ });+ expect(order).toEqual(["terminals ws_1", "server ws_1", "desktop ws_1"]);+ });+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 1b049190..598fca1f 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -38,6 +38,7 @@ import { applyBrandAppName } from "./brand-app-name.mjs";import { createBrowserLoginSync } from "./browser-login-sync.mjs";import { createBrowserPanel } from "./browser-panel.mjs";import { createWorkspaceStore } from "./workspace-store.mjs";+import { createTerminalSessions, terminalShells } from "./terminal-sessions.mjs";import {buildNukeManifest,executeNukeFreshStart,@@ -192,14 +193,6 @@ const uiControlServer = createUiControlServer({},});-const terminalProcesses = new Map();-let nextTerminalId = 1;--function defaultTerminalShell() {- if (process.platform === "win32") return process.env.COMSPEC || "powershell.exe";- return process.env.SHELL || (process.platform === "darwin" ? "/bin/zsh" : "/bin/bash");-}-async function resolveTerminalCwd(cwd) {const fallback = os.homedir();if (typeof cwd !== "string" || !cwd.trim()) return fallback;@@ -208,23 +201,25 @@ async function resolveTerminalCwd(cwd) {return info?.isDirectory() ? candidate : fallback;}-function terminalForSender(event, terminalId) {- const terminal = terminalProcesses.get(String(terminalId ?? ""));- if (!terminal || terminal.webContentsId !== event.sender.id) return null;- return terminal;-}+// Terminal tabs: one shell per tab, owned by the window that opened it.+const terminalShellList = terminalShells({ platform: process.platform, env: process.env, exists: (file) => existsSync(file) });+const terminalSessions = createTerminalSessions({+ spawn: (file, args, options) => pty.spawn(file, args, options),+ resolveCwd: resolveTerminalCwd,+ shells: () => terminalShellList,+});+/** Windows whose terminals end with them (closed, crashed or reloaded). */+const terminalOwners = new WeakSet();-function killTerminal(terminalId) {- const terminal = terminalProcesses.get(terminalId);- if (!terminal) return;- terminalProcesses.delete(terminalId);- try { terminal.process.kill(); } catch { /* already gone */ }-}--function killTerminalsForWebContents(webContentsId) {- for (const [terminalId, terminal] of terminalProcesses.entries()) {- if (terminal.webContentsId === webContentsId) killTerminal(terminalId);- }+function watchTerminalOwner(contents) {+ if (terminalOwners.has(contents)) return;+ terminalOwners.add(contents);+ const ownerId = contents.id;+ const endAll = () => { void terminalSessions.killOwner(ownerId); };+ contents.once("destroyed", endAll);+ contents.on("render-process-gone", endAll);+ // A reload starts a new page with no tabs: the old page's shells go with it.+ contents.on("did-navigate", endAll);}// Production Electron shares the same on-disk state folder as the Tauri shell@@ -1873,6 +1868,9 @@ const desktopCommandHandlers = {return workspaceStore.updateWorkspaceDisplayName(args[0] ?? {});},"workspaceForget": async (event, ...args) => {+ // A removed workspace's terminal shells end first (on Windows an open+ // shell keeps its folder locked).+ await terminalSessions.killWorkspace(String(args[0] ?? "").trim());return workspaceStore.forgetWorkspace(String(args[0] ?? "").trim());},"workspaceAddAuthorizedRoot": async (event, ...args) => {@@ -2775,54 +2773,34 @@ ipcMain.handle("omnirush:system:askMicrophoneAccess", async () => {});// ── Terminal IPC ────────────────────────────────────────────────────────+ipcMain.handle("omnirush:terminal:shells", () => terminalShellList.map(({ id, label }) => ({ id, label })));ipcMain.handle("omnirush:terminal:create", async (event, options = {}) => {assertDesktopActivation();- const cwd = await resolveTerminalCwd(options?.cwd);- const cols = Number.isFinite(options?.cols) ? Math.max(20, Math.floor(options.cols)) : 80;- const rows = Number.isFinite(options?.rows) ? Math.max(5, Math.floor(options.rows)) : 24;- const terminalId = `term_${nextTerminalId++}`;- const shellPath = defaultTerminalShell();- const child = pty.spawn(shellPath, [], {- name: "xterm-256color",- cols,- rows,- cwd,- env: {- ...process.env,- TERM: "xterm-256color",- COLORTERM: "truecolor",- OMNIRUSH_TERMINAL: "1",+ const contents = event.sender;+ watchTerminalOwner(contents);+ return terminalSessions.create({+ ownerId: contents.id,+ workspaceId: typeof options?.workspaceId === "string" ? options.workspaceId : null,+ cwd: options?.cwd,+ cols: options?.cols,+ rows: options?.rows,+ shellId: typeof options?.shellId === "string" ? options.shellId : null,+ send: (channel, payload) => {+ if (!contents.isDestroyed()) contents.send(channel, payload);},});-- terminalProcesses.set(terminalId, { process: child, webContentsId: event.sender.id });- event.sender.once("destroyed", () => killTerminalsForWebContents(event.sender.id));- child.onData((data) => {- if (event.sender.isDestroyed()) return;- event.sender.send("omnirush:terminal:data", { terminalId, data });- });- child.onExit(({ exitCode, signal }) => {- terminalProcesses.delete(terminalId);- if (event.sender.isDestroyed()) return;- event.sender.send("omnirush:terminal:exit", { terminalId, exitCode, signal });- });-- return { terminalId };});ipcMain.handle("omnirush:terminal:write", (event, terminalId, data) => {- const terminal = terminalForSender(event, terminalId);- if (!terminal || typeof data !== "string") return;- terminal.process.write(data);+ terminalSessions.write(event.sender.id, terminalId, data);});ipcMain.handle("omnirush:terminal:resize", (event, terminalId, cols, rows) => {- const terminal = terminalForSender(event, terminalId);- if (!terminal || !Number.isFinite(cols) || !Number.isFinite(rows)) return;- terminal.process.resize(Math.max(20, Math.floor(cols)), Math.max(5, Math.floor(rows)));+ terminalSessions.resize(event.sender.id, terminalId, cols, rows);+});+ipcMain.handle("omnirush:terminal:kill", async (event, terminalId) => {+ await terminalSessions.kill(event.sender.id, terminalId);});-ipcMain.handle("omnirush:terminal:kill", (event, terminalId) => {- const terminal = terminalForSender(event, terminalId);- if (!terminal) return;- killTerminal(String(terminalId));+ipcMain.handle("omnirush:terminal:killWorkspace", async (event, workspaceId) => {+ await terminalSessions.killWorkspace(workspaceId, event.sender.id);});browserPanel.registerIpc(ipcMain);@@ -2905,6 +2883,7 @@ or use: pnpm dev:worktree`);await Promise.all([disposeRuntimeBeforeQuit(),uiControlServer.stop(),+ terminalSessions.killAll(),]);} finally {scheduleBlankSlateProfileCleanup();diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjsindex e89b892f..4999a418 100644--- a/apps/desktop/electron/preload.mjs+++ b/apps/desktop/electron/preload.mjs@@ -248,7 +248,9 @@ contextBridge.exposeInMainWorld("__OMNIRUSH_ELECTRON__", {} : {}),},terminal: {+ shells() { return ipcRenderer.invoke("omnirush:terminal:shells"); },create(options) { return ipcRenderer.invoke("omnirush:terminal:create", options); },+ killWorkspace(workspaceId) { return ipcRenderer.invoke("omnirush:terminal:killWorkspace", workspaceId); },write(terminalId, data) { return ipcRenderer.invoke("omnirush:terminal:write", terminalId, data); },resize(terminalId, cols, rows) { return ipcRenderer.invoke("omnirush:terminal:resize", terminalId, cols, rows); },kill(terminalId) { return ipcRenderer.invoke("omnirush:terminal:kill", terminalId); },diff --git a/apps/desktop/electron/terminal-sessions.mjs b/apps/desktop/electron/terminal-sessions.mjsnew file mode 100644index 00000000..e2607c7a--- /dev/null+++ b/apps/desktop/electron/terminal-sessions.mjs@@ -0,0 +1,252 @@+// Shells behind the app's terminal tabs. Every tab is one shell (node-pty)+// owned by the window that opened it and tagged with its workspace, so a+// closed tab, a removed workspace, a reloaded or closed window and the app's+// quit each end exactly their shells, together with whatever the shells+// started: nothing a terminal ran outlives the app.+//+// Ending a shell: on macOS and Linux the shell gets SIGHUP (an interactive+// shell passes it on to its jobs, as when a terminal window closes); the+// processes below it that are still alive after a grace period get SIGTERM,+// then SIGKILL. The process tree is read before the shell ends, since its+// children are re-parented once it exits. On Windows the whole tree is ended+// with `taskkill /T /F` before the ConPTY is closed.+import { execFile } from "node:child_process";+import path from "node:path";++const MIN_COLS = 20;+const MIN_ROWS = 5;+const DEFAULT_GRACE_MS = 1500;++function clampSize(value, min, fallback) {+ return Number.isFinite(value) ? Math.max(min, Math.floor(value)) : fallback;+}++/**+ * The shells a new tab can start, default first. Windows: PowerShell (7 when+ * installed, then Windows PowerShell) and Command Prompt. macOS and Linux:+ * the user's login shell ($SHELL), then the other common shells installed.+ * macOS starts login shells (-l), as Terminal.app does, so PATH from the+ * user's profile is there for an app launched from the Dock.+ */+export function terminalShells({ platform = process.platform, env = process.env, exists }) {+ if (platform === "win32") {+ const shells = [];+ const pathDirs = String(env.PATH ?? env.Path ?? "").split(";").filter(Boolean);+ const pwsh = pathDirs.map((dir) => path.win32.join(dir, "pwsh.exe")).find((candidate) => exists(candidate));+ if (pwsh) shells.push({ id: "pwsh", label: "PowerShell 7", path: pwsh, args: ["-NoLogo"] });+ const systemRoot = env.SystemRoot || env.SYSTEMROOT || "C:\\Windows";+ const windowsPowerShell = path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");+ shells.push({ id: "powershell", label: "Windows PowerShell", path: exists(windowsPowerShell) ? windowsPowerShell : "powershell.exe", args: ["-NoLogo"] });+ shells.push({ id: "cmd", label: "Command Prompt", path: env.COMSPEC || env.ComSpec || "cmd.exe", args: [] });+ return shells;+ }+ const loginArgs = (shellPath) => (platform === "darwin" && /(?:^|\/)(?:zsh|bash|fish)$/.test(shellPath) ? ["-l"] : []);+ const preferred = env.SHELL && exists(env.SHELL) ? env.SHELL : platform === "darwin" ? "/bin/zsh" : "/bin/bash";+ const candidates = [preferred, "/bin/zsh", "/bin/bash", "/usr/bin/fish", "/opt/homebrew/bin/fish", "/usr/local/bin/fish", "/bin/sh"];+ const seen = new Set();+ const shells = [];+ for (const candidate of candidates) {+ if (seen.has(candidate) || (candidate !== preferred && !exists(candidate))) continue;+ seen.add(candidate);+ shells.push({ id: path.posix.basename(candidate), label: path.posix.basename(candidate), path: candidate, args: loginArgs(candidate) });+ }+ return shells.filter((shell, index) => shells.findIndex((other) => other.id === shell.id) === index);+}++/** Every process below `rootPid` (children, grandchildren, ...) from a `ps -A -o pid=,ppid=` listing. */+export function descendantsOf(rootPid, listing) {+ const children = new Map();+ for (const line of String(listing).split("\n")) {+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);+ if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;+ const list = children.get(ppid) ?? [];+ list.push(pid);+ children.set(ppid, list);+ }+ const out = [];+ const queue = [rootPid];+ while (queue.length) {+ const next = queue.shift();+ for (const child of children.get(next) ?? []) {+ if (child === rootPid || out.includes(child)) continue;+ out.push(child);+ queue.push(child);+ }+ }+ return out;+}++function defaultRun(command, args) {+ return new Promise((resolve) => {+ execFile(command, args, { windowsHide: true, timeout: 5000, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {+ resolve(error ? "" : String(stdout));+ });+ });+}++function alive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error?.code === "EPERM";+ }+}++function signal(pid, name) {+ try {+ process.kill(pid, name);+ } catch {+ // Already gone.+ }+}++/**+ * @param {object} options+ * @param {(file: string, args: string[], options: object) => any} options.spawn node-pty's spawn+ * @param {(cwd: unknown) => Promise<string>} options.resolveCwd+ * @param {() => Array<{ id: string, label: string, path: string, args: string[] }>} options.shells+ * @param {string} [options.platform]+ * @param {Record<string, string | undefined>} [options.env]+ * @param {(command: string, args: string[]) => Promise<string>} [options.run]+ * @param {(pid: number) => boolean} [options.isAlive]+ * @param {(pid: number, name: string) => void} [options.sendSignal]+ * @param {number} [options.graceMs]+ * @param {(ms: number) => Promise<unknown>} [options.sleep]+ */+export function createTerminalSessions({+ spawn,+ resolveCwd,+ shells,+ platform = process.platform,+ env = process.env,+ run = defaultRun,+ isAlive = alive,+ sendSignal = signal,+ graceMs = DEFAULT_GRACE_MS,+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+}) {+ /** terminalId -> { process, ownerId, workspaceId, send, ended } */+ const sessions = new Map();+ /** Shells being ended (their grace periods still running): the app's quit waits for them. */+ const ending = new Set();+ let nextId = 1;++ /** Ends one shell and its process tree; resolves once they are gone (or given up on). */+ async function endTree(child) {+ const pid = child.pid;+ if (platform === "win32") {+ if (Number.isInteger(pid)) await run("taskkill", ["/PID", String(pid), "/T", "/F"]);+ try { child.kill(); } catch { /* already gone */ }+ return;+ }+ const tree = Number.isInteger(pid) ? descendantsOf(pid, await run("ps", ["-A", "-o", "pid=,ppid="])) : [];+ try { child.kill("SIGHUP"); } catch { /* already gone */ }+ const remaining = () => [pid, ...tree].filter((each) => Number.isInteger(each) && isAlive(each));+ for (const next of ["SIGTERM", "SIGKILL"]) {+ for (let waited = 0; waited < graceMs && remaining().length; waited += 50) await sleep(50);+ const left = remaining();+ if (!left.length) return;+ for (const each of left) sendSignal(each, next);+ }+ }++ function end(terminalId) {+ const session = sessions.get(terminalId);+ if (!session) return Promise.resolve();+ sessions.delete(terminalId);+ session.ended = true;+ const done = endTree(session.process).catch(() => undefined).finally(() => ending.delete(done));+ ending.add(done);+ return done;+ }++ function owned(ownerId, terminalId) {+ const session = sessions.get(String(terminalId ?? ""));+ return session && session.ownerId === ownerId ? session : null;+ }++ return {+ shells,++ /**+ * @param {{ ownerId: number, workspaceId?: string | null, cwd?: unknown, cols?: number, rows?: number, shellId?: string | null, send: (channel: string, payload: object) => void }} input+ */+ async create({ ownerId, workspaceId = null, cwd, cols, rows, shellId = null, send }) {+ const available = shells();+ const shell = available.find((each) => each.id === shellId) ?? available[0];+ const directory = await resolveCwd(cwd);+ const terminalId = `term_${nextId++}`;+ const child = spawn(shell.path, shell.args, {+ name: "xterm-256color",+ cols: clampSize(cols, MIN_COLS, 80),+ rows: clampSize(rows, MIN_ROWS, 24),+ cwd: directory,+ env: { ...env, TERM: "xterm-256color", COLORTERM: "truecolor", OMNIRUSH_TERMINAL: "1" },+ ...(platform === "win32" ? { useConpty: true } : {}),+ });+ const session = { process: child, ownerId, workspaceId: workspaceId ? String(workspaceId) : null, send, ended: false };+ sessions.set(terminalId, session);+ child.onData((data) => {+ if (!session.ended) send("omnirush:terminal:data", { terminalId, data });+ });+ child.onExit(({ exitCode, signal: exitSignal }) => {+ const wasOpen = sessions.get(terminalId) === session;+ if (wasOpen) sessions.delete(terminalId);+ // A shell the user exited (or that crashed) tells its tab; one we ended does not.+ if (wasOpen && !session.ended) send("omnirush:terminal:exit", { terminalId, exitCode, signal: exitSignal });+ session.ended = true;+ });+ return { terminalId, shellId: shell.id, shellLabel: shell.label, cwd: directory };+ },++ write(ownerId, terminalId, data) {+ const session = owned(ownerId, terminalId);+ if (session && typeof data === "string") session.process.write(data);+ },++ resize(ownerId, terminalId, cols, rows) {+ const session = owned(ownerId, terminalId);+ if (!session || !Number.isFinite(cols) || !Number.isFinite(rows)) return;+ try {+ session.process.resize(clampSize(cols, MIN_COLS, 80), clampSize(rows, MIN_ROWS, 24));+ } catch {+ // The shell exited between the check and the resize.+ }+ },++ kill(ownerId, terminalId) {+ return owned(ownerId, terminalId) ? end(String(terminalId)) : Promise.resolve();+ },++ /** Ends every shell of one workspace (the workspace is being removed). */+ killWorkspace(workspaceId, ownerId = null) {+ const id = String(workspaceId ?? "");+ const ids = [...sessions.entries()]+ .filter(([, session]) => session.workspaceId === id && (ownerId === null || session.ownerId === ownerId))+ .map(([terminalId]) => terminalId);+ return Promise.all(ids.map(end)).then(() => ids.length);+ },++ /** Ends every shell a window opened (it closed, crashed or reloaded). */+ killOwner(ownerId) {+ const ids = [...sessions.entries()].filter(([, session]) => session.ownerId === ownerId).map(([terminalId]) => terminalId);+ return Promise.all(ids.map(end)).then(() => ids.length);+ },++ /**+ * Ends every shell (the app is quitting), and waits for shells already+ * being ended (a window that just closed), so the app never exits+ * before a stubborn process got its SIGTERM/SIGKILL.+ */+ killAll() {+ for (const terminalId of [...sessions.keys()]) end(terminalId);+ return Promise.all([...ending]).then(() => undefined);+ },++ /** Live terminal ids of one window. */+ list(ownerId) {+ return [...sessions.entries()].filter(([, session]) => session.ownerId === ownerId).map(([terminalId]) => terminalId);+ },+ };+}diff --git a/apps/desktop/electron/terminal-sessions.test.mjs b/apps/desktop/electron/terminal-sessions.test.mjsnew file mode 100644index 00000000..b0e7b580--- /dev/null+++ b/apps/desktop/electron/terminal-sessions.test.mjs@@ -0,0 +1,236 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync, existsSync, realpathSync } from "node:fs";+import { createRequire } from "node:module";+import os from "node:os";+import path from "node:path";+import test from "node:test";++import { createTerminalSessions, descendantsOf, terminalShells } from "./terminal-sessions.mjs";++const require = createRequire(import.meta.url);+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++function alive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error?.code === "EPERM";+ }+}++async function waitFor(check, timeoutMs = 10_000) {+ const started = Date.now();+ while (Date.now() - started < timeoutMs) {+ if (await check()) return true;+ await sleep(50);+ }+ return false;+}++test("shell list: Windows offers PowerShell (7 first when installed) and Command Prompt", () => {+ const shells = terminalShells({+ platform: "win32",+ env: { PATH: "C:\\Tools;C:\\Program Files\\PowerShell\\7", SystemRoot: "C:\\Windows", COMSPEC: "C:\\Windows\\system32\\cmd.exe" },+ exists: (file) => file === "C:\\Program Files\\PowerShell\\7\\pwsh.exe" || file.endsWith("powershell.exe"),+ });+ assert.deepEqual(shells.map((shell) => shell.id), ["pwsh", "powershell", "cmd"]);+ assert.equal(shells[0].path, "C:\\Program Files\\PowerShell\\7\\pwsh.exe");+ assert.equal(shells[1].path, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");+ assert.equal(shells[2].path, "C:\\Windows\\system32\\cmd.exe");+ const plain = terminalShells({ platform: "win32", env: { PATH: "" }, exists: () => false });+ assert.deepEqual(plain.map((shell) => [shell.id, shell.path]), [["powershell", "powershell.exe"], ["cmd", "cmd.exe"]]);+});++test("shell list: macOS and Linux start the user's shell first; macOS shells are login shells", () => {+ const installed = new Set(["/opt/homebrew/bin/fish", "/bin/zsh", "/bin/bash", "/bin/sh"]);+ const mac = terminalShells({ platform: "darwin", env: { SHELL: "/opt/homebrew/bin/fish" }, exists: (file) => installed.has(file) });+ assert.deepEqual(mac.map((shell) => shell.path), ["/opt/homebrew/bin/fish", "/bin/zsh", "/bin/bash", "/bin/sh"]);+ assert.deepEqual(mac[0].args, ["-l"]);+ assert.deepEqual(mac.at(-1).args, []);+ const linux = terminalShells({ platform: "linux", env: {}, exists: (file) => file === "/bin/bash" || file === "/bin/sh" });+ assert.deepEqual(linux.map((shell) => [shell.id, shell.args]), [["bash", []], ["sh", []]]);+});++test("descendantsOf walks the whole process tree below a shell", () => {+ const listing = " 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n";+ assert.deepEqual(descendantsOf(10, listing).sort(), [11, 12, 13]);+ assert.deepEqual(descendantsOf(20, listing), []);+});++function fakePty() {+ const spawned = [];+ const spawn = (file, args, options) => {+ const listeners = { data: [], exit: [] };+ const child = {+ pid: 4242 + spawned.length,+ file, args, options,+ written: [], resized: [], killed: [],+ onData: (fn) => listeners.data.push(fn),+ onExit: (fn) => listeners.exit.push(fn),+ write: (data) => child.written.push(data),+ resize: (cols, rows) => child.resized.push([cols, rows]),+ kill: (signal) => child.killed.push(signal ?? "default"),+ emit: (data) => listeners.data.forEach((fn) => fn(data)),+ exit: (exitCode) => listeners.exit.forEach((fn) => fn({ exitCode, signal: 0 })),+ };+ spawned.push(child);+ return child;+ };+ return { spawn, spawned };+}++test("tabs are separate shells in their workspace folder, owned by their window", async () => {+ const { spawn, spawned } = fakePty();+ const sent = [];+ const sessions = createTerminalSessions({+ spawn,+ platform: "linux",+ env: { PATH: "/usr/bin" },+ resolveCwd: async (cwd) => String(cwd),+ shells: () => [{ id: "bash", label: "bash", path: "/bin/bash", args: [] }, { id: "sh", label: "sh", path: "/bin/sh", args: [] }],+ run: async () => "",+ isAlive: () => false,+ });+ const send = (channel, payload) => sent.push([channel, payload]);+ const a = await sessions.create({ ownerId: 1, workspaceId: "ws_a", cwd: "/work/a", cols: 100, rows: 30, send });+ const b = await sessions.create({ ownerId: 1, workspaceId: "ws_a", cwd: "/work/a", cols: 5, rows: 1, shellId: "sh", send });+ const c = await sessions.create({ ownerId: 2, workspaceId: "ws_b", cwd: "/work/b", send });+ assert.notEqual(a.terminalId, b.terminalId);+ assert.deepEqual(spawned.map((child) => [child.file, child.options.cwd, child.options.cols, child.options.rows]), [+ ["/bin/bash", "/work/a", 100, 30],+ ["/bin/sh", "/work/a", 20, 5],+ ["/bin/bash", "/work/b", 80, 24],+ ]);+ assert.equal(spawned[0].options.env.OMNIRUSH_TERMINAL, "1");+ assert.equal(b.shellLabel, "sh");++ spawned[0].emit("hello");+ assert.deepEqual(sent.at(-1), ["omnirush:terminal:data", { terminalId: a.terminalId, data: "hello" }]);+ // Another window cannot type into, resize or end a tab it does not own.+ sessions.write(2, a.terminalId, "rm -rf /\r");+ sessions.resize(2, a.terminalId, 200, 50);+ await sessions.kill(2, a.terminalId);+ assert.deepEqual(spawned[0].written, []);+ assert.deepEqual(spawned[0].resized, []);+ assert.deepEqual(spawned[0].killed, []);+ sessions.write(1, a.terminalId, "ls\r");+ assert.deepEqual(spawned[0].written, ["ls\r"]);++ // A shell the user exits tells its tab.+ spawned[1].exit(0);+ assert.deepEqual(sent.at(-1), ["omnirush:terminal:exit", { terminalId: b.terminalId, exitCode: 0, signal: 0 }]);+ assert.deepEqual(sessions.list(1), [a.terminalId]);++ // A closed tab ends its shell with SIGHUP and sends nothing more.+ await sessions.kill(1, a.terminalId);+ assert.deepEqual(spawned[0].killed, ["SIGHUP"]);+ const before = sent.length;+ spawned[0].emit("late");+ spawned[0].exit(129);+ assert.equal(sent.length, before);++ // A removed workspace ends only its own shells; a closed window ends its own.+ const d = await sessions.create({ ownerId: 1, workspaceId: "ws_b", cwd: "/work/b", send });+ assert.equal(await sessions.killWorkspace("ws_b"), 2);+ assert.deepEqual(spawned[2].killed, ["SIGHUP"]);+ assert.deepEqual(spawned[3].killed, ["SIGHUP"]);+ assert.deepEqual(sessions.list(1), []);+ assert.ok(d.terminalId);+ await sessions.create({ ownerId: 3, cwd: "/", send });+ await sessions.create({ ownerId: 4, cwd: "/", send });+ assert.equal(await sessions.killOwner(3), 1);+ assert.deepEqual(sessions.list(4).length, 1);+ await sessions.killAll();+ assert.deepEqual(sessions.list(4), []);+});++test("Windows: a closed tab ends the whole process tree with taskkill before closing the ConPTY", async () => {+ const { spawn, spawned } = fakePty();+ const runs = [];+ const sessions = createTerminalSessions({+ spawn,+ platform: "win32",+ env: {},+ resolveCwd: async (cwd) => String(cwd),+ shells: () => [{ id: "powershell", label: "Windows PowerShell", path: "powershell.exe", args: ["-NoLogo"] }],+ run: async (command, args) => {+ runs.push([command, ...args, `killed-before-close=${spawned[0].killed.length === 0}`]);+ return "";+ },+ });+ const { terminalId } = await sessions.create({ ownerId: 1, workspaceId: "ws", cwd: "C:\\work", send: () => undefined });+ assert.equal(spawned[0].options.useConpty, true);+ assert.deepEqual(spawned[0].args, ["-NoLogo"]);+ await sessions.kill(1, terminalId);+ assert.deepEqual(runs, [["taskkill", "/PID", String(spawned[0].pid), "/T", "/F", "killed-before-close=true"]]);+ assert.deepEqual(spawned[0].killed, ["default"]);+});++test("a shell that ignores SIGHUP, and what it started, are ended with SIGTERM then SIGKILL", async () => {+ const { spawn, spawned } = fakePty();+ const living = new Set([4242, 5001, 5002]);+ const signals = [];+ const sessions = createTerminalSessions({+ spawn,+ platform: "darwin",+ env: {},+ resolveCwd: async (cwd) => String(cwd),+ shells: () => [{ id: "zsh", label: "zsh", path: "/bin/zsh", args: ["-l"] }],+ run: async () => "4242 1\n5001 4242\n5002 5001\n6000 1\n4243 1\n5003 4243\n",+ isAlive: (pid) => living.has(pid),+ sendSignal: (pid, name) => {+ signals.push([pid, name]);+ if (name === "SIGKILL" || pid === 5002) living.delete(pid);+ },+ graceMs: 100,+ sleep: (ms) => sleep(Math.min(ms, 5)),+ });+ const { terminalId } = await sessions.create({ ownerId: 1, cwd: "/", send: () => undefined });+ await sessions.kill(1, terminalId);+ assert.deepEqual(spawned[0].killed, ["SIGHUP"]);+ assert.deepEqual(signals, [[4242, "SIGTERM"], [5001, "SIGTERM"], [5002, "SIGTERM"], [4242, "SIGKILL"], [5001, "SIGKILL"]]);+ assert.equal(living.size, 0);++ // A window that closed started ending its shells; the app's quit waits for that to finish.+ living.add(4243).add(5003);+ signals.length = 0;+ await sessions.create({ ownerId: 2, cwd: "/", send: () => undefined });+ const closing = sessions.killOwner(2);+ await sessions.killAll();+ assert.equal(living.size, 0, "killAll resolved before the closing window's shells were gone");+ await closing;+});++test("real shell (macOS/Linux): closing a tab leaves no process it started behind", { skip: process.platform === "win32" }, async () => {+ let pty;+ try {+ pty = require("node-pty");+ } catch {+ return;+ }+ const cwd = mkdtempSync(path.join(os.tmpdir(), "omnirush-terminal-"));+ try {+ const sessions = createTerminalSessions({+ spawn: (file, args, options) => pty.spawn(file, args, options),+ resolveCwd: async (dir) => String(dir),+ shells: () => [{ id: "sh", label: "sh", path: existsSync("/bin/bash") ? "/bin/bash" : "/bin/sh", args: [] }],+ graceMs: 800,+ });+ let output = "";+ const { terminalId } = await sessions.create({ ownerId: 1, workspaceId: "ws", cwd, send: (channel, payload) => { if (channel === "omnirush:terminal:data") output += payload.data; } });+ // A background job that ignores SIGHUP, and a foreground one.+ sessions.write(1, terminalId, "pwd; (trap '' HUP; exec sleep 3001) & echo BG=$!; sleep 3002 &\r");+ sessions.write(1, terminalId, "echo FG_START; exec 2>&1; sleep 3003\r");+ assert.ok(await waitFor(() => /BG=\d+/.test(output) && output.includes("FG_START")), output);+ assert.ok(output.includes(realpathSync(cwd)) || output.includes(cwd), "the shell starts in the workspace folder");+ /** @type {string} */+ const listing = await new Promise((resolve) => require("node:child_process").execFile("ps", ["-A", "-o", "pid=,args="], (_e, out) => resolve(String(out))));+ const sleeps = listing.split("\n").filter((line) => /sleep 300[123]/.test(line)).map((line) => Number(line.trim().split(/\s+/)[0]));+ assert.equal(sleeps.length, 3, listing);+ await sessions.kill(1, terminalId);+ assert.ok(await waitFor(() => sleeps.every((pid) => !alive(pid)), 5000), `still running: ${sleeps.filter(alive)}`);+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 21cc4b25..26028e0d 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},