Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add the iTerm2 view to the Shell page (#8114)
[._.]/ Adam Eivy36aabac41a8c
diff --git a/client/src/App.jsx b/client/src/App.jsxindex eeb12a1c53..29e8afdb66 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -417,6 +417,9 @@ export default function App() {<Route path="local-llm/playground" element={<LocalLlmPlayground />} /><Route path="uploads" element={<Uploads />} /><Route path="shell" element={<Shell />} />+ {/* The iTerm2 view (#8114): the static `iterm` segment outranks :sessionId. */}+ <Route path="shell/iterm" element={<Shell />} />+ <Route path="shell/iterm/:itermSessionId" element={<Shell />} /><Route path="shell/:sessionId" element={<Shell />} /><Route path="browser" element={<BrowserPage />} /><Route path="insights" element={<Navigate to="/insights/overview" replace />} />diff --git a/client/src/components/shell/ItermSessionTabs.jsx b/client/src/components/shell/ItermSessionTabs.jsxnew file mode 100644index 0000000000..c2bb08a341--- /dev/null+++ b/client/src/components/shell/ItermSessionTabs.jsx@@ -0,0 +1,60 @@+import { AppWindow } from 'lucide-react';+import { clickableProps } from '../../lib/a11yKeyboard.js';++// Separator-agnostic basename, as in ShellSessionTabs.+const folderName = (cwd) => cwd?.split(/[\\/]/).filter(Boolean).pop();++// Where a session sits in iTerm2: `Window 1 › Tab 2 › Pane 1/2` (the pane+// segment only when the tab is split).+export const itermLocation = (s) => [+ `Window ${s.windowIndex}`,+ `Tab ${s.tabIndex}`,+ ...(s.paneCount > 1 ? [`Pane ${s.paneIndex}/${s.paneCount}`] : []),+].join(' › ');++// Session strip for the Shell page's iTerm2 view (#8114), grouped by iTerm2+// window → tab with panes as their own entries. Deliberately NOT+// ShellSessionTabs: there is no kill or new-session control, because PortOS+// cannot close or create iTerm2 sessions. Each entry carries the iTerm2 badge+// so it never reads as a PortOS shell.+export default function ItermSessionTabs({ sessions, activeSessionId, onSelect }) {+ return (+ <div className="flex items-center gap-1.5 overflow-x-auto scrollbar-hide touch-pan-x" aria-label="iTerm2 sessions">+ {sessions.map((s, idx) => {+ const isActive = s.id === activeSessionId;+ const newWindow = idx === 0 || sessions[idx - 1].windowIndex !== s.windowIndex;+ const label = s.label || s.jobName || 'session';+ const folder = folderName(s.cwd);+ const where = itermLocation(s);+ return (+ <div key={s.id} className="flex items-center gap-1.5 shrink-0">+ {newWindow && (+ <span className="text-[10px] uppercase tracking-wide text-port-warning/80 font-semibold shrink-0 pl-1">+ W{s.windowIndex}+ </span>+ )}+ <div+ data-testid="iterm-session-tab"+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs font-mono transition-colors cursor-pointer min-h-[40px] ${+ isActive+ ? 'bg-port-warning/20 text-port-warning border border-port-warning/50'+ : 'bg-port-card hover:bg-port-border text-gray-400 hover:text-white border border-port-border'+ }`}+ onClick={() => !isActive && onSelect(s.id)}+ {...clickableProps(() => !isActive && onSelect(s.id))}+ aria-current={isActive ? 'true' : undefined}+ title={`iTerm2 — ${where} — ${label}${s.cwd ? ` — ${s.cwd}` : ''}`}+ >+ <AppWindow size={12} className="shrink-0 text-port-warning" aria-label="iTerm2" />+ <span className="text-[10px] opacity-70 shrink-0">+ T{s.tabIndex}{s.paneCount > 1 ? ` · P${s.paneIndex}/${s.paneCount}` : ''}+ </span>+ <span className="truncate max-w-[9rem] sm:max-w-[16rem]">{label}</span>+ {folder && <span className="hidden sm:inline text-[10px] opacity-60 truncate max-w-[8rem]">{folder}</span>}+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/shell/ItermShellView.jsx b/client/src/components/shell/ItermShellView.jsxnew file mode 100644index 0000000000..95b1e4947c--- /dev/null+++ b/client/src/components/shell/ItermShellView.jsx@@ -0,0 +1,164 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Link, useParams } from 'react-router';+import { AppWindow, Maximize2, Minimize2 } from 'lucide-react';+import * as api from '../../services/api';+import { readClipboard } from '../../lib/clipboard';+import { useInstanceFeatures } from '../../hooks/useInstanceFeatures.js';+import { useItermSession } from '../../hooks/useItermSession';+import TerminalHotKeys from './TerminalHotKeys';+import ShellSourceSwitch from './ShellSourceSwitch';+import ItermSessionTabs, { itermLocation } from './ItermSessionTabs';+import ItermStatusHint from './ItermStatusHint';+import { visibleQuickCommands } from './quickCommands';+import Kbd from '../ui/Kbd';++// The Shell page's iTerm2 view (#8114): this Mac's live iTerm2 sessions, shown+// and typed into from PortOS. Kept visibly and structurally apart from PortOS+// shells — its own URL, hook, toolbar and an amber iTerm2 frame — because+// iTerm2 owns these sessions' size and lifecycle: there is no New, Stop,+// Restart, cd picker or provider launcher here, and no resize is ever sent.+export default function ItermShellView() {+ const { itermSessionId } = useParams();+ const { features, isFeatureEnabled } = useInstanceFeatures();+ const enabled = isFeatureEnabled('iterm');+ const featureOff = features !== null && !enabled;+ const [isFullscreen, setIsFullscreen] = useState(false);+ const [showPasteInput, setShowPasteInput] = useState(false);+ const [fetchedStatus, setFetchedStatus] = useState(null);+ const pasteInputRef = useRef(null);++ const {+ terminalRef, sessions, listed, status, activeSession, connected,+ selectSession, emitInput, sendCtrlB, sendCtrlC, sendEsc, sendNavKey,+ } = useItermSession({ itermSessionId, enabled });++ // The static checks (not installed, API disabled, not running) come from the+ // status endpoint; the live socket status wins once it says anything more+ // specific than "disconnected".+ useEffect(() => {+ if (!enabled) return undefined;+ let active = true;+ api.getItermStatus({ silent: true })+ .then((res) => { if (active) setFetchedStatus(res?.state ?? null); })+ .catch(() => {});+ return () => { active = false; };+ }, [enabled]);+ const liveState = status?.state;+ const hintState = liveState && liveState !== 'disconnected' ? liveState : (fetchedStatus ?? liveState ?? 'disconnected');++ const handlePaste = useCallback(async () => {+ const text = await readClipboard();+ if (text == null) { setShowPasteInput(true); return; }+ if (text) emitInput(text);+ }, [emitInput]);++ const handlePasteInputEvent = useCallback((e) => {+ e.preventDefault();+ const text = e.clipboardData?.getData('text');+ if (text) emitInput(text);+ setShowPasteInput(false);+ }, [emitInput]);++ useEffect(() => {+ if (showPasteInput) pasteInputRef.current?.focus();+ }, [showPasteInput]);++ const hotKeyProps = {+ sendCtrlB, sendCtrlC, sendEsc, handlePaste, sendNavKey,+ showPasteInput, setShowPasteInput, pasteInputRef, handlePasteInputEvent,+ };++ if (featureOff) {+ return (+ <div className="h-full flex flex-col gap-3 p-2 md:p-6">+ <h1 className="text-xl font-semibold text-white">Shell</h1>+ <p className="text-sm text-gray-400">+ iTerm2 sessions are turned off: <Link to="/settings/features" className="text-port-accent underline">Settings > Features</Link>.{' '}+ <Link to="/shell" className="text-port-accent underline">Back to PortOS shells</Link>+ </p>+ </div>+ );+ }++ const geometry = activeSession ? `${activeSession.cols}×${activeSession.rows} · sized by iTerm` : null;++ return (+ <div className={isFullscreen+ ? 'fixed inset-0 z-[70] flex flex-col bg-port-bg p-2'+ : 'h-full flex flex-col gap-2 md:gap-3 p-2 md:p-6'}>+ {!isFullscreen && (+ <div className="flex items-center gap-2">+ <h1 className="text-xl font-semibold text-white min-w-0 truncate">Shell</h1>+ <ShellSourceSwitch source="iterm" />+ <span className="flex items-center gap-1 shrink-0 text-xs px-2 py-1 rounded bg-port-warning/15 text-port-warning">+ <AppWindow size={12} />+ <span className="hidden sm:inline">{activeSession ? itermLocation(activeSession) : 'iTerm2'}</span>+ </span>+ {geometry && (+ <span data-testid="iterm-geometry" className="hidden sm:inline text-xs text-gray-500 font-mono shrink-0">{geometry}</span>+ )}+ <button+ onClick={() => setIsFullscreen(true)}+ className="ml-auto flex items-center gap-1.5 px-2.5 py-2 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded-lg text-sm transition-colors border border-port-border min-h-[40px] shrink-0"+ title="Fullscreen terminal"+ aria-label="Fullscreen terminal"+ >+ <Maximize2 size={16} />+ <span className="hidden sm:inline">Fullscreen</span>+ </button>+ </div>+ )}++ {!isFullscreen && sessions.length > 0 && (+ <ItermSessionTabs sessions={sessions} activeSessionId={activeSession?.id ?? itermSessionId} onSelect={selectSession} />+ )}++ {!isFullscreen && connected && (+ <div className="flex items-center gap-2 overflow-x-auto scrollbar-hide touch-pan-x">+ <TerminalHotKeys {...hotKeyProps} />+ <div className="w-px h-6 bg-port-border shrink-0" />+ {visibleQuickCommands(isFeatureEnabled).map(({ label, command }) => (+ <button+ key={label}+ onClick={() => emitInput(`${command}\r`)}+ className="px-3 py-1.5 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded text-xs font-mono transition-colors border border-port-border min-h-[40px] shrink-0"+ title={command}+ >+ {label}+ </button>+ ))}+ </div>+ )}++ {!isFullscreen && listed && <ItermStatusHint state={hintState} sessionCount={sessions.length} />}++ {/* iTerm2 owns the grid: the terminal keeps iTerm2's cols/rows and this+ frame scrolls when it is narrower, instead of resizing iTerm2. */}+ <div className={`flex-1 min-h-0 bg-port-bg overflow-auto border-2 border-port-warning/60 ${isFullscreen ? '' : 'rounded-lg'}`}>+ <div ref={terminalRef} data-testid="iterm-terminal" className="inline-block" style={{ padding: '8px' }} />+ </div>++ {!isFullscreen && (+ <p className="shrink-0 px-1 text-xs text-gray-500">+ Typing goes to iTerm2. <Kbd size="sm">Shift+Tab</Kbd> moves focus out of the terminal+ </p>+ )}++ {isFullscreen && (+ <div className="flex items-center gap-1.5 mt-2 overflow-x-auto scrollbar-hide touch-pan-x pb-1">+ <button+ onClick={() => setIsFullscreen(false)}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded text-xs transition-colors border border-port-border min-h-[40px] shrink-0"+ title="Exit fullscreen"+ aria-label="Exit fullscreen"+ >+ <Minimize2 size={14} />+ <span className="hidden sm:inline">Exit</span>+ </button>+ <div className="w-px h-6 bg-port-border shrink-0" />+ {connected && <TerminalHotKeys {...hotKeyProps} popoverPlacement="above" />}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/shell/ItermShellView.test.jsx b/client/src/components/shell/ItermShellView.test.jsxnew file mode 100644index 0000000000..6316ffc333--- /dev/null+++ b/client/src/components/shell/ItermShellView.test.jsx@@ -0,0 +1,122 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, cleanup, within } from '@testing-library/react';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';++const state = vi.hoisted(() => ({ featuresLoaded: true, enabled: true, hook: null }));+vi.mock('../../hooks/useInstanceFeatures.js', () => ({+ useInstanceFeatures: () => ({+ features: state.featuresLoaded ? [] : null,+ isFeatureEnabled: (id) => (id === 'iterm' ? state.enabled : false),+ }),+}));+vi.mock('../../hooks/useItermSession', () => ({ useItermSession: () => state.hook }));+vi.mock('../../services/api', () => ({ getItermStatus: vi.fn(() => new Promise(() => {})) }));++import ItermShellView from './ItermShellView';+import ShellSourceSwitch from './ShellSourceSwitch';+import { itermHintText } from './ItermStatusHint';++// Invented fixtures only.+const session = (id, over = {}) => ({+ id, windowIndex: 1, tabIndex: 1, paneIndex: 1, paneCount: 1, label: id, cwd: '/tmp/example-app', cols: 245, rows: 59, ...over,+});+const SESSIONS = [+ session('iterm-A', { paneIndex: 1, paneCount: 2, label: 'vim' }),+ session('iterm-B', { paneIndex: 2, paneCount: 2, label: 'claude' }),+ session('iterm-C', { windowIndex: 2, label: 'htop' }),+];+const hookState = (over = {}) => ({+ terminalRef: { current: null },+ sessions: SESSIONS,+ listed: true,+ status: { state: 'connected' },+ activeSession: SESSIONS[0],+ connected: true,+ selectSession: vi.fn(),+ emitInput: vi.fn(),+ sendCtrlB: vi.fn(),+ sendCtrlC: vi.fn(),+ sendEsc: vi.fn(),+ sendNavKey: vi.fn(),+ ...over,+});++let location;+const LocationProbe = () => { location = useLocation(); return null; };+const renderAt = (path, element) => render(+ <MemoryRouter initialEntries={[path]}>+ <LocationProbe />+ <Routes>+ <Route path="/shell/iterm" element={element} />+ <Route path="/shell/iterm/:itermSessionId" element={element} />+ <Route path="*" element={element} />+ </Routes>+ </MemoryRouter>+);++describe('ShellSourceSwitch', () => {+ beforeEach(() => { state.enabled = true; });+ afterEach(cleanup);++ it('is absent while the iterm feature is off', () => {+ state.enabled = false;+ renderAt('/shell', <ShellSourceSwitch source="portos" />);+ expect(screen.queryByRole('tab', { name: /iTerm2/ })).toBeNull();+ });++ it('navigates between the PortOS and iTerm2 views', () => {+ renderAt('/shell', <ShellSourceSwitch source="portos" />);+ fireEvent.click(screen.getByRole('tab', { name: /iTerm2/ }));+ expect(location.pathname).toBe('/shell/iterm');+ fireEvent.click(screen.getByRole('tab', { name: /PortOS/ }));+ expect(location.pathname).toBe('/shell');+ });+});++describe('ItermShellView', () => {+ beforeEach(() => {+ state.featuresLoaded = true;+ state.enabled = true;+ state.hook = hookState();+ });+ afterEach(cleanup);++ it('offers input helpers but no PortOS lifecycle controls', () => {+ renderAt('/shell/iterm/iterm-A', <ItermShellView />);+ expect(screen.getByRole('button', { name: /Send Ctrl\+C/ })).toBeTruthy();+ for (const name of [/^New$/, /Start new session/, /Stop/, /Restart/, /cd to app/, /Kill session/]) {+ expect(screen.queryByRole('button', { name })).toBeNull();+ }+ expect(screen.getByTestId('iterm-geometry').textContent).toBe('245×59 · sized by iTerm');+ });++ it('groups sessions window › tab › pane and selects through the URL callback', () => {+ renderAt('/shell/iterm/iterm-A', <ItermShellView />);+ const tabs = screen.getAllByTestId('iterm-session-tab');+ expect(tabs).toHaveLength(3);+ expect(tabs[0].getAttribute('title')).toContain('Window 1 › Tab 1 › Pane 1/2');+ expect(tabs[2].getAttribute('title')).toContain('Window 2 › Tab 1');+ expect(screen.getByText('W2')).toBeTruthy();+ fireEvent.click(within(tabs[1]).getByText('claude'));+ expect(state.hook.selectSession).toHaveBeenCalledWith('iterm-B');+ });++ it('shows a turned-off notice with a way back when the feature is off', () => {+ state.enabled = false;+ renderAt('/shell/iterm', <ItermShellView />);+ expect(screen.getByText(/iTerm2 sessions are turned off/)).toBeTruthy();+ expect(screen.getByRole('link', { name: /Back to PortOS shells/ }).getAttribute('href')).toBe('/shell');+ });++ it('names the fix for each status', () => {+ expect(itermHintText({ state: 'api-disabled' })).toMatch(/Enable Python API/);+ expect(itermHintText({ state: 'not-running' })).toMatch(/isn’t running/);+ expect(itermHintText({ state: 'auth-failed' })).toMatch(/Automation/);+ expect(itermHintText({ state: 'connected', sessionCount: 0 })).toBe('No iTerm2 sessions open.');+ expect(itermHintText({ state: 'connected', sessionCount: 2 })).toBeNull();++ state.hook = hookState({ sessions: [], activeSession: null, connected: false, status: { state: 'not-running' } });+ renderAt('/shell/iterm', <ItermShellView />);+ expect(screen.getByRole('status').textContent).toMatch(/iTerm2 isn’t running/);+ });+});diff --git a/client/src/components/shell/ItermStatusHint.jsx b/client/src/components/shell/ItermStatusHint.jsxnew file mode 100644index 0000000000..876e7fd4fb--- /dev/null+++ b/client/src/components/shell/ItermStatusHint.jsx@@ -0,0 +1,26 @@+// One compact line naming the fix for an iTerm2 view that isn't showing+// sessions (#8114). `state` is the bridge status (see docs/ITERM.md).+export const ITERM_STATUS_HINTS = {+ 'unsupported-platform': 'iTerm2 sessions are only available on macOS.',+ 'not-installed': 'iTerm2 isn’t installed in /Applications or ~/Applications.',+ 'api-disabled': 'Enable iTerm2 Settings → General → Magic → Enable Python API.',+ 'not-running': 'iTerm2 isn’t running.',+ 'auth-failed': 'Allow PortOS to control iTerm2 in System Settings → Privacy & Security → Automation.',+ 'connect-failed': 'Couldn’t connect to iTerm2’s API — check that the Python API is enabled.',+ disconnected: 'Connecting to iTerm2…',+};++export const itermHintText = ({ state, sessionCount }) => {+ if (state === 'connected') return sessionCount === 0 ? 'No iTerm2 sessions open.' : null;+ return ITERM_STATUS_HINTS[state] ?? null;+};++export default function ItermStatusHint({ state, sessionCount }) {+ const text = itermHintText({ state, sessionCount });+ if (!text) return null;+ return (+ <p role="status" className="shrink-0 px-1 text-xs text-port-warning">+ {text}+ </p>+ );+}diff --git a/client/src/components/shell/ShellSourceSwitch.jsx b/client/src/components/shell/ShellSourceSwitch.jsxnew file mode 100644index 0000000000..3411b82ff2--- /dev/null+++ b/client/src/components/shell/ShellSourceSwitch.jsx@@ -0,0 +1,31 @@+import { useNavigate } from 'react-router';+import { AppWindow, SquareTerminal } from 'lucide-react';+import TabPills from '../ui/TabPills';+import { useInstanceFeatures } from '../../hooks/useInstanceFeatures.js';++const SOURCES = [+ { id: 'portos', label: 'PortOS', icon: SquareTerminal, path: '/shell' },+ { id: 'iterm', label: 'iTerm2', icon: AppWindow, path: '/shell/iterm' },+];++// The Shell page's `PortOS | iTerm2` source switch (#8114). The two sides are+// separate views with separate URLs, so this is navigation, not a filter, and+// the URL is its only state. It renders whenever the `iterm` feature is on —+// regardless of iTerm2's connection status — so the way back to PortOS shells+// never depends on the iTerm2 connection having worked.+export default function ShellSourceSwitch({ source }) {+ const navigate = useNavigate();+ const { isFeatureEnabled } = useInstanceFeatures();+ if (!isFeatureEnabled('iterm')) return null;+ return (+ <TabPills+ tabs={SOURCES}+ activeTab={source}+ onChange={(id) => navigate(SOURCES.find((s) => s.id === id).path)}+ variant="pills"+ size="xs"+ ariaLabel="Terminal source"+ className="shrink-0"+ />+ );+}diff --git a/client/src/components/shell/TerminalHotKeys.jsx b/client/src/components/shell/TerminalHotKeys.jsxindex 6837736697..e8212989a0 100644--- a/client/src/components/shell/TerminalHotKeys.jsx+++ b/client/src/components/shell/TerminalHotKeys.jsx@@ -82,9 +82,11 @@ export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, sendEsc, handlePonBlur={() => setShowPasteInput(false)}/>)}- <ShellImageDrop onSend={sendImage} placement={popoverPlacement} />- <div className="w-px h-6 bg-port-border shrink-0" />- {SCROLL_KEYS.map((key) => (+ {/* Photo and view-scroll are PortOS-PTY only: the iTerm2 view (#8114) has+ no image endpoint and no scrollback, so it omits both callbacks. */}+ {sendImage && <ShellImageDrop onSend={sendImage} placement={popoverPlacement} />}+ {scrollPage && <div className="w-px h-6 bg-port-border shrink-0" />}+ {scrollPage && SCROLL_KEYS.map((key) => (<buttonkey={key.label}onClick={() => scrollPage(key.direction)}diff --git a/client/src/components/shell/createShellTerminal.js b/client/src/components/shell/createShellTerminal.jsnew file mode 100644index 0000000000..69db573194--- /dev/null+++ b/client/src/components/shell/createShellTerminal.js@@ -0,0 +1,66 @@+import { Terminal } from '@xterm/xterm';+import { WebLinksAddon } from '@xterm/addon-web-links';+import '@xterm/xterm/css/xterm.css';+import { buildTerminalTheme, parseCssColorToHex } from '../../lib/terminalTheme';+import { isFocusEscapeKey } from '../../lib/a11yKeyboard';++// The xterm construction both Shell views share — the PortOS PTY view+// (hooks/useShellSession.js) and the iTerm2 view (hooks/useItermSession.js) —+// so the font stack, theme, links and keyboard-escape rule cannot drift apart.++// Read the active theme's colors off the document and assemble the xterm palette.+// The day/night mode comes from the `data-port-theme-mode` attribute applyTheme()+// stamps on <html>, so this stays correct without threading React state in.+// Background/foreground prefer the dedicated --port-terminal-* tokens (hand-tuned+// per theme) and fall back to the page bg/text.+export const readTerminalTheme = () => {+ const root = document.documentElement;+ const mode = root.dataset.portThemeMode === 'day' ? 'day' : 'night';+ const css = (varName) => getComputedStyle(root).getPropertyValue(varName).trim();+ return buildTerminalTheme({+ bg: parseCssColorToHex(css('--port-terminal-bg') || css('--port-bg'), '#070707'),+ fg: parseCssColorToHex(css('--port-terminal-text') || css('--port-text'), '#e5e5e5'),+ accent: parseCssColorToHex(css('--port-accent')),+ card: parseCssColorToHex(css('--port-card')),+ error: parseCssColorToHex(css('--port-error')),+ success: parseCssColorToHex(css('--port-success')),+ warning: parseCssColorToHex(css('--port-warning')),+ }, mode);+};++/** Create, open and return an xterm Terminal mounted in `container`. */+export const createShellTerminal = (container, options = {}) => {+ const term = new Terminal({+ cursorBlink: true,+ cursorStyle: 'block',+ fontSize: 14,+ fontFamily: '"Roboto Mono for Powerline", "MesloLGS NF", "MesloLGS Nerd Font", "Hack Nerd Font", "FiraCode Nerd Font", "JetBrainsMono Nerd Font", Menlo, Monaco, "Courier New", monospace',+ theme: readTerminalTheme(),+ scrollback: 5000,+ allowProposedApi: true,+ // Screen-reader mode is what makes xterm build its .xterm-accessibility+ // live region — without it every rendered row stays aria-hidden and a+ // screen-reader user focusing the terminal hears an empty textarea. It+ // also relaxes _keyDown's blanket preventDefault on resolved keys, which+ // the dictation bridge (lib/terminalDictation.js) is already written to+ // defer to.+ screenReaderMode: true,+ ...options,+ });++ term.loadAddon(new WebLinksAddon());+ term.open(container);++ // WCAG 2.1.2 (no keyboard trap): xterm's helper textarea is in the tab+ // order but its _keyDown preventDefaults Tab, Shift+Tab and Escape alike,+ // so a keyboard user who tabs in cannot leave without a mouse. The+ // documented escape is Shift+Tab — the conventional "leave this widget"+ // backtab: returning false makes _keyDown bail before it cancels the+ // event, so the browser performs the focus move to the previous tabbable+ // element and nothing reaches the PTY. Plain Tab must stay claimed — it is+ // shell completion. The gesture itself is the shared isFocusEscapeKey+ // predicate so the stand-down rule lives in one place.+ term.attachCustomKeyEventHandler((event) => !isFocusEscapeKey(event));++ return term;+};diff --git a/client/src/components/shell/quickCommands.js b/client/src/components/shell/quickCommands.jsnew file mode 100644index 0000000000..988575ec91--- /dev/null+++ b/client/src/components/shell/quickCommands.js@@ -0,0 +1,21 @@+// Typed-into-the-current-session shortcuts only. The AI CLIs that used to sit+// here as hardcoded buttons (claude / codex / agy / grok) now come from the+// enabled TUI providers via ShellProviderLauncher — a dynamic list that scales+// past a row of buttons and, unlike a typed command line, carries each+// provider's own backend env.+//+// `openclaw` is the one holdout, because PortOS ships no provider record for it.+// A new AI CLI belongs in `providers.sample.json` as a TUI provider, where the+// launcher picks it up for free — do not grow this list back.+export const QUICK_COMMANDS = [+ { label: 'openclaw', command: 'openclaw tui' },+ // Claude Code slash-command shortcuts — typed + submitted into an interactive+ // `claude` session. The flags are double-dash (`--`); keep them verbatim.+ { label: '/do:next', command: '/do:next --issues --self --review-with=claude,codex --merge' },+ { label: '/remote-control', command: '/remote-control' },+];+++// The quick commands this install shows: `openclaw` only while its feature is on.+export const visibleQuickCommands = (isFeatureEnabled) => QUICK_COMMANDS+ .filter(({ label }) => label !== 'openclaw' || isFeatureEnabled('openclaw'));diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 3c000320fd..90b5b2043f 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -88,6 +88,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. || `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. || `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |+| `useItermSession` | Socket.IO `iterm:*` state for the Shell page's iTerm2 view (#8114): list subscription, URL-selected attach with a strict pending-target guard, byte-exact input, and an xterm sized to iTerm2's own grid (never fit, never resized back). Never touches `shell:*`. || `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. || `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. || `useCharacterAugmentation` | The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns `preview`/`accepted`/`proposing`/`applying` and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an `onApplied`. | A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex f468818411..51e1d2c184 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -165,6 +165,7 @@ export * from './useCatalogTypes.jsx';// === Sockets & lifecycle ===export * from './useCosTaskUpdates.js';export * from './usePrevious.js';+export * from './useItermSession.js';export * from './useShellSession.js';export * from './useSocket.js';export * from './useSocketSubscription.js';diff --git a/client/src/hooks/useItermSession.js b/client/src/hooks/useItermSession.jsnew file mode 100644index 0000000000..77237eef7e--- /dev/null+++ b/client/src/hooks/useItermSession.js@@ -0,0 +1,199 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useNavigate } from 'react-router';+import { useSocket } from './useSocket';+import { useThemeContext } from '../components/ThemeContext';+import { createShellTerminal, readTerminalTheme } from '../components/shell/createShellTerminal';++export const ITERM_SHELL_PATH = '/shell/iterm';++/**+ * useItermSession — socket + terminal state for the Shell page's iTerm2 view+ * (#8114). Sibling of useShellSession, but it speaks ONLY the `iterm:*` events,+ * so an iTerm2 session never enters the PortOS shell tab strip or registry.+ *+ * Differences from a PortOS PTY that shape this hook:+ * - iTerm2 owns the size. The terminal is sized to the server-reported grid+ * with `term.resize(cols, rows)` (never fit to the container, never a+ * resize event back), and the container scrolls when narrower.+ * - Many viewers may watch one session, so there is no claim/detached dance:+ * attaching only adds this socket as a viewer.+ * - PortOS cannot create, stop or restart iTerm2 sessions.+ *+ * The selected session lives in the URL (`/shell/iterm/:itermSessionId`).+ * With no id, the first listed session is selected with a replace navigation.+ * `pendingRef = { target, generation }` gates `iterm:attached` by strict+ * equality so a response for a session the user already left is dropped.+ *+ * @param {object} params+ * @param {string|undefined} params.itermSessionId - selection from the URL+ * @param {boolean} params.enabled - false while the feature is off: no subscription+ */+export function useItermSession({ itermSessionId, enabled = true } = {}) {+ const socket = useSocket();+ const navigate = useNavigate();+ const { themeId, theme: activeTheme } = useThemeContext();+ const themeMode = activeTheme?.mode ?? 'night';+ const terminalRef = useRef(null);+ const termRef = useRef(null);+ const attachedIdRef = useRef(null);+ const pendingRef = useRef({ target: null, generation: 0 });+ const [sessions, setSessions] = useState(null); // null = not listed yet+ const [status, setStatus] = useState(null);+ const [attachedId, setAttachedId] = useState(null);++ const setPending = useCallback((target) => {+ pendingRef.current = { target, generation: pendingRef.current.generation + 1 };+ }, []);++ // Terminal lifetime = component lifetime.+ useEffect(() => {+ if (!enabled || !terminalRef.current || termRef.current) return undefined;+ termRef.current = createShellTerminal(terminalRef.current, { scrollback: 0, cursorBlink: false });+ return () => {+ termRef.current?.dispose();+ termRef.current = null;+ };+ }, [enabled]);++ useEffect(() => {+ if (termRef.current) termRef.current.options.theme = readTerminalTheme();+ }, [themeId, themeMode]);++ const sizeTo = useCallback((cols, rows) => {+ const term = termRef.current;+ if (!term || !(cols > 0) || !(rows > 0)) return;+ if (term.cols !== cols || term.rows !== rows) term.resize(cols, rows);+ }, []);++ const emitInput = useCallback((data, { focus = true } = {}) => {+ const id = attachedIdRef.current;+ if (!socket || !id || pendingRef.current.target) return false;+ socket.emit('iterm:input', { id, data });+ if (focus) termRef.current?.focus();+ return true;+ }, [socket]);++ // Keystrokes typed into the terminal go to the viewed iTerm2 session verbatim.+ useEffect(() => {+ const term = termRef.current;+ if (!term) return undefined;+ const disposable = term.onData((data) => emitInput(data, { focus: false }));+ return () => disposable.dispose();+ }, [emitInput, enabled]);++ // List subscription + event wiring.+ useEffect(() => {+ if (!socket || !enabled) return undefined;++ const handleConnect = () => socket.emit('iterm:list');+ const handleSessions = ({ sessions: list, status: nextStatus } = {}) => {+ setSessions(Array.isArray(list) ? list : []);+ setStatus(nextStatus ?? null);+ const active = list?.find?.((s) => s.id === attachedIdRef.current);+ if (active) sizeTo(active.cols, active.rows);+ };+ const handleAttached = ({ id, cols, rows, bufferedOutput }) => {+ if (pendingRef.current.target !== id) return;+ setPending(null);+ attachedIdRef.current = id;+ setAttachedId(id);+ const term = termRef.current;+ if (!term) return;+ term.reset();+ sizeTo(cols, rows);+ if (bufferedOutput) term.write(bufferedOutput);+ };+ const handleOutput = ({ id, data }) => {+ if (id === attachedIdRef.current && !pendingRef.current.target) termRef.current?.write(data);+ };+ const handleExit = ({ id }) => {+ if (id !== attachedIdRef.current) return;+ attachedIdRef.current = null;+ setAttachedId(null);+ termRef.current?.writeln('\r\n\x1b[33m[iTerm2 session closed]\x1b[0m');+ navigate(ITERM_SHELL_PATH, { replace: true });+ };+ const handleError = ({ id, error }) => {+ if (id !== pendingRef.current.target && id !== attachedIdRef.current) return;+ if (id === pendingRef.current.target) setPending(null);+ termRef.current?.writeln(`\r\n\x1b[31m[Error: ${error}]\x1b[0m`);+ };++ socket.on('connect', handleConnect);+ socket.on('iterm:sessions', handleSessions);+ socket.on('iterm:attached', handleAttached);+ socket.on('iterm:output', handleOutput);+ socket.on('iterm:exit', handleExit);+ socket.on('iterm:error', handleError);+ if (socket.connected) handleConnect();++ return () => {+ socket.off('connect', handleConnect);+ socket.off('iterm:sessions', handleSessions);+ socket.off('iterm:attached', handleAttached);+ socket.off('iterm:output', handleOutput);+ socket.off('iterm:exit', handleExit);+ socket.off('iterm:error', handleError);+ if (socket.connected) {+ if (attachedIdRef.current) socket.emit('iterm:detach', { id: attachedIdRef.current });+ socket.emit('iterm:unlist');+ }+ attachedIdRef.current = null;+ };+ }, [socket, enabled, navigate, setPending, sizeTo]);++ const sessionIds = sessions?.map((s) => s.id).join('\n') ?? null;++ // URL → attachment. No id: select the first session. Unknown id once the+ // list is in: fall back to the view root rather than a dead deep link.+ useEffect(() => {+ if (!socket || !enabled || sessionIds === null) return;+ const ids = sessionIds ? sessionIds.split('\n') : [];+ if (!itermSessionId) {+ if (ids.length > 0) navigate(`${ITERM_SHELL_PATH}/${ids[0]}`, { replace: true });+ return;+ }+ if (!ids.includes(itermSessionId)) {+ navigate(ITERM_SHELL_PATH, { replace: true });+ return;+ }+ if (attachedIdRef.current === itermSessionId || pendingRef.current.target === itermSessionId) return;+ if (attachedIdRef.current) socket.emit('iterm:detach', { id: attachedIdRef.current });+ attachedIdRef.current = null;+ setAttachedId(null);+ setPending(itermSessionId);+ const term = termRef.current;+ if (term) {+ term.reset();+ term.writeln('\x1b[36mAttaching to iTerm2 session...\x1b[0m');+ }+ socket.emit('iterm:attach', { id: itermSessionId });+ }, [socket, enabled, itermSessionId, sessionIds, navigate, setPending]);++ const selectSession = useCallback((id) => {+ if (id !== itermSessionId) navigate(`${ITERM_SHELL_PATH}/${id}`);+ }, [itermSessionId, navigate]);++ const sendNavKey = useCallback((key) => {+ // The frames carry no DECCKM state, so arrows always go out in CSI form,+ // which shells, vim and Claude Code all accept.+ emitInput(key.seq ?? `\x1b[${key.code}`, { focus: false });+ }, [emitInput]);++ const activeSession = sessions?.find((s) => s.id === attachedId) ?? null;++ return {+ terminalRef,+ sessions: sessions ?? [],+ listed: sessions !== null,+ status,+ activeSession,+ connected: Boolean(attachedId),+ selectSession,+ emitInput,+ sendCtrlB: () => emitInput('\x02'),+ sendCtrlC: () => emitInput('\x03'),+ sendEsc: () => emitInput('\x1b'),+ sendNavKey,+ };+}diff --git a/client/src/hooks/useItermSession.test.jsx b/client/src/hooks/useItermSession.test.jsxnew file mode 100644index 0000000000..a4d071dde6--- /dev/null+++ b/client/src/hooks/useItermSession.test.jsx@@ -0,0 +1,101 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act, cleanup } from '@testing-library/react';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';++const { handlers, emitted, socketMock } = vi.hoisted(() => {+ const handlers = new Map();+ const emitted = [];+ const socketMock = {+ connected: true,+ on: (event, fn) => { handlers.set(event, fn); },+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },+ emit: (event, ...args) => { emitted.push([event, ...args]); },+ };+ return { handlers, emitted, socketMock };+});+vi.mock('../services/socket', () => ({ default: socketMock, getSocket: () => socketMock }));+vi.mock('../components/ThemeContext', () => ({+ useThemeContext: () => ({ themeId: 'test', theme: { mode: 'night' } }),+}));++import { useItermSession } from './useItermSession.js';++// Invented fixtures only.+const session = (id, over = {}) => ({+ id, windowIndex: 1, tabIndex: 1, paneIndex: 1, paneCount: 1, label: id, cols: 100, rows: 30, ...over,+});+const LIST = { status: { state: 'connected' }, sessions: [session('iterm-AAAA'), session('iterm-BBBB', { tabIndex: 2 })] };++const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });+const emitsOf = (event) => emitted.filter(([e]) => e === event);++let location;+const renderAt = (path) => renderHook(() => {+ location = useLocation();+ return useItermSession({ itermSessionId: location.pathname.split('/')[3], enabled: true });+}, {+ wrapper: ({ children }) => (+ <MemoryRouter initialEntries={[path]}>+ <Routes><Route path="*" element={children} /></Routes>+ </MemoryRouter>+ ),+});++describe('useItermSession', () => {+ beforeEach(() => { handlers.clear(); emitted.length = 0; socketMock.connected = true; });+ afterEach(cleanup);++ it('lists iTerm2 sessions and never speaks the PortOS shell protocol', () => {+ const { unmount } = renderAt('/shell/iterm');+ expect(emitted).toContainEqual(['iterm:list']);+ fire('iterm:sessions', LIST);+ unmount();+ expect(emitted.some(([event]) => event.startsWith('shell:'))).toBe(false);+ expect(emitted).toContainEqual(['iterm:unlist']);+ });++ it('auto-selects the first session when the URL names none', () => {+ renderAt('/shell/iterm');+ fire('iterm:sessions', LIST);+ expect(location.pathname).toBe('/shell/iterm/iterm-AAAA');+ expect(emitsOf('iterm:attach')).toEqual([['iterm:attach', { id: 'iterm-AAAA' }]]);+ });++ it('deep-links to the session in the URL, drops a stale attach reply, and types into it', () => {+ const { result } = renderAt('/shell/iterm/iterm-BBBB');+ fire('iterm:sessions', LIST);+ expect(emitsOf('iterm:attach')).toEqual([['iterm:attach', { id: 'iterm-BBBB' }]]);++ fire('iterm:attached', { id: 'iterm-AAAA', cols: 100, rows: 30, bufferedOutput: '' });+ expect(result.current.connected).toBe(false);++ fire('iterm:attached', { id: 'iterm-BBBB', cols: 100, rows: 30, bufferedOutput: 'x' });+ expect(result.current.connected).toBe(true);+ expect(result.current.activeSession.id).toBe('iterm-BBBB');++ act(() => result.current.sendCtrlC());+ act(() => result.current.sendNavKey({ code: 'A' }));+ expect(emitsOf('iterm:input')).toEqual([+ ['iterm:input', { id: 'iterm-BBBB', data: '\x03' }],+ ['iterm:input', { id: 'iterm-BBBB', data: '\x1b[A' }],+ ]);+ // iTerm2 owns the size: nothing here ever asks for a resize.+ expect(emitted.some(([event]) => event.includes('resize'))).toBe(false);+ });++ it('falls back to the view root when the deep-linked session is gone', () => {+ renderAt('/shell/iterm/iterm-GONE');+ fire('iterm:sessions', LIST);+ expect(location.pathname).toBe('/shell/iterm/iterm-AAAA');+ });++ it('switching sessions detaches the previous one', () => {+ const { result } = renderAt('/shell/iterm/iterm-AAAA');+ fire('iterm:sessions', LIST);+ fire('iterm:attached', { id: 'iterm-AAAA', cols: 100, rows: 30, bufferedOutput: '' });+ act(() => result.current.selectSession('iterm-BBBB'));+ expect(location.pathname).toBe('/shell/iterm/iterm-BBBB');+ expect(emitsOf('iterm:detach')).toEqual([['iterm:detach', { id: 'iterm-AAAA' }]]);+ expect(emitsOf('iterm:attach').at(-1)).toEqual(['iterm:attach', { id: 'iterm-BBBB' }]);+ });+});diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.jsindex ce4d5b8649..4a103a94b3 100644--- a/client/src/hooks/useShellSession.js+++ b/client/src/hooks/useShellSession.js@@ -1,13 +1,9 @@import { useEffect, useRef, useState, useCallback } from 'react';import useMounted from './useMounted';import { useSearchParams, useParams, useNavigate } from 'react-router';-import { Terminal } from '@xterm/xterm';-import { WebLinksAddon } from '@xterm/addon-web-links';-import '@xterm/xterm/css/xterm.css';import { useSocket } from './useSocket';import { useThemeContext } from '../components/ThemeContext';-import { buildTerminalTheme, parseCssColorToHex } from '../lib/terminalTheme';-import { isFocusEscapeKey } from '../lib/a11yKeyboard';+import { createShellTerminal, readTerminalTheme } from '../components/shell/createShellTerminal';import { attachDictationBridge } from '../lib/terminalDictation';import { fitTerminal } from '../lib/terminalFit';import {@@ -27,26 +23,6 @@ export const MAX_SESSIONS = 20;// /shell and content to stay there when nothing is free to adopt.const STAY_PUT = () => {};-// Read the active theme's colors off the document and assemble the xterm palette.-// The day/night mode comes from the `data-port-theme-mode` attribute applyTheme()-// stamps on <html>, so this stays correct without threading React state in.-// Background/foreground prefer the dedicated --port-terminal-* tokens (hand-tuned-// per theme) and fall back to the page bg/text.-const readTerminalTheme = () => {- const root = document.documentElement;- const mode = root.dataset.portThemeMode === 'day' ? 'day' : 'night';- const css = (varName) => getComputedStyle(root).getPropertyValue(varName).trim();- return buildTerminalTheme({- bg: parseCssColorToHex(css('--port-terminal-bg') || css('--port-bg'), '#070707'),- fg: parseCssColorToHex(css('--port-terminal-text') || css('--port-text'), '#e5e5e5'),- accent: parseCssColorToHex(css('--port-accent')),- card: parseCssColorToHex(css('--port-card')),- error: parseCssColorToHex(css('--port-error')),- success: parseCssColorToHex(css('--port-success')),- warning: parseCssColorToHex(css('--port-warning')),- }, mode);-};-/*** useShellSession — all socket/session/terminal state and lifecycle for the Shell* page, extracted so the route component (`pages/Shell.jsx`) stays thin and purely@@ -258,39 +234,9 @@ export function useShellSession({ isFullscreen } = {}) {useEffect(() => {if (!terminalRef.current || termInstanceRef.current) return;- const term = new Terminal({- cursorBlink: true,- cursorStyle: 'block',- fontSize: 14,- fontFamily: '"Roboto Mono for Powerline", "MesloLGS NF", "MesloLGS Nerd Font", "Hack Nerd Font", "FiraCode Nerd Font", "JetBrainsMono Nerd Font", Menlo, Monaco, "Courier New", monospace',- theme: readTerminalTheme(),- scrollback: 5000,- allowProposedApi: true,- // Screen-reader mode is what makes xterm build its .xterm-accessibility- // live region — without it every rendered row stays aria-hidden and a- // screen-reader user focusing the terminal hears an empty textarea. It- // also relaxes _keyDown's blanket preventDefault on resolved keys, which- // the dictation bridge (lib/terminalDictation.js) is already written to- // defer to.- screenReaderMode: true- });-- const webLinksAddon = new WebLinksAddon();-- term.loadAddon(webLinksAddon);-- term.open(terminalRef.current);-- // WCAG 2.1.2 (no keyboard trap): xterm's helper textarea is in the tab- // order but its _keyDown preventDefaults Tab, Shift+Tab and Escape alike,- // so a keyboard user who tabs in cannot leave without a mouse. The- // documented escape is Shift+Tab — the conventional "leave this widget"- // backtab: returning false makes _keyDown bail before it cancels the- // event, so the browser performs the focus move to the previous tabbable- // element and nothing reaches the PTY. Plain Tab must stay claimed — it is- // shell completion. The gesture itself is the shared isFocusEscapeKey- // predicate so the stand-down rule lives in one place.- term.attachCustomKeyEventHandler((event) => !isFocusEscapeKey(event));+ // Construction, theme, links and the Shift+Tab focus escape are shared with+ // the iTerm2 view (components/shell/createShellTerminal.js).+ const term = createShellTerminal(terminalRef.current);// xterm binds no touch handlers of its own, so without this a swipe over the// terminal does nothing. Alternate-screen TUIs need the matching wheel capture sodiff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex 939e450798..e28808fc2d 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -11,25 +11,23 @@ import ShellProviderLauncher from '../components/shell/ShellProviderLauncher';import InfoTooltip from '../components/ui/InfoTooltip';import Kbd from '../components/ui/Kbd';import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';+import { useLocation } from 'react-router';+import ShellSourceSwitch from '../components/shell/ShellSourceSwitch';+import ItermShellView from '../components/shell/ItermShellView';+import { visibleQuickCommands } from '../components/shell/quickCommands';-// Typed-into-the-current-session shortcuts only. The AI CLIs that used to sit-// here as hardcoded buttons (claude / codex / agy / grok) now come from the-// enabled TUI providers via ShellProviderLauncher — a dynamic list that scales-// past a row of buttons and, unlike a typed command line, carries each-// provider's own backend env.-//-// `openclaw` is the one holdout, because PortOS ships no provider record for it.-// A new AI CLI belongs in `providers.sample.json` as a TUI provider, where the-// launcher picks it up for free — do not grow this list back.-const QUICK_COMMANDS = [- { label: 'openclaw', command: 'openclaw tui' },- // Claude Code slash-command shortcuts — typed + submitted into an interactive- // `claude` session. The flags are double-dash (`--`); keep them verbatim.- { label: '/do:next', command: '/do:next --issues --self --review-with=claude,codex --merge' },- { label: '/remote-control', command: '/remote-control' },-];+// `/shell` + `/shell/:sessionId` are PortOS PTY shells; `/shell/iterm` ++// `/shell/iterm/:itermSessionId` are the iTerm2 view (#8114). Two separate+// views, each with its own hook, so the PortOS one never lists, auto-starts or+// navigates while the iTerm2 view is open, and vice versa.+const isItermShellPath = (pathname) => pathname === '/shell/iterm' || pathname.startsWith('/shell/iterm/');export default function Shell() {+ const { pathname } = useLocation();+ return isItermShellPath(pathname) ? <ItermShellView /> : <PortosShellView />;+}++function PortosShellView() {const { isFeatureEnabled } = useInstanceFeatures();// Fullscreen promotes the terminal to a fixed overlay above the sidebar, hiding// the stacked toolbars so the TUI gets the whole viewport — the key mobile win@@ -152,6 +150,7 @@ export default function Shell() {an overflow — without it a narrow phone would push the row wider thanthe page and give the whole document a horizontal scrollbar. */}<h1 className="text-xl font-semibold text-white min-w-0 truncate">Shell</h1>+ <ShellSourceSwitch source="portos" /><divclassName={`flex items-center gap-2 shrink-0 text-sm px-2 py-1 rounded ${connected ? 'text-port-success sm:bg-port-success/20' : 'text-gray-400 sm:bg-gray-500/20'@@ -252,7 +251,7 @@ export default function Shell() {onOpen={loadProviders}onLaunch={launchProvider}/>- {QUICK_COMMANDS.filter(({ label }) => label !== 'openclaw' || isFeatureEnabled('openclaw')).map(({ label, command }) => (+ {visibleQuickCommands(isFeatureEnabled).map(({ label, command }) => (<buttonkey={label}onClick={() => sendCommand(command)}diff --git a/client/src/pages/Shell.test.jsx b/client/src/pages/Shell.test.jsxnew file mode 100644index 0000000000..a544a24623--- /dev/null+++ b/client/src/pages/Shell.test.jsx@@ -0,0 +1,59 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { render, cleanup, act } from '@testing-library/react';+import { MemoryRouter, Route, Routes } from 'react-router';++const mocks = vi.hoisted(() => ({ shell: vi.fn(), iterm: vi.fn() }));+vi.mock('../hooks/useShellSession', () => ({+ MAX_SESSIONS: 20,+ useShellSession: (...args) => {+ mocks.shell(...args);+ return { terminalRef: { current: null }, connected: false, sessions: [], interactiveCount: 0, liveRunCount: 0 };+ },+}));+vi.mock('../hooks/useItermSession', () => ({+ useItermSession: (...args) => {+ mocks.iterm(...args);+ return { terminalRef: { current: null }, sessions: [], listed: false, status: null, activeSession: null, connected: false };+ },+}));+vi.mock('../hooks/useInstanceFeatures.js', () => ({+ useInstanceFeatures: () => ({ features: [], isFeatureEnabled: () => true }),+}));+vi.mock('../services/api', () => ({+ getApps: vi.fn(async () => []),+ getItermStatus: vi.fn(() => new Promise(() => {})),+}));++import Shell from './Shell';++const renderAt = (path) => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/shell" element={<Shell />} />+ <Route path="/shell/iterm" element={<Shell />} />+ <Route path="/shell/iterm/:itermSessionId" element={<Shell />} />+ <Route path="/shell/:sessionId" element={<Shell />} />+ </Routes>+ </MemoryRouter>+);++// The two sources are separate views: the PortOS view (and its tab strip)+// never subscribes to iTerm2 sessions, and the iTerm2 view never lists,+// auto-starts or navigates PortOS shells.+describe('Shell page source routing (#8114)', () => {+ afterEach(() => { cleanup(); mocks.shell.mockClear(); mocks.iterm.mockClear(); });++ it('renders only the PortOS view at /shell and /shell/:sessionId', async () => {+ renderAt('/shell');+ renderAt('/shell/abc123');+ await act(async () => {}); // settle the app-folder fetch+ expect(mocks.shell).toHaveBeenCalled();+ expect(mocks.iterm).not.toHaveBeenCalled();+ });++ it('renders only the iTerm2 view at /shell/iterm/:itermSessionId', () => {+ renderAt('/shell/iterm/iterm-EXAMPLE');+ expect(mocks.iterm).toHaveBeenCalledWith(expect.objectContaining({ itermSessionId: 'iterm-EXAMPLE' }));+ expect(mocks.shell).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiShell.js b/client/src/services/apiShell.jsindex fddf678500..089675a0c5 100644--- a/client/src/services/apiShell.js+++ b/client/src/services/apiShell.js@@ -21,3 +21,10 @@ export const sendShellImage = (sessionId, { data, filename, message }, options =body: JSON.stringify({ data, filename, message }),...options,});++/**+ * Capability state of the Shell page's iTerm2 view (#8114): `{ state, detail }`,+ * never session contents. States and their fixes are in docs/ITERM.md.+ * @param {{ silent?: boolean }} [options]+ */+export const getItermStatus = (options = {}) => request('/iterm/status', options);diff --git a/docs/ITERM.md b/docs/ITERM.mdindex b6d951df12..c061757a76 100644--- a/docs/ITERM.md+++ b/docs/ITERM.md@@ -10,6 +10,10 @@ On a Mac running iTerm2, PortOS can list the terminals you already have open inThe first time PortOS connects, macOS may ask whether PortOS (the process running `osascript`) may control iTerm2. Allow it under **System Settings → Privacy & Security → Automation**.+## Using it++With the feature on, the Shell page header shows a `PortOS | iTerm2` switch. `/shell` and `/shell/:sessionId` stay PortOS shells. `/shell/iterm` lists the iTerm2 sessions, grouped window › tab › pane, and `/shell/iterm/iterm-<uuid>` opens one directly (⌘K "iterm" goes there too). The view has an amber iTerm2 frame and badge plus a `cols×rows · sized by iTerm` geometry badge. The input helpers (Ctrl-C, Esc, arrows, paste, quick commands, fullscreen) all work. New, Stop, Restart, the cd picker and the provider launcher are absent on purpose.+## How it works- **In-process and demand-driven.** `server/services/itermBridge.js` holds one WebSocket to iTerm2's private Unix socket (`~/Library/Application Support/iTerm2/private/socket`, subprotocol `api.iterm2.com`). It connects only while the feature is on **and** a browser is listing or viewing iTerm2 sessions (`iterm:list`). It disconnects 60s after the last viewer leaves, and at once when the feature is turned off. Server boot never connects.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex db22b77238..e05a0b0c9c 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -208,6 +208,9 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', feature: 'jira', aliases: ['jira-reports'] },{ id: 'nav.devtools.quota-burn', path: '/devtools/quota-burn', label: 'Quota Burn', section: 'Models', tabId: 'quota-burn', navGroup: 'Operate', aliases: ['quota-burn', 'burn-quota', 'quota'], keywords: ['subscription', 'usage', 'reset window', 'spend quota', 'claude', 'codex', 'grok', 'agy', 'burn'] },{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },+ // ⌘K / voice only — no sidebar row: the view is reached from the Shell page's+ // PortOS | iTerm2 switch (#8114).+ { id: 'nav.shell-iterm', path: '/shell/iterm', label: 'iTerm2 Sessions', section: 'Dev Tools', feature: 'iterm', aliases: ['iterm', 'iterm2'], keywords: ['terminal', 'mac', 'sessions'] },{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Models', tabId: 'usage', navGroup: 'Operate', aliases: ['devtools-usage'] },{ id: 'nav.devtools.video-download', path: '/devtools/video-download', label: 'Video Downloader', section: 'Dev Tools', aliases: ['video-download', 'video-downloader', 'download-video'], keywords: ['youtube', 'x.com', 'twitter', 'yt-dlp', 'download', 'clip'] },{ id: 'nav.workspace-contexts', path: '/workspace-contexts', label: 'Workspaces', section: 'Dev Tools', aliases: ['workspaces', 'workspace-contexts', 'project-contexts', 'project-switcher'], keywords: ['project', 'context', 'switch project', 'branch', 'shell', 'tasks', 'restore', 'working context'] },