Skip to content

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

feat: add the iTerm2 bridge server for the Shell page's iTerm2 view (#8114)

[._.]/ Adam Eivy8c2f3a7c7995
diff --git a/docs/API.md b/docs/API.md
index c79eac39f7..fd3de6d7f4 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -768,6 +768,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models |
| `/api/privacy` | PII vault / trusted-org / broker opt-out |
| `/api/shell` | Browser PTY shells |
+| `/api/iterm` | iTerm2 view capability status (`GET /status` → `{ state, detail }`); sessions themselves travel over the `iterm:*` socket events ([ITERM.md](./ITERM.md)) |
| `/api/ports` | Port scan / allocation |
| `/api/logs` | PM2 process logs |
| `/api/detect` | App-repo detection |
@@ -911,6 +912,21 @@ socket.emit('shell:resize', { sessionId, cols: 120, rows: 40 });
socket.emit('shell:stop', { sessionId });
```
+### iTerm2 Sessions
+
+The Shell page's iTerm2 view uses its own `iterm:*` events, never the `shell:*` ones — see [ITERM.md](./ITERM.md). There is no start, stop or resize: iTerm2 owns its sessions' lifecycle and size.
+
+```javascript
+socket.emit('iterm:list'); // subscribe; replies (and re-broadcasts) iterm:sessions
+socket.on('iterm:sessions', ({ status, sessions }) => {}); // status.state, [{ id: 'iterm-<uuid>', windowIndex, tabIndex, paneIndex, label, cwd, cols, rows, … }]
+socket.emit('iterm:attach', { id }); // → iterm:attached { id, cols, rows, bufferedOutput } | iterm:error
+socket.on('iterm:output', ({ id, data }) => {}); // one full-screen ANSI repaint per frame
+socket.emit('iterm:input', { id, data: 'ls\r' }); // exact bytes, delivered in order
+socket.on('iterm:exit', ({ id }) => {}); // session closed or iTerm2 went away
+socket.emit('iterm:detach', { id });
+socket.emit('iterm:unlist');
+```
+
### Provider Status
```javascript
diff --git a/docs/ITERM.md b/docs/ITERM.md
new file mode 100644
index 0000000000..b6d951df12
--- /dev/null
+++ b/docs/ITERM.md
@@ -0,0 +1,45 @@
+# iTerm2 sessions on the Shell page
+
+On a Mac running iTerm2, PortOS can list the terminals you already have open in iTerm2, show one live with its colors and cursor, and type into it. This is the Shell page's **iTerm2 view** (#8114). On any other host nothing changes: there is no iTerm2 UI, no connection attempt, and no AppleScript runs.
+
+## Requirements
+
+- macOS, with iTerm2 installed in `/Applications/iTerm.app` or `~/Applications/iTerm.app`.
+- iTerm2's Python API turned on: **iTerm2 → Settings → General → Magic → Enable Python API**. (PortOS does not use Python; the setting enables the API server that PortOS talks to.)
+- The **iTerm2 sessions** feature on in **Settings → Features**. On a fresh install it turns on by itself when the two checks above pass. The check only looks for the app bundle and reads one `defaults` value (`com.googlecode.iterm2 EnableAPIServer`). It never runs AppleScript and never connects.
+
+The first time PortOS connects, macOS may ask whether PortOS (the process running `osascript`) may control iTerm2. Allow it under **System Settings → Privacy & Security → Automation**.
+
+## 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.
+- **Never launches iTerm2.** Before every connection attempt it checks `application "iTerm2" is running`. Only then does it ask iTerm2 for a fresh auth cookie (`request cookie and key for app named "PortOS"`). A plain `tell application` would launch the app. The cookie is never logged.
+- **Streams only what you view.** Screen-update notifications are subscribed per session only while it is being viewed. A burst of updates collapses into one buffer fetch in flight plus one trailing fetch. Each fetch becomes one full-screen ANSI repaint (`server/lib/itermScreenRender.js`).
+- **Input is exact and ordered.** Keystrokes, escape sequences and bracketed pastes are sent byte-for-byte through a per-session queue.
+- **iTerm2 owns size and lifecycle.** The web view never resizes the iTerm2 window, because a phone would shrink the desktop window. The server reports iTerm2's grid and the view sizes itself to match. PortOS cannot create, close or restart iTerm2 sessions; leaving a session only stops viewing it.
+- **Reconnects by itself.** If iTerm2 quits, the list clears and the status becomes `not-running`. PortOS retries with backoff (1s → 2s → … capped at 30s) while the view is open, and reconnects once iTerm2 is running again.
+
+## Status states
+
+`GET /api/iterm/status` returns capability state only, `{ state, detail }`, never session contents.
+
+| State | Meaning | Fix |
+|---|---|---|
+| `unsupported-platform` | Not macOS | None; the feature does not apply |
+| `not-installed` | No iTerm.app found | Install iTerm2 in `/Applications` or `~/Applications` |
+| `api-disabled` | iTerm2's API server is off | iTerm2 → Settings → General → Magic → Enable Python API |
+| `not-running` | iTerm2 isn't running | Launch iTerm2; PortOS never launches it |
+| `auth-failed` | iTerm2 refused the cookie request | Allow PortOS to control iTerm2 in System Settings → Privacy & Security → Automation |
+| `connect-failed` | The socket or handshake failed | Check that the API is enabled and iTerm2 is up to date |
+| `disconnected` | Not currently connected (nothing is viewing, or the feature is off) | None needed |
+| `connected` | Live | None needed |
+
+## Why iTerm2 sessions are separate from PortOS shells
+
+iTerm2 sessions have their own registry (`itermBridge.js`) and their own socket events (`iterm:list`, `iterm:unlist`, `iterm:attach`, `iterm:detach`, `iterm:input`, and outbound `iterm:sessions`, `iterm:attached`, `iterm:output`, `iterm:exit`, `iterm:error`). They are **never** added to `server/services/shell.js` `shellSessions`. That registry also feeds the Workspaces widget (`workspaceContext.js` groups `listAllSessions()` by cwd), the session cap, and the agent runners' session lookups. Registering iTerm2 sessions there would leak them into Workspaces. It would also force iTerm2 special cases into kill/resize/attach and put the pause-while-watched behavior of TUI runs at risk. `itermBridge.test.js` asserts the bridge's import graph never reaches `shell.js` or `workspaceContext.js`.
+
+Nothing here enters federation or sync. iTerm2 sessions stay on this machine.
+
+## Clean-room protocol rule
+
+iTerm2 and its Python client are GPLv2; PortOS is MIT. The wire codec (`server/lib/protobufWire.js`) and the message declarations (`server/lib/itermMessages.js`) are written by PortOS. They declare only the messages and fields PortOS uses, with field numbers that match iTerm2's published API protocol. **Do not vendor `api.proto`, paste its text, or port reference-client code.** Unknown fields on the wire are skipped, so declaring less than the full protocol is safe.
diff --git a/docs/README.md b/docs/README.md
index 2a32d748b4..41ba4b031c 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -19,6 +19,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [STORAGE.md](./STORAGE.md) | Storage classification contract — PostgreSQL vs filesystem, new-data-store checklist |
| [BACKUP.md](./BACKUP.md) | Filesystem snapshots + PostgreSQL dumps, restore semantics |
| [PORTS.md](./PORTS.md) | Port allocation (5553–5561) and how 5555/5553/5554 relate |
+| [ITERM.md](./ITERM.md) | The Shell page's iTerm2 view — requirements, status states and their fixes, why iTerm2 sessions stay separate from PortOS shells, the clean-room protocol rule |
| [INSTANCE_FEATURES.md](./INSTANCE_FEATURES.md) | Optional per-install features — registry, client-side nav gating, feature groups, reconcile-at-toggle |
| [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects |
| [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry |
diff --git a/server/index.js b/server/index.js
index fb5bf492ee..d8268b7940 100644
--- a/server/index.js
+++ b/server/index.js
@@ -35,6 +35,7 @@ import usageRoutes from './routes/usage.js';
import quotaBurnRoutes from './routes/quotaBurn.js';
import screenshotsRoutes from './routes/screenshots.js';
import shellRoutes from './routes/shell.js';
+import itermRoutes from './routes/iterm.js';
import attachmentsRoutes from './routes/attachments.js';
import clientErrorsRoutes from './routes/clientErrors.js';
import autoFixMetricsRoutes from './routes/autoFixMetrics.js';
@@ -307,6 +308,7 @@ app.use('/api/usage', usageRoutes);
app.use('/api/quota-burn', quotaBurnRoutes);
app.use('/api/screenshots', screenshotsRoutes);
app.use('/api/shell', shellRoutes);
+app.use('/api/iterm', itermRoutes);
app.use('/api/search', searchRoutes);
app.use('/api/rapid-reader', rapidReaderRoutes);
app.use('/api/palette', paletteRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 01bf35f0ac..cbc0b2f5e9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -448,6 +448,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `beeperOAuthOrigin.js` | Which origin the Beeper OAuth `redirect_uri` is built from: `parseBrowserOrigin` (a bare `http(s)://host[:port]`, else null), `hostnameOf`, `isLoopbackHostname` (the loopback-spelling predicate reused by the `settings.beeper.baseUrl` gate and the OAuth token-endpoint host pin), and `resolveOAuthOrigin({ clientOrigin, requestOrigin, configuredOrigins })` → `{ origin, source, rejectedClientOrigin }`. The browser sends `window.location.origin` because the request-derived origin is the API's own under the Vite dev proxy (`changeOrigin`, no `x-forwarded-*`), which sends the consent redirect to a host the TLS cert does not cover; the value is untrusted, so it is accepted only for a loopback host, the request's own host, or a configured `PORTOS_UI_URL`/`PORTOS_API_URL` host — port unpinned, since UI and API are different ports of one install. Rejection falls back to the request origin. Pure. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. `client/src/lib/isSafeHref.js` re-exports it, and `client/src/utils/urlNormalize.js` re-exports that as `isHttpUrl`. |
| `networkExposure.js` | Runtime scheme/bind/cert snapshot plus the shared ordered Tailscale, MagicDNS, certificate, and trusted-launch setup guide used by CLI and UI; `localApiBaseUrl()` resolves the plain-HTTP loopback origin (mirror port under HTTPS, API port otherwise) for local scripts and agent-facing curl snippets. |
+| `protobufWire.js` | Dependency-free protobuf wire codec over a small declarative schema (`encodeMessage` / `decodeMessage`): varint (64-bit two's complement), bool, string, bytes, nested/recursive message, double; repeated + packed; unknown fields skipped; truncated input throws `code: PROTOBUF_WIRE_ERROR`. |
+| `itermMessages.js` | PortOS-authored (clean-room, no vendored `api.proto`) schemas for the iTerm2 API subset the Shell page's iTerm2 view uses — list sessions, notifications, get buffer, send text, variables — plus `encode/decodeItermClientMessage`, `encode/decodeItermServerMessage` and `flattenItermLayout` (window → tab → pane order). |
+| `itermScreenRender.js` | `renderItermFrame({ lines, cursor, firstVisibleLine, cols, rows })` — one iTerm2 screen snapshot → an in-place ANSI repaint (SGR truecolor/palette/attributes, code-point cell runs for wide chars, scrollback cursor offset, control chars neutralized); `itermStyleToSgr`. |
## Search & indexing
diff --git a/server/lib/index.js b/server/lib/index.js
index 7c86e19671..14b2540956 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -406,10 +406,13 @@ export * from './requestAbort.js';
export * from './httpClient.js';
export * from './httpsState.js';
export * from './isSafeHref.js';
+export * from './itermMessages.js';
+export * from './itermScreenRender.js';
export * from './networkExposure.js';
export * from './peerHttpClient.js';
export * from './peerProbeDiagnostics.js';
export * from './peerSelfHost.js';
+export * from './protobufWire.js';
export * from './peerUrl.js';
export * from './pinterestFeed.js';
export * from './readResponseJson.js';
diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.js
index 1819fa1f01..9d3cd5ce1f 100644
--- a/server/lib/instanceFeatureRegistry.js
+++ b/server/lib/instanceFeatureRegistry.js
@@ -102,6 +102,15 @@ export const INSTANCE_FEATURES = Object.freeze([
// installs on that behavior until the user explicitly changes the flag.
defaultEnabled: true,
}),
+ Object.freeze({
+ id: 'iterm',
+ label: 'iTerm2 sessions',
+ description: 'Show and type into this Mac\'s live iTerm2 sessions from the Shell page. Needs iTerm2 with Settings → General → Magic → Enable Python API.',
+ // The detector in services/instanceFeatures.js turns it on only on a Mac
+ // with iTerm2 installed and its Python API enabled; no host is ever probed
+ // beyond an app-bundle check and one `defaults read` (docs/ITERM.md).
+ defaultEnabled: false,
+ }),
Object.freeze({
id: 'rigging',
label: 'Character rigging',
diff --git a/server/lib/itermMessages.js b/server/lib/itermMessages.js
new file mode 100644
index 0000000000..1553eac190
--- /dev/null
+++ b/server/lib/itermMessages.js
@@ -0,0 +1,228 @@
+// PortOS-authored message declarations for the subset of the iTerm2 scripting
+// API the Shell page's iTerm2 view uses (#8114): list sessions, notification
+// subscribe/unsubscribe, get buffer, send text and get variable.
+//
+// PROTOCOL REFERENCE: the iTerm2 API's documented wire protocol — protobuf
+// frames (`ClientOriginatedMessage` out, `ServerOriginatedMessage` in) over a
+// WebSocket on iTerm2's private Unix socket. Field NUMBERS below match that
+// published protocol so the frames interoperate; the field NAMES, structure
+// and every line of this file are PortOS's own.
+//
+// CLEAN-ROOM RULE: iTerm2 and its Python client are GPLv2 and PortOS is MIT.
+// Do not vendor `api.proto`, paste its text, or port reference-client code into
+// this module. Declare only the messages and fields PortOS actually reads or
+// writes; anything else on the wire is skipped by lib/protobufWire.js.
+
+import { decodeMessage, encodeMessage } from './protobufWire.js';
+
+export const ITERM_NOTIFICATION = Object.freeze({
+ SCREEN_UPDATE: 2,
+ NEW_SESSION: 6,
+ TERMINATE_SESSION: 7,
+ LAYOUT_CHANGE: 8,
+ VARIABLE_CHANGE: 13,
+});
+
+export const ITERM_VARIABLE_SCOPE = Object.freeze({ SESSION: 1 });
+
+// The session variables the iTerm2 view shows next to each session.
+export const ITERM_SESSION_VARIABLES = Object.freeze(['name', 'jobName', 'path']);
+
+const m = (no, schema, extra = {}) => ({ no, type: 'message', schema, ...extra });
+
+// --- shared geometry ---------------------------------------------------------
+
+const COORD = { x: { no: 1, type: 'varint' }, y: { no: 2, type: 'varint' } };
+const SIZE = { width: { no: 1, type: 'varint' }, height: { no: 2, type: 'varint' } };
+const RANGE = { location: { no: 1, type: 'varint' }, length: { no: 2, type: 'varint' } };
+const COORD_RANGE = { start: m(1, COORD), end: m(2, COORD) };
+const WINDOWED_COORD_RANGE = { coordRange: m(1, COORD_RANGE), columns: m(2, RANGE) };
+
+// --- list sessions / layout --------------------------------------------------
+
+const SESSION_SUMMARY = {
+ uniqueIdentifier: { no: 1, type: 'string' },
+ gridSize: m(3, SIZE),
+ title: { no: 4, type: 'string' },
+};
+
+// A tab's panes form a binary split tree; each link holds a pane or a subtree.
+const SPLIT_TREE_NODE = {
+ vertical: { no: 1, type: 'bool' },
+ links: m(2, () => SPLIT_TREE_LINK, { repeated: true }),
+};
+const SPLIT_TREE_LINK = {
+ session: m(1, SESSION_SUMMARY),
+ node: m(2, SPLIT_TREE_NODE),
+};
+
+const LIST_TAB = {
+ tabId: { no: 2, type: 'string' },
+ root: m(3, SPLIT_TREE_NODE),
+};
+const LIST_WINDOW = {
+ tabs: m(1, LIST_TAB, { repeated: true }),
+ windowId: { no: 2, type: 'string' },
+ number: { no: 4, type: 'varint' },
+};
+const LIST_SESSIONS_RESPONSE = {
+ windows: m(1, LIST_WINDOW, { repeated: true }),
+};
+
+// --- get buffer ------------------------------------------------------------
+
+const LINE_RANGE = {
+ screenContentsOnly: { no: 1, type: 'bool' },
+ trailingLines: { no: 2, type: 'varint' },
+};
+const GET_BUFFER_REQUEST = {
+ session: { no: 1, type: 'string' },
+ lineRange: m(2, LINE_RANGE),
+ includeStyles: { no: 3, type: 'bool' },
+};
+const RGB = { red: { no: 1, type: 'varint' }, green: { no: 2, type: 'varint' }, blue: { no: 3, type: 'varint' } };
+// fg/bg are each a oneof: an "alternate" semantic color (0 = default), a
+// 24-bit color, or a 256-color palette index.
+const CELL_STYLE = {
+ fgAlternate: { no: 1, type: 'varint' },
+ fgRgb: m(2, RGB),
+ fgStandard: { no: 3, type: 'varint' },
+ bgAlternate: { no: 5, type: 'varint' },
+ bgRgb: m(6, RGB),
+ bgStandard: { no: 7, type: 'varint' },
+ bold: { no: 9, type: 'bool' },
+ faint: { no: 10, type: 'bool' },
+ italic: { no: 11, type: 'bool' },
+ underline: { no: 13, type: 'bool' },
+ strikethrough: { no: 14, type: 'bool' },
+ invisible: { no: 15, type: 'bool' },
+ inverse: { no: 16, type: 'bool' },
+ repeats: { no: 20, type: 'varint' },
+};
+const CODE_POINTS_PER_CELL = {
+ numCodePoints: { no: 1, type: 'varint' },
+ repeats: { no: 2, type: 'varint' },
+};
+const LINE_CONTENTS = {
+ text: { no: 1, type: 'string' },
+ codePointsPerCell: m(2, CODE_POINTS_PER_CELL, { repeated: true }),
+ style: m(4, CELL_STYLE, { repeated: true }),
+};
+const GET_BUFFER_RESPONSE = {
+ status: { no: 1, type: 'varint' },
+ range: m(2, RANGE),
+ contents: m(3, LINE_CONTENTS, { repeated: true }),
+ cursor: m(4, COORD),
+ numLinesAboveScreen: { no: 5, type: 'varint' },
+ windowedCoordRange: m(6, WINDOWED_COORD_RANGE),
+};
+
+// --- notifications -----------------------------------------------------------
+
+const VARIABLE_MONITOR_REQUEST = {
+ name: { no: 1, type: 'string' },
+ scope: { no: 2, type: 'varint' },
+ identifier: { no: 3, type: 'string' },
+};
+const NOTIFICATION_REQUEST = {
+ session: { no: 1, type: 'string' },
+ subscribe: { no: 2, type: 'bool' },
+ notificationType: { no: 3, type: 'varint' },
+ variableMonitorRequest: m(6, VARIABLE_MONITOR_REQUEST),
+};
+const STATUS_ONLY = { status: { no: 1, type: 'varint' } };
+const SESSION_REF = { session: { no: 1, type: 'string' } };
+const SESSION_ID_REF = { sessionId: { no: 1, type: 'string' } };
+const LAYOUT_CHANGED = { listSessionsResponse: m(1, LIST_SESSIONS_RESPONSE) };
+const VARIABLE_CHANGED = {
+ scope: { no: 1, type: 'varint' },
+ identifier: { no: 2, type: 'string' },
+ name: { no: 3, type: 'string' },
+ jsonNewValue: { no: 4, type: 'string' },
+};
+const NOTIFICATION = {
+ screenUpdateNotification: m(2, SESSION_REF),
+ newSessionNotification: m(6, SESSION_ID_REF),
+ terminateSessionNotification: m(7, SESSION_ID_REF),
+ layoutChangedNotification: m(8, LAYOUT_CHANGED),
+ variableChangedNotification: m(13, VARIABLE_CHANGED),
+};
+
+// --- send text / variables ---------------------------------------------------
+
+const SEND_TEXT_REQUEST = {
+ session: { no: 1, type: 'string' },
+ text: { no: 2, type: 'string' },
+};
+const VARIABLE_REQUEST = {
+ sessionId: { no: 1, type: 'string' },
+ get: { no: 5, type: 'string', repeated: true },
+};
+const VARIABLE_RESPONSE = {
+ status: { no: 1, type: 'varint' },
+ values: { no: 2, type: 'string', repeated: true },
+};
+
+// --- envelopes ---------------------------------------------------------------
+
+export const CLIENT_MESSAGE_SCHEMA = Object.freeze({
+ id: { no: 1, type: 'varint' },
+ getBufferRequest: m(100, GET_BUFFER_REQUEST),
+ notificationRequest: m(103, NOTIFICATION_REQUEST),
+ listSessionsRequest: m(106, {}),
+ sendTextRequest: m(107, SEND_TEXT_REQUEST),
+ variableRequest: m(115, VARIABLE_REQUEST),
+});
+
+export const SERVER_MESSAGE_SCHEMA = Object.freeze({
+ id: { no: 1, type: 'varint' },
+ error: { no: 2, type: 'string' },
+ getBufferResponse: m(100, GET_BUFFER_RESPONSE),
+ notificationResponse: m(103, STATUS_ONLY),
+ listSessionsResponse: m(106, LIST_SESSIONS_RESPONSE),
+ sendTextResponse: m(107, STATUS_ONLY),
+ variableResponse: m(115, VARIABLE_RESPONSE),
+ notification: m(1000, NOTIFICATION),
+});
+
+export const encodeItermClientMessage = (msg) => encodeMessage(CLIENT_MESSAGE_SCHEMA, msg);
+export const decodeItermClientMessage = (buf) => decodeMessage(CLIENT_MESSAGE_SCHEMA, buf);
+export const encodeItermServerMessage = (msg) => encodeMessage(SERVER_MESSAGE_SCHEMA, msg);
+export const decodeItermServerMessage = (buf) => decodeMessage(SERVER_MESSAGE_SCHEMA, buf);
+
+// Depth-first pane order of one tab's split tree.
+const collectPanes = (node, out = []) => {
+ for (const link of node?.links ?? []) {
+ if (link.session?.uniqueIdentifier) out.push(link.session);
+ else if (link.node) collectPanes(link.node, out);
+ }
+ return out;
+};
+
+/**
+ * Flatten a decoded list-sessions (or layout-changed) response into panes in
+ * iTerm's own window → tab → pane order. Indexes are 1-based for display.
+ */
+export const flattenItermLayout = (listSessionsResponse) => {
+ const panes = [];
+ (listSessionsResponse?.windows ?? []).forEach((window, windowIdx) => {
+ (window.tabs ?? []).forEach((tab, tabIdx) => {
+ const tabPanes = collectPanes(tab.root);
+ tabPanes.forEach((summary, paneIdx) => {
+ panes.push({
+ uuid: summary.uniqueIdentifier,
+ windowId: window.windowId ?? null,
+ tabId: tab.tabId ?? null,
+ windowIndex: windowIdx + 1,
+ tabIndex: tabIdx + 1,
+ paneIndex: paneIdx + 1,
+ paneCount: tabPanes.length,
+ title: summary.title ?? '',
+ cols: summary.gridSize?.width ?? 0,
+ rows: summary.gridSize?.height ?? 0,
+ });
+ });
+ });
+ });
+ return panes;
+};
diff --git a/server/lib/itermScreenRender.js b/server/lib/itermScreenRender.js
new file mode 100644
index 0000000000..c6b468029f
--- /dev/null
+++ b/server/lib/itermScreenRender.js
@@ -0,0 +1,112 @@
+// Render one iTerm2 get-buffer snapshot (decoded by lib/itermMessages.js) into
+// a single ANSI string that repaints an xterm.js viewer in place (#8114).
+//
+// Frame layout: hide the cursor and home, then for each screen row
+// `CSI r;1H` + SGR runs + text + `CSI 0m CSI K`, then park the cursor at
+// iTerm's cursor position and show it again. Rows past the snapshot are
+// cleared, so a shrinking screen leaves no stale text behind.
+//
+// iTerm reports the cursor in ABSOLUTE scrollback coordinates, so its row is
+// offset by the first visible line number before use. Cells are rebuilt from
+// the per-cell code-point run lengths so combined and wide characters (CJK,
+// emoji) keep the following text column-aligned; a cell with zero code points
+// (the right half of a wide character) emits nothing.
+
+const ESC = '\x1b[';
+
+const sgrColor = (base, rgb, standard) => {
+ if (rgb) return `${base + 8};2;${rgb.red ?? 0};${rgb.green ?? 0};${rgb.blue ?? 0}`;
+ if (standard !== undefined) return `${base + 8};5;${standard}`;
+ return `${base + 9}`;
+};
+
+/** SGR parameter string for one decoded cell style (`undefined` = default). */
+export const itermStyleToSgr = (style) => {
+ const params = ['0'];
+ if (!style) return params.join(';');
+ if (style.bold) params.push('1');
+ if (style.faint) params.push('2');
+ if (style.italic) params.push('3');
+ if (style.underline) params.push('4');
+ if (style.inverse) params.push('7');
+ if (style.invisible) params.push('8');
+ if (style.strikethrough) params.push('9');
+ const fg = sgrColor(30, style.fgRgb, style.fgStandard);
+ const bg = sgrColor(40, style.bgRgb, style.bgStandard);
+ if (fg !== '39') params.push(fg);
+ if (bg !== '49') params.push(bg);
+ return params.join(';');
+};
+
+// Replace C0/C1 controls and DEL so screen text can never smuggle an escape
+// sequence into the viewer's terminal.
+const safeText = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ');
+
+// Expand run-length encoded entries (`repeats`, default 1) lazily.
+const runLengthCursor = (runs) => {
+ let runIdx = 0;
+ let used = 0;
+ return () => {
+ while (runIdx < runs.length) {
+ const run = runs[runIdx];
+ const repeats = Math.max(1, run?.repeats ?? 1);
+ if (used < repeats) {
+ used += 1;
+ return run;
+ }
+ runIdx += 1;
+ used = 0;
+ }
+ return undefined;
+ };
+};
+
+const renderLine = (line, cols) => {
+ const codePoints = Array.from(line?.text ?? '');
+ const cells = line?.codePointsPerCell ?? [];
+ const nextCell = runLengthCursor(cells);
+ const nextStyle = runLengthCursor(line?.style ?? []);
+ let out = '';
+ let lastSgr = null;
+ let cp = 0;
+ for (let col = 0; col < cols && cp < codePoints.length; col += 1) {
+ const cell = cells.length > 0 ? nextCell() : null;
+ if (cells.length > 0 && !cell) break;
+ const width = cell ? (cell.numCodePoints ?? 1) : 1;
+ const sgr = itermStyleToSgr(nextStyle());
+ const text = codePoints.slice(cp, cp + width).join('');
+ cp += width;
+ if (width === 0) continue;
+ if (sgr !== lastSgr) {
+ out += `${ESC}${sgr}m`;
+ lastSgr = sgr;
+ }
+ out += safeText(text);
+ }
+ return out;
+};
+
+const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
+
+/**
+ * @param {object} frame
+ * @param {Array} frame.lines - decoded LineContents, top row first
+ * @param {{x:number,y:number}} [frame.cursor] - absolute (scrollback) cursor
+ * @param {number} [frame.firstVisibleLine] - absolute line number of row 1
+ * @param {number} frame.cols
+ * @param {number} frame.rows
+ * @returns {string}
+ */
+export const renderItermFrame = ({ lines = [], cursor, firstVisibleLine = 0, cols, rows }) => {
+ const width = Math.max(1, cols || 0);
+ const height = Math.max(1, rows || lines.length || 1);
+ let out = `${ESC}?25l${ESC}H`;
+ for (let row = 0; row < height; row += 1) {
+ out += `${ESC}${row + 1};1H${renderLine(lines[row], width)}${ESC}0m${ESC}K`;
+ }
+ const cursorRow = cursor ? clamp((cursor.y ?? 0) - firstVisibleLine + 1, 1, height) : 1;
+ const cursorCol = cursor ? clamp((cursor.x ?? 0) + 1, 1, width) : 1;
+ out += `${ESC}${cursorRow};${cursorCol}H`;
+ if (cursor) out += `${ESC}?25h`;
+ return out;
+};
diff --git a/server/lib/itermScreenRender.test.js b/server/lib/itermScreenRender.test.js
new file mode 100644
index 0000000000..455c93731a
--- /dev/null
+++ b/server/lib/itermScreenRender.test.js
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+import { itermStyleToSgr, renderItermFrame } from './itermScreenRender.js';
+
+const E = '\x1b[';
+
+describe('itermStyleToSgr', () => {
+ it('maps truecolor, palette, default colors and attributes', () => {
+ expect(itermStyleToSgr(undefined)).toBe('0');
+ expect(itermStyleToSgr({ fgAlternate: 0, bgAlternate: 0 })).toBe('0');
+ expect(itermStyleToSgr({ fgRgb: { red: 255, green: 16, blue: 0 } })).toBe('0;38;2;255;16;0');
+ // Palette index 0 (black) is a real color, not "unset".
+ expect(itermStyleToSgr({ fgStandard: 0, bgStandard: 200 })).toBe('0;38;5;0;48;5;200');
+ expect(itermStyleToSgr({ bold: true, faint: true, italic: true, underline: true, inverse: true, strikethrough: true }))
+ .toBe('0;1;2;3;4;7;9');
+ });
+});
+
+describe('renderItermFrame', () => {
+ it('positions every row, emits SGR only on style changes, and clears stale rows', () => {
+ const red = { fgStandard: 1, repeats: 2 };
+ const plain = { repeats: 3 };
+ const frame = renderItermFrame({
+ lines: [{ text: 'hello', style: [red, plain] }],
+ cursor: { x: 5, y: 0 },
+ firstVisibleLine: 0,
+ cols: 10,
+ rows: 2,
+ });
+ expect(frame.startsWith(`${E}?25l${E}H`)).toBe(true);
+ expect(frame).toContain(`${E}1;1H${E}0;38;5;1mhe${E}0mllo${E}0m${E}K`);
+ expect(frame).toContain(`${E}2;1H${E}0m${E}K`);
+ expect(frame.endsWith(`${E}1;6H${E}?25h`)).toBe(true);
+ });
+
+ it('keeps wide and combined characters column-aligned via code-point runs', () => {
+ // Cells: 'a', '界' (wide), its right half (0 code points), 'e'+U+0301 (2 code points), 'z'.
+ const frame = renderItermFrame({
+ lines: [{
+ text: 'a界éz',
+ codePointsPerCell: [
+ { numCodePoints: 1, repeats: 2 },
+ { numCodePoints: 0 },
+ { numCodePoints: 2 },
+ { numCodePoints: 1 },
+ ],
+ }],
+ cols: 5,
+ rows: 1,
+ });
+ expect(frame).toContain(`${E}1;1H${E}0ma界éz${E}0m${E}K`);
+ });
+
+ it('offsets the scrollback-absolute cursor by the first visible line', () => {
+ const frame = renderItermFrame({ lines: [], cursor: { x: 2, y: 1041 }, firstVisibleLine: 1000, cols: 80, rows: 50 });
+ expect(frame.endsWith(`${E}42;3H${E}?25h`)).toBe(true);
+ });
+
+ it('neutralizes control characters so screen text cannot inject escapes', () => {
+ const frame = renderItermFrame({ lines: [{ text: 'a\x1b[2Jb' }], cols: 10, rows: 1 });
+ expect(frame).toContain('a [2Jb');
+ expect(frame).not.toContain('\x1b[2J');
+ });
+});
diff --git a/server/lib/protobufWire.js b/server/lib/protobufWire.js
new file mode 100644
index 0000000000..e98ef2a462
--- /dev/null
+++ b/server/lib/protobufWire.js
@@ -0,0 +1,227 @@
+// Minimal, dependency-free protobuf wire codec for a small declarative schema.
+//
+// A schema maps a JS field name to its wire declaration:
+//
+// { id: { no: 1, type: 'varint' }, name: { no: 2, type: 'string' },
+// tags: { no: 3, type: 'string', repeated: true },
+// child: { no: 4, type: 'message', schema: () => CHILD_SCHEMA } }
+//
+// Types: 'varint' (int32/int64/uint32/uint64/enum — decoded as a Number, with
+// 64-bit two's complement read back as a negative), 'bool', 'string', 'bytes'
+// (Buffer), 'message' (nested; `schema` is an object or a thunk so recursive
+// messages can reference themselves), and 'double'.
+//
+// Decoding skips any field number the schema does not declare (and a declared
+// field whose wire type does not match), for every skippable wire type
+// (varint, fixed64, length-delimited, fixed32). Truncated or malformed input
+// throws an Error with `code: PROTOBUF_WIRE_ERROR` rather than returning a partial object.
+// Absent singular fields decode as `undefined`; absent repeated fields as `[]`.
+
+const WIRE_VARINT = 0;
+const WIRE_FIXED64 = 1;
+const WIRE_LENGTH_DELIMITED = 2;
+const WIRE_FIXED32 = 5;
+
+const TWO_POW_63 = 1n << 63n;
+const TWO_POW_64 = 1n << 64n;
+
+export const PROTOBUF_WIRE_ERROR = 'PROTOBUF_WIRE';
+const wireError = (message) => Object.assign(new Error(message), { code: PROTOBUF_WIRE_ERROR });
+
+const WIRE_TYPE_FOR = Object.freeze({
+ varint: WIRE_VARINT,
+ bool: WIRE_VARINT,
+ string: WIRE_LENGTH_DELIMITED,
+ bytes: WIRE_LENGTH_DELIMITED,
+ message: WIRE_LENGTH_DELIMITED,
+ double: WIRE_FIXED64,
+});
+
+const resolveSchema = (schema) => (typeof schema === 'function' ? schema() : schema);
+
+// --- encoding ---------------------------------------------------------------
+
+const encodeVarint = (value, out) => {
+ let v = typeof value === 'bigint' ? value : BigInt(Math.trunc(Number(value)));
+ if (v < 0n) v += TWO_POW_64;
+ do {
+ let byte = Number(v & 0x7fn);
+ v >>= 7n;
+ if (v > 0n) byte |= 0x80;
+ out.push(byte);
+ } while (v > 0n);
+};
+
+const pushBytes = (out, bytes) => {
+ for (const b of bytes) out.push(b);
+};
+
+const encodeField = (field, value, out) => {
+ const wireType = WIRE_TYPE_FOR[field.type];
+ if (wireType === undefined) throw wireError(`Unsupported field type: ${field.type}`);
+ encodeVarint((field.no << 3) | wireType, out);
+ switch (field.type) {
+ case 'varint':
+ encodeVarint(value, out);
+ break;
+ case 'bool':
+ out.push(value ? 1 : 0);
+ break;
+ case 'double': {
+ const buf = Buffer.alloc(8);
+ buf.writeDoubleLE(Number(value), 0);
+ pushBytes(out, buf);
+ break;
+ }
+ case 'string':
+ case 'bytes':
+ case 'message': {
+ const payload = field.type === 'string'
+ ? Buffer.from(String(value), 'utf8')
+ : field.type === 'bytes'
+ ? Buffer.from(value)
+ : encodeMessage(resolveSchema(field.schema), value);
+ encodeVarint(payload.length, out);
+ pushBytes(out, payload);
+ break;
+ }
+ default:
+ throw wireError(`Unsupported field type: ${field.type}`);
+ }
+};
+
+/** Encode `obj` against `schema`; `undefined`/`null` fields are omitted. */
+export const encodeMessage = (schema, obj = {}) => {
+ const out = [];
+ for (const [name, field] of Object.entries(schema)) {
+ const value = obj?.[name];
+ if (value === undefined || value === null) continue;
+ if (field.repeated) {
+ if (!Array.isArray(value)) throw wireError(`Repeated field "${name}" must be an array`);
+ for (const item of value) encodeField(field, item, out);
+ } else {
+ encodeField(field, value, out);
+ }
+ }
+ return Buffer.from(out);
+};
+
+// --- decoding ---------------------------------------------------------------
+
+const readVarint = (buf, state) => {
+ let result = 0n;
+ let shift = 0n;
+ for (let i = 0; i < 10; i += 1) {
+ if (state.pos >= buf.length) throw wireError('Truncated varint');
+ const byte = buf[state.pos];
+ state.pos += 1;
+ result |= BigInt(byte & 0x7f) << shift;
+ if ((byte & 0x80) === 0) return result & (TWO_POW_64 - 1n);
+ shift += 7n;
+ }
+ throw wireError('Varint exceeds 10 bytes');
+};
+
+const varintToNumber = (big) => Number(big >= TWO_POW_63 ? big - TWO_POW_64 : big);
+
+const readLengthDelimited = (buf, state) => {
+ const length = Number(readVarint(buf, state));
+ const end = state.pos + length;
+ if (end > buf.length) throw wireError('Truncated length-delimited field');
+ const slice = buf.subarray(state.pos, end);
+ state.pos = end;
+ return slice;
+};
+
+const skipField = (buf, state, wireType) => {
+ switch (wireType) {
+ case WIRE_VARINT:
+ readVarint(buf, state);
+ return;
+ case WIRE_FIXED64:
+ if (state.pos + 8 > buf.length) throw wireError('Truncated fixed64 field');
+ state.pos += 8;
+ return;
+ case WIRE_LENGTH_DELIMITED:
+ readLengthDelimited(buf, state);
+ return;
+ case WIRE_FIXED32:
+ if (state.pos + 4 > buf.length) throw wireError('Truncated fixed32 field');
+ state.pos += 4;
+ return;
+ default:
+ throw wireError(`Unsupported wire type ${wireType}`);
+ }
+};
+
+const decodeScalar = (field, buf, state) => {
+ switch (field.type) {
+ case 'varint':
+ return varintToNumber(readVarint(buf, state));
+ case 'bool':
+ return readVarint(buf, state) !== 0n;
+ case 'double': {
+ if (state.pos + 8 > buf.length) throw wireError('Truncated double field');
+ const value = buf.readDoubleLE(state.pos);
+ state.pos += 8;
+ return value;
+ }
+ case 'string':
+ return readLengthDelimited(buf, state).toString('utf8');
+ case 'bytes':
+ return Buffer.from(readLengthDelimited(buf, state));
+ case 'message':
+ return decodeMessage(resolveSchema(field.schema), readLengthDelimited(buf, state));
+ default:
+ throw wireError(`Unsupported field type: ${field.type}`);
+ }
+};
+
+const fieldsByNumber = new WeakMap();
+const indexSchema = (schema) => {
+ let index = fieldsByNumber.get(schema);
+ if (!index) {
+ index = new Map(Object.entries(schema).map(([name, field]) => [field.no, { name, field }]));
+ fieldsByNumber.set(schema, index);
+ }
+ return index;
+};
+
+/** Decode `input` (Buffer/Uint8Array) against `schema`. Throws on malformed input. */
+export const decodeMessage = (schema, input) => {
+ const buf = Buffer.isBuffer(input) ? input : Buffer.from(input);
+ const index = indexSchema(schema);
+ const result = {};
+ for (const [name, field] of Object.entries(schema)) {
+ if (field.repeated) result[name] = [];
+ }
+ const state = { pos: 0 };
+ while (state.pos < buf.length) {
+ const tag = Number(readVarint(buf, state));
+ const fieldNo = tag >>> 3;
+ const wireType = tag & 0x7;
+ if (fieldNo === 0) throw wireError('Invalid field number 0');
+ const entry = index.get(fieldNo);
+ if (!entry) {
+ skipField(buf, state, wireType);
+ continue;
+ }
+ const { name, field } = entry;
+ const expected = WIRE_TYPE_FOR[field.type];
+ const packable = field.repeated && (expected === WIRE_VARINT || expected === WIRE_FIXED64);
+ if (packable && wireType === WIRE_LENGTH_DELIMITED) {
+ const packed = readLengthDelimited(buf, state);
+ const inner = { pos: 0 };
+ while (inner.pos < packed.length) result[name].push(decodeScalar(field, packed, inner));
+ continue;
+ }
+ if (wireType !== expected) {
+ skipField(buf, state, wireType);
+ continue;
+ }
+ const value = decodeScalar(field, buf, state);
+ if (field.repeated) result[name].push(value);
+ else result[name] = value;
+ }
+ return result;
+};
diff --git a/server/lib/protobufWire.test.js b/server/lib/protobufWire.test.js
new file mode 100644
index 0000000000..aa37d2707d
--- /dev/null
+++ b/server/lib/protobufWire.test.js
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import { PROTOBUF_WIRE_ERROR, decodeMessage, encodeMessage } from './protobufWire.js';
+
+const NODE = {
+ label: { no: 1, type: 'string' },
+ children: { no: 2, type: 'message', repeated: true, schema: () => NODE },
+};
+
+const SCHEMA = {
+ id: { no: 1, type: 'varint' },
+ flag: { no: 2, type: 'bool' },
+ name: { no: 3, type: 'string' },
+ blob: { no: 4, type: 'bytes' },
+ ratio: { no: 5, type: 'double' },
+ tags: { no: 6, type: 'string', repeated: true },
+ counts: { no: 7, type: 'varint', repeated: true },
+ tree: { no: 8, type: 'message', schema: NODE },
+};
+
+// Hand-built wire bytes for fields the schema does not declare.
+const unknownVarint = [0x48, 0x96, 0x01]; // field 9, varint 150
+const unknownFixed64 = [0x51, 1, 2, 3, 4, 5, 6, 7, 8]; // field 10, fixed64
+const unknownLengthDelimited = [0x5a, 0x03, 0x61, 0x62, 0x63]; // field 11, "abc"
+const unknownFixed32 = [0x65, 1, 2, 3, 4]; // field 12, fixed32
+
+describe('protobufWire', () => {
+ it('round-trips every field type, repeated fields and recursive messages', () => {
+ const value = {
+ id: 300, // multi-byte varint
+ flag: true,
+ name: 'héllo ✓',
+ blob: Buffer.from([0, 255, 7]),
+ ratio: 1.5,
+ tags: ['a', 'b'],
+ counts: [1, 2 ** 40, -1],
+ tree: { label: 'root', children: [{ label: 'leaf', children: [{ label: 'deep', children: [] }] }] },
+ };
+ const decoded = decodeMessage(SCHEMA, encodeMessage(SCHEMA, value));
+ expect(decoded).toEqual(value);
+ });
+
+ it('encodes varints with the standard little-endian base-128 layout', () => {
+ expect([...encodeMessage(SCHEMA, { id: 150 })]).toEqual([0x08, 0x96, 0x01]);
+ // A negative int64 is ten bytes of two's complement and reads back negative.
+ const negative = encodeMessage(SCHEMA, { id: -2 });
+ expect(negative.length).toBe(11);
+ expect(decodeMessage(SCHEMA, negative).id).toBe(-2);
+ });
+
+ it('omits absent fields and decodes them as undefined (repeated as [])', () => {
+ expect(encodeMessage(SCHEMA, { name: undefined, flag: null }).length).toBe(0);
+ const decoded = decodeMessage(SCHEMA, Buffer.alloc(0));
+ expect(decoded.name).toBeUndefined();
+ expect(decoded.tags).toEqual([]);
+ });
+
+ it('skips unknown fields of every wire type', () => {
+ const known = [...encodeMessage(SCHEMA, { id: 7, name: 'x' })];
+ const buf = Buffer.from([
+ ...unknownVarint, ...known.slice(0, 2), ...unknownFixed64,
+ ...unknownLengthDelimited, ...known.slice(2), ...unknownFixed32,
+ ]);
+ expect(decodeMessage(SCHEMA, buf)).toMatchObject({ id: 7, name: 'x' });
+ });
+
+ it('accepts packed encoding for a repeated varint field', () => {
+ const packed = Buffer.from([0x3a, 0x03, 0x01, 0x96, 0x01]); // field 7, [1, 150]
+ expect(decodeMessage(SCHEMA, packed).counts).toEqual([1, 150]);
+ });
+
+ it('rejects truncated input instead of returning a partial object', () => {
+ const full = encodeMessage(SCHEMA, { name: 'truncate me', id: 300 });
+ for (const cut of [1, 5, full.length - 1]) {
+ expect(() => decodeMessage(SCHEMA, full.subarray(0, cut))).toThrow(expect.objectContaining({ code: PROTOBUF_WIRE_ERROR }));
+ }
+ expect(() => decodeMessage(SCHEMA, Buffer.from(unknownFixed64.slice(0, 5)))).toThrow(/Truncated/);
+ expect(() => decodeMessage(SCHEMA, Buffer.from([0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]))).toThrow(/10 bytes/);
+ });
+});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 85f192e74f..498a65fe7a 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -7,6 +7,8 @@ import {
appUpdateSchema,
detectStartSchema,
errorRecoverSchema,
+ itermInputSchema,
+ itermSessionRefSchema,
logsSubscribeSchema,
logsUnsubscribeSchema,
shellAttachSchema,
@@ -29,6 +31,9 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),
'detect:start': input(detectStartSchema, 'Start streamed application detection.'),
'error:recover': input(errorRecoverSchema, 'Request a bounded recovery task for a reported error.'),
+ 'iterm:attach': input(itermSessionRefSchema, 'Start viewing one live iTerm2 session.'),
+ 'iterm:detach': input(itermSessionRefSchema, 'Stop viewing one live iTerm2 session.'),
+ 'iterm:input': input(itermInputSchema, 'Type bytes into one live iTerm2 session.'),
'logs:subscribe': input(logsSubscribeSchema, 'Subscribe to a bounded process-log tail.'),
'logs:unsubscribe': input(logsUnsubscribeSchema, 'Release one process-log subscription or all legacy subscriptions.'),
'shell:attach': input(shellAttachSchema, 'Attach this socket to an existing terminal session.'),
diff --git a/server/lib/socketValidation.js b/server/lib/socketValidation.js
index 02339114d7..517e67f3bd 100644
--- a/server/lib/socketValidation.js
+++ b/server/lib/socketValidation.js
@@ -81,6 +81,19 @@ export const shellAttachSchema = z.object({
// shell:stop — session ID
export const shellStopSchema = shellSessionIdSchema;
+// iterm:* — the iTerm2 view's own events (#8114). Ids are `iterm-<iTerm session
+// UUID>` and never overlap PortOS shell session ids.
+const itermSessionId = z.string().regex(/^iterm-[A-Za-z0-9-]{1,64}$/, 'id must be an iTerm2 session id');
+
+// iterm:attach / iterm:detach — the iTerm2 session to start or stop viewing.
+export const itermSessionRefSchema = z.object({ id: itermSessionId });
+
+// iterm:input — exact bytes to type into the iTerm2 session.
+export const itermInputSchema = z.object({
+ id: itermSessionId,
+ data: z.string().max(1_000_000)
+});
+
// app:update — app ID for pull/install/restart cycle. `acknowledgeFork` and
// `acknowledgePersistentMindImageBackup` are only consulted for the PortOS app
// record — they mirror POST /api/update/execute's executeSchema so App
diff --git a/server/routes/iterm.js b/server/routes/iterm.js
new file mode 100644
index 0000000000..789908db8e
--- /dev/null
+++ b/server/routes/iterm.js
@@ -0,0 +1,13 @@
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { getItermStatus } from '../services/itermBridge.js';
+
+const router = Router();
+
+// GET /api/iterm/status — capability state only ({ state, detail }), never
+// session contents: the iTerm2 view's hint line names the fix for each state.
+router.get('/status', asyncHandler(async (_req, res) => {
+ res.json(await getItermStatus());
+}));
+
+export default router;
diff --git a/server/routes/settings.js b/server/routes/settings.js
index fd15f718de..9927fcf732 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -294,6 +294,15 @@ async function reconcileBeeperArming(reason, options = {}) {
.catch((err) => console.error(`❌ Beeper ingestion reconcile (${reason}) failed: ${err.message}`));
}
+// The iTerm2 bridge connects only while its feature is on (#8114): turning it
+// off must drop the connection now, and turning it on must serve an already-
+// open iTerm2 view without a restart. Same persisted-flag rule as above.
+async function reconcileItermOnToggle() {
+ const { reconcileItermBridge } = await import('../services/itermBridge.js');
+ await reconcileItermBridge({ reason: 'feature-toggle' })
+ .catch((err) => console.error(`❌ iTerm2 bridge reconcile (feature-toggle) failed: ${err.message}`));
+}
+
// An interval-only Beeper save (no `enabled` flip) used to take effect only
// at the next process restart: the registered event's `intervalMs` is read
// once, at `schedule()` time (`createSettingsGatedSyncScheduler.js`), and
@@ -317,6 +326,7 @@ router.put('/features/:featureId', asyncHandler(async (req, res) => {
const { enabled } = validateRequest(instanceFeatureUpdateSchema, req.body || {});
const result = await updateInstanceFeature(featureId, enabled);
if (featureId === 'beeper') await reconcileBeeperArming('feature-toggle');
+ if (featureId === 'iterm') await reconcileItermOnToggle();
res.json(result);
}));
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index e1725148f1..2d8706f11a 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -98,9 +98,16 @@ vi.mock('../services/beeperScheduler.js', () => ({
isBeeperSchedulerRegistered: vi.fn(() => false),
}));
+// The iTerm2 bridge connects only while its feature is on (#8114); what a
+// reconcile does is covered by services/itermBridge.test.js.
+vi.mock('../services/itermBridge.js', () => ({
+ reconcileItermBridge: vi.fn(async () => ({ enabled: false, connected: false })),
+}));
+
import settingsRoutes from './settings.js';
import codeReviewRoutes from './codeReview.js';
import { reconcileBeeperIngestion } from '../services/beeperArming.js';
+import { reconcileItermBridge } from '../services/itermBridge.js';
import { restartBeeperScheduler, isBeeperSchedulerRegistered } from '../services/beeperScheduler.js';
import { updateSettingsWith } from '../services/settings.js';
import { hasConfiguredInstances as hasConfiguredDatadogInstances } from '../services/datadog.js';
@@ -313,6 +320,18 @@ describe('Settings routes — instance feature participation', () => {
expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'feature-toggle' });
});
+ // #8114: turning iTerm2 sessions off must drop the live connection now, and a
+ // reconcile failure must not turn the already-saved toggle into a 500.
+ it('reconciles the iTerm2 bridge when its feature is toggled, without failing the save', async () => {
+ reconcileItermBridge.mockRejectedValueOnce(new Error('bridge exploded'));
+ const res = await request(buildApp())
+ .put('/api/settings/features/iterm')
+ .send({ enabled: false });
+
+ expect(res.status).toBe(200);
+ expect(reconcileItermBridge).toHaveBeenCalledWith({ reason: 'feature-toggle' });
+ });
+
// Beeper sits in the Comms group, so the group toggle moves the same gate.
it('reconciles Beeper ingestion when the Comms group is toggled', async () => {
const res = await request(buildApp())
diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.js
index fa290b37f8..3043753c2d 100644
--- a/server/services/instanceFeatures.js
+++ b/server/services/instanceFeatures.js
@@ -61,6 +61,14 @@ const DETECTORS = {
const report = await checkSetup();
return report.helper?.ok === 'ok' && report.identity?.ok === 'ok';
},
+ // Cheap and fail-closed: platform, app bundle and the EnableAPIServer pref —
+ // no AppleScript, no socket connect, never launches iTerm2.
+ iterm: async () => {
+ if (process.platform !== 'darwin') return false;
+ const { detectItermInstall } = await import('./itermAuth.js');
+ const install = await detectItermInstall().catch(() => null);
+ return install?.state === 'ready';
+ },
};
const FEATURE_BY_ID = new Map(INSTANCE_FEATURES.map((feature) => [feature.id, feature]));
diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.js
index 924a1f2854..0f1233f084 100644
--- a/server/services/instanceFeatures.test.js
+++ b/server/services/instanceFeatures.test.js
@@ -45,6 +45,12 @@ vi.mock('./rigging/readiness.js', () => ({
}),
}));
+// The iTerm2 detector reads a macOS preference; keep a dev Mac's own iTerm2
+// setup out of this suite's answers.
+vi.mock('./itermAuth.js', () => ({
+ detectItermInstall: vi.fn(async () => ({ state: 'not-installed' })),
+}));
+
vi.mock('../lib/gitRemote.js', () => ({
getOriginInfo: vi.fn(async () => mock.portosOrigin),
}));
@@ -308,7 +314,7 @@ describe('instance features', () => {
const { features } = await getInstanceFeatures();
expect(Object.fromEntries(features.map((f) => [f.id, f.enabled]))).toEqual({
post: true, autobiography: true, datadog: true, jira: false, eidoverse: false, gsd: false, 'cos-task-templates': false, openclaw: false, health: true,
- rigging: false, facetime: false, imessage: true, signal: true, x: true, 'stacker-news': true, beeper: false,
+ iterm: false, rigging: false, facetime: false, imessage: true, signal: true, x: true, 'stacker-news': true, beeper: false,
jev: false,
'laya-mlx': false,
});
diff --git a/server/services/itermAuth.js b/server/services/itermAuth.js
new file mode 100644
index 0000000000..232ad14cf7
--- /dev/null
+++ b/server/services/itermAuth.js
@@ -0,0 +1,69 @@
+// Host probes and authentication for the iTerm2 scripting API (#8114).
+//
+// Three tiers, cheapest first:
+// - detectItermInstall(): platform + app bundle + `EnableAPIServer` pref.
+// No AppleScript, no socket — cheap enough for the instance-feature
+// detector, and memoized for 30s.
+// - isItermRunning(): AppleScript `application "iTerm2" is running`, which
+// never launches the app.
+// - requestItermCookie(): AppleScript `request cookie and key`. A bare
+// `tell application` LAUNCHES iTerm2, so this is only ever called after a
+// positive running check. The cookie and key are secrets: never log them.
+
+import { existsSync } from 'fs';
+import { homedir } from 'os';
+import { join } from 'path';
+import { promisify } from 'util';
+import { execFile } from '../lib/childProcess.js';
+
+const execFileAsync = promisify(execFile);
+
+export const ITERM_APP_NAME = 'PortOS';
+const PROBE_TIMEOUT_MS = 10_000;
+const INSTALL_MEMO_MS = 30_000;
+
+export const itermSocketPath = () => join(homedir(), 'Library', 'Application Support', 'iTerm2', 'private', 'socket');
+
+const itermAppPaths = () => ['/Applications/iTerm.app', join(homedir(), 'Applications', 'iTerm.app')];
+
+const readApiServerEnabled = async () => {
+ const { stdout } = await execFileAsync('defaults', ['read', 'com.googlecode.iterm2', 'EnableAPIServer'], { timeout: PROBE_TIMEOUT_MS })
+ .catch(() => ({ stdout: '' }));
+ return stdout.trim() === '1';
+};
+
+let installMemo = null;
+
+/**
+ * @returns {Promise<{ state: 'unsupported-platform'|'not-installed'|'api-disabled'|'ready' }>}
+ */
+export async function detectItermInstall({ now = Date.now() } = {}) {
+ if (installMemo && now - installMemo.at < INSTALL_MEMO_MS) return installMemo.value;
+ let state = 'ready';
+ if (process.platform !== 'darwin') state = 'unsupported-platform';
+ else if (!itermAppPaths().some((path) => existsSync(path))) state = 'not-installed';
+ else if (!await readApiServerEnabled()) state = 'api-disabled';
+ installMemo = { at: now, value: { state } };
+ return installMemo.value;
+}
+
+export const __resetItermInstallMemo = () => { installMemo = null; };
+
+const runAppleScript = async (script) => {
+ const { stdout } = await execFileAsync('osascript', ['-e', script], { timeout: PROBE_TIMEOUT_MS });
+ return stdout.trim();
+};
+
+export async function isItermRunning() {
+ if (process.platform !== 'darwin') return false;
+ const answer = await runAppleScript('application "iTerm2" is running').catch(() => 'false');
+ return answer === 'true';
+}
+
+/** Fresh `{ cookie, key }` for one connection attempt. Throws on failure. */
+export async function requestItermCookie() {
+ const answer = await runAppleScript(`tell application "iTerm2" to request cookie and key for app named "${ITERM_APP_NAME}"`);
+ const [cookie, key] = answer.split(/\s+/);
+ if (!cookie || !key) throw new Error('iTerm2 returned no cookie');
+ return { cookie, key };
+}
diff --git a/server/services/itermBridge.js b/server/services/itermBridge.js
new file mode 100644
index 0000000000..24001179d6
--- /dev/null
+++ b/server/services/itermBridge.js
@@ -0,0 +1,650 @@
+/**
+ * iTerm2 bridge — shows and drives this Mac's live iTerm2 sessions from the
+ * Shell page's iTerm2 view (#8114). Design record: docs/ITERM.md.
+ *
+ * SEPARATE FROM PORTOS SHELLS, BY CONSTRUCTION. iTerm owns these sessions'
+ * size and lifecycle, so they live in this module's own registry and its own
+ * `iterm:*` socket events. Nothing here touches `services/shell.js`
+ * `shellSessions`, so an iTerm session can never appear in the PortOS tab
+ * strip, the Workspaces widget, the session cap, or an agent-run lookup.
+ *
+ * DEMAND-DRIVEN, NEVER AT BOOT. The one connection to iTerm's private Unix
+ * socket opens only while the `iterm` instance feature is enabled AND a socket
+ * is listing or viewing sessions. It closes `idleMs` (60s) after the last
+ * subscriber leaves, and immediately when the feature turns off. Every
+ * connect / disconnect decision goes through `reconcileItermBridge()`, which
+ * is idempotent and serialized on one promise tail (the `beeperArming.js`
+ * shape), and logs only on status transitions.
+ *
+ * STREAMS ONLY WHAT IS VIEWED. Screen-update notifications are subscribed per
+ * session while at least one socket views it; bursts coalesce to one buffer
+ * fetch in flight plus one trailing refetch. The list-level notifications
+ * (new session, terminate, layout, variable changes) stay subscribed for the
+ * life of the connection.
+ *
+ * iTerm IS AUTHORITATIVE FOR SIZE: there is deliberately no resize path — a
+ * phone viewer must never shrink the desktop window. PortOS also never
+ * creates, closes or restarts iTerm sessions.
+ *
+ * Every notification, `ws` event and timer callback runs inside try/catch:
+ * this code executes outside any request lifecycle.
+ */
+
+import net from 'net';
+import WebSocket from 'ws';
+import {
+ ITERM_NOTIFICATION,
+ ITERM_SESSION_VARIABLES,
+ ITERM_VARIABLE_SCOPE,
+ decodeItermServerMessage,
+ encodeItermClientMessage,
+ flattenItermLayout,
+} from '../lib/itermMessages.js';
+import { renderItermFrame } from '../lib/itermScreenRender.js';
+import {
+ ITERM_APP_NAME,
+ detectItermInstall,
+ isItermRunning,
+ itermSocketPath,
+ requestItermCookie,
+} from './itermAuth.js';
+
+export const ITERM_FEATURE_ID = 'iterm';
+export const ITERM_SESSION_PREFIX = 'iterm-';
+export const ITERM_SUBPROTOCOL = 'api.iterm2.com';
+
+const LOG_PREFIX = 'iTerm2 bridge';
+const FAILURE_STATES = new Set(['auth-failed', 'connect-failed']);
+
+const defaultIsFeatureEnabled = async () => {
+ const { isInstanceFeatureEnabled } = await import('./instanceFeatures.js');
+ return isInstanceFeatureEnabled(ITERM_FEATURE_ID);
+};
+
+const parseVariableValue = (json) => {
+ if (typeof json !== 'string' || json === '') return null;
+ try {
+ const value = JSON.parse(json);
+ return typeof value === 'string' ? value : null;
+ } catch {
+ return null;
+ }
+};
+
+const safeEmit = (socket, event, payload) => {
+ try {
+ socket.emit(event, payload);
+ } catch (err) {
+ console.error(`❌ ${LOG_PREFIX}: emit ${event} failed: ${err.message}`);
+ }
+};
+
+export function createItermBridge(deps = {}) {
+ const {
+ socketPath = itermSocketPath,
+ auth = requestItermCookie,
+ isRunning = isItermRunning,
+ detectInstall = detectItermInstall,
+ isFeatureEnabled = defaultIsFeatureEnabled,
+ idleMs = 60_000,
+ backoffInitialMs = 1_000,
+ backoffMaxMs = 30_000,
+ requestTimeoutMs = 10_000,
+ libraryVersion = 'node portos',
+ } = deps;
+
+ let conn = null; // { ws, pending: Map<id, {resolve, reject, timer}>, nextId, warnedVariables }
+ let epoch = 0;
+ let status = { state: 'disconnected', detail: null };
+ let sessions = new Map();
+ const listSubscribers = new Set();
+ let reconnectTimer = null;
+ let reconnectDelay = backoffInitialMs;
+ let idleTimer = null;
+ let idleExpired = false;
+ let tail = Promise.resolve();
+
+ // --- projections & broadcast ----------------------------------------------
+
+ const project = (entry) => ({
+ id: entry.id,
+ windowId: entry.windowId,
+ tabId: entry.tabId,
+ windowIndex: entry.windowIndex,
+ tabIndex: entry.tabIndex,
+ paneIndex: entry.paneIndex,
+ paneCount: entry.paneCount,
+ label: entry.name || entry.title || entry.jobName || 'iTerm2 session',
+ title: entry.title,
+ jobName: entry.jobName,
+ cwd: entry.cwd,
+ cols: entry.cols,
+ rows: entry.rows,
+ });
+
+ const listItermSessions = () => [...sessions.values()].map(project);
+
+ const broadcastList = () => {
+ const payload = { status: { ...status }, sessions: listItermSessions() };
+ for (const socket of listSubscribers) safeEmit(socket, 'iterm:sessions', payload);
+ };
+
+ const setStatus = (state, detail = null) => {
+ if (status.state === state && status.detail === detail) return;
+ const previous = status.state;
+ status = { state, detail };
+ if (previous !== state) {
+ const log = FAILURE_STATES.has(state) ? console.error : console.log;
+ const marker = FAILURE_STATES.has(state) ? '❌' : '🖥️';
+ log(`${marker} ${LOG_PREFIX}: ${previous} → ${state}${detail ? ` (${detail})` : ''}`);
+ }
+ broadcastList();
+ };
+
+ const hasDemand = () => listSubscribers.size > 0
+ || [...sessions.values()].some((entry) => entry.viewers.size > 0);
+
+ // --- request/response -------------------------------------------------------
+
+ const request = (message) => new Promise((resolve, reject) => {
+ if (!conn) {
+ reject(new Error('iTerm2 is not connected'));
+ return;
+ }
+ const current = conn;
+ const id = current.nextId;
+ current.nextId += 1;
+ const timer = setTimeout(() => {
+ current.pending.delete(id);
+ reject(new Error('iTerm2 request timed out'));
+ }, requestTimeoutMs);
+ current.pending.set(id, { resolve, reject, timer });
+ try {
+ current.ws.send(encodeItermClientMessage({ id, ...message }));
+ } catch (err) {
+ clearTimeout(timer);
+ current.pending.delete(id);
+ reject(err);
+ }
+ });
+
+ const rejectPending = (current, reason) => {
+ for (const { reject, timer } of current.pending.values()) {
+ clearTimeout(timer);
+ reject(new Error(reason));
+ }
+ current.pending.clear();
+ };
+
+ // --- session registry -------------------------------------------------------
+
+ const emitExit = (entry) => {
+ for (const viewer of entry.viewers) safeEmit(viewer, 'iterm:exit', { id: entry.id });
+ };
+
+ const clearSessions = () => {
+ for (const entry of sessions.values()) emitExit(entry);
+ sessions = new Map();
+ };
+
+ const subscribeScreen = (entry, subscribe) => request({
+ notificationRequest: { session: entry.uuid, subscribe, notificationType: ITERM_NOTIFICATION.SCREEN_UPDATE },
+ }).catch((err) => {
+ console.error(`❌ ${LOG_PREFIX}: screen ${subscribe ? 'subscribe' : 'unsubscribe'} failed: ${err.message}`);
+ });
+
+ const fetchFrame = (entry) => {
+ if (entry.fetchInFlight) {
+ entry.fetchQueued = true;
+ return entry.fetchInFlight;
+ }
+ entry.fetchInFlight = (async () => {
+ try {
+ do {
+ entry.fetchQueued = false;
+ const response = await request({
+ getBufferRequest: { session: entry.uuid, lineRange: { screenContentsOnly: true }, includeStyles: true },
+ });
+ const buffer = response.getBufferResponse;
+ if (!buffer || sessions.get(entry.id) !== entry) break;
+ const lineCount = buffer.contents.length;
+ if (lineCount > 0 && lineCount !== entry.rows && lineCount !== entry.lastLineCount) {
+ // The grid may have changed under us; the list call refreshes
+ // cols/rows. Once per distinct line count, never once per frame.
+ refreshSessions().catch((err) => console.error(`❌ ${LOG_PREFIX}: resize refresh failed: ${err.message}`));
+ }
+ entry.lastLineCount = lineCount;
+ entry.lastFrame = renderItermFrame({
+ lines: buffer.contents,
+ cursor: buffer.cursor,
+ firstVisibleLine: buffer.windowedCoordRange?.coordRange?.start?.y
+ ?? buffer.range?.location
+ ?? buffer.numLinesAboveScreen
+ ?? 0,
+ cols: entry.cols,
+ rows: Math.max(entry.rows || 0, lineCount),
+ });
+ for (const viewer of entry.viewers) safeEmit(viewer, 'iterm:output', { id: entry.id, data: entry.lastFrame });
+ } while (entry.fetchQueued && entry.viewers.size > 0);
+ } catch (err) {
+ console.error(`❌ ${LOG_PREFIX}: screen fetch failed: ${err.message}`);
+ } finally {
+ entry.fetchInFlight = null;
+ }
+ })();
+ return entry.fetchInFlight;
+ };
+
+ const loadVariables = async (entry) => {
+ const response = await request({ variableRequest: { sessionId: entry.uuid, get: [...ITERM_SESSION_VARIABLES] } });
+ const values = response.variableResponse?.values ?? [];
+ ITERM_SESSION_VARIABLES.forEach((name, idx) => applyVariable(entry, name, values[idx]));
+ };
+
+ const applyVariable = (entry, name, json) => {
+ const value = parseVariableValue(json);
+ if (name === 'name') entry.name = value;
+ else if (name === 'jobName') entry.jobName = value;
+ else if (name === 'path') entry.cwd = value;
+ };
+
+ const monitorVariables = (entry) => Promise.all(ITERM_SESSION_VARIABLES.map((name) => request({
+ notificationRequest: {
+ subscribe: true,
+ notificationType: ITERM_NOTIFICATION.VARIABLE_CHANGE,
+ variableMonitorRequest: { name, scope: ITERM_VARIABLE_SCOPE.SESSION, identifier: entry.uuid },
+ },
+ })));
+
+ const initSession = async (entry) => {
+ try {
+ await loadVariables(entry);
+ broadcastList();
+ await monitorVariables(entry);
+ } catch (err) {
+ if (conn && !conn.warnedVariables) {
+ conn.warnedVariables = true;
+ console.warn(`⚠️ ${LOG_PREFIX}: session variables unavailable: ${err.message}`);
+ }
+ }
+ };
+
+ const applyLayout = (listSessionsResponse) => {
+ const panes = flattenItermLayout(listSessionsResponse);
+ const next = new Map();
+ const added = [];
+ for (const pane of panes) {
+ const id = `${ITERM_SESSION_PREFIX}${pane.uuid}`;
+ let entry = sessions.get(id);
+ if (!entry) {
+ entry = {
+ id, uuid: pane.uuid, name: null, jobName: null, cwd: null, lastFrame: null, lastLineCount: null,
+ viewers: new Set(), fetchInFlight: null, fetchQueued: false, inputTail: Promise.resolve(),
+ };
+ added.push(entry);
+ }
+ const resized = entry.cols !== pane.cols || entry.rows !== pane.rows;
+ Object.assign(entry, {
+ windowId: pane.windowId,
+ tabId: pane.tabId,
+ windowIndex: pane.windowIndex,
+ tabIndex: pane.tabIndex,
+ paneIndex: pane.paneIndex,
+ paneCount: pane.paneCount,
+ title: pane.title,
+ cols: pane.cols,
+ rows: pane.rows,
+ });
+ if (resized && entry.viewers.size > 0 && !added.includes(entry)) fetchFrame(entry);
+ next.set(id, entry);
+ }
+ for (const [id, entry] of sessions) {
+ if (!next.has(id)) emitExit(entry);
+ }
+ sessions = next;
+ broadcastList();
+ for (const entry of added) initSession(entry);
+ };
+
+ const refreshSessions = async () => {
+ const response = await request({ listSessionsRequest: {} });
+ applyLayout(response.listSessionsResponse);
+ };
+
+ const removeSession = (id) => {
+ const entry = sessions.get(id);
+ if (!entry) return;
+ sessions.delete(id);
+ emitExit(entry);
+ broadcastList();
+ };
+
+ // --- notifications ----------------------------------------------------------
+
+ const handleNotification = (notification) => {
+ const screen = notification.screenUpdateNotification;
+ if (screen?.session) {
+ const entry = sessions.get(`${ITERM_SESSION_PREFIX}${screen.session}`);
+ if (entry && entry.viewers.size > 0) fetchFrame(entry);
+ }
+ if (notification.newSessionNotification) {
+ refreshSessions().catch((err) => console.error(`❌ ${LOG_PREFIX}: new-session refresh failed: ${err.message}`));
+ }
+ const terminated = notification.terminateSessionNotification?.sessionId;
+ if (terminated) removeSession(`${ITERM_SESSION_PREFIX}${terminated}`);
+ const layout = notification.layoutChangedNotification?.listSessionsResponse;
+ if (layout) applyLayout(layout);
+ const variable = notification.variableChangedNotification;
+ if (variable?.identifier && variable.scope === ITERM_VARIABLE_SCOPE.SESSION) {
+ const entry = sessions.get(`${ITERM_SESSION_PREFIX}${variable.identifier}`);
+ if (entry && ITERM_SESSION_VARIABLES.includes(variable.name)) {
+ applyVariable(entry, variable.name, variable.jsonNewValue);
+ broadcastList();
+ }
+ }
+ };
+
+ const handleFrame = (data) => {
+ const message = decodeItermServerMessage(data);
+ if (message.notification) {
+ handleNotification(message.notification);
+ return;
+ }
+ const waiter = conn?.pending.get(message.id);
+ if (!waiter) return;
+ conn.pending.delete(message.id);
+ clearTimeout(waiter.timer);
+ if (message.error) waiter.reject(new Error(message.error));
+ else waiter.resolve(message);
+ };
+
+ // --- connection lifecycle ---------------------------------------------------
+
+ const openSocket = ({ cookie, key }) => new Promise((resolve, reject) => {
+ const path = typeof socketPath === 'function' ? socketPath() : socketPath;
+ const ws = new WebSocket('ws://localhost/', ITERM_SUBPROTOCOL, {
+ origin: 'ws://localhost/',
+ headers: {
+ 'x-iterm2-library-version': libraryVersion,
+ 'x-iterm2-disable-auth-ui': 'true',
+ 'x-iterm2-cookie': cookie,
+ 'x-iterm2-key': key,
+ 'x-iterm2-advisory-name': ITERM_APP_NAME,
+ },
+ createConnection: () => net.connect(path),
+ handshakeTimeout: requestTimeoutMs,
+ perMessageDeflate: false,
+ });
+ // A permanent listener: an 'error' after the open promise settled must
+ // never surface as an uncaught EventEmitter error.
+ ws.on('error', (err) => {
+ if (conn?.ws === ws) console.error(`❌ ${LOG_PREFIX}: socket error: ${err.message}`);
+ reject(err);
+ });
+ ws.once('open', () => resolve(ws));
+ });
+
+ const onConnectionLost = (ws) => {
+ if (conn?.ws !== ws) return;
+ const current = conn;
+ conn = null;
+ rejectPending(current, 'iTerm2 connection closed');
+ clearSessions();
+ setStatus('disconnected');
+ scheduleReconnect();
+ };
+
+ const attachConnection = (ws) => {
+ conn = { ws, pending: new Map(), nextId: 1, warnedVariables: false };
+ ws.on('message', (data) => {
+ try {
+ handleFrame(data);
+ } catch (err) {
+ console.error(`❌ ${LOG_PREFIX}: bad frame: ${err.message}`);
+ }
+ });
+ ws.on('close', () => {
+ try {
+ onConnectionLost(ws);
+ } catch (err) {
+ console.error(`❌ ${LOG_PREFIX}: close handling failed: ${err.message}`);
+ }
+ });
+ };
+
+ const scheduleReconnect = () => {
+ if (reconnectTimer || !hasDemand()) return;
+ const delay = reconnectDelay;
+ reconnectDelay = Math.min(delay * 2, backoffMaxMs);
+ reconnectTimer = setTimeout(() => {
+ reconnectTimer = null;
+ reconcileItermBridge({ reason: 'reconnect' }).catch((err) => {
+ console.error(`❌ ${LOG_PREFIX}: reconnect failed: ${err.message}`);
+ });
+ }, delay);
+ };
+
+ const connectOnce = async () => {
+ const myEpoch = epoch;
+ const stale = () => myEpoch !== epoch;
+ const install = await detectInstall();
+ if (stale()) return;
+ if (install.state !== 'ready') {
+ setStatus(install.state);
+ scheduleReconnect();
+ return;
+ }
+ // Checked before EVERY attempt: requesting a cookie from a quit iTerm2
+ // would launch it, and PortOS must never launch iTerm2.
+ if (!await isRunning()) {
+ if (!stale()) {
+ setStatus('not-running');
+ scheduleReconnect();
+ }
+ return;
+ }
+ if (stale()) return;
+ let credentials;
+ try {
+ credentials = await auth();
+ } catch (err) {
+ if (!stale()) {
+ setStatus('auth-failed', err.message);
+ scheduleReconnect();
+ }
+ return;
+ }
+ if (stale()) return;
+ let ws;
+ try {
+ ws = await openSocket(credentials);
+ } catch (err) {
+ if (!stale()) {
+ setStatus('connect-failed', err.message);
+ scheduleReconnect();
+ }
+ return;
+ }
+ if (stale()) {
+ ws.close();
+ return;
+ }
+ attachConnection(ws);
+ reconnectDelay = backoffInitialMs;
+ setStatus('connected');
+ await Promise.all([
+ ITERM_NOTIFICATION.NEW_SESSION,
+ ITERM_NOTIFICATION.TERMINATE_SESSION,
+ ITERM_NOTIFICATION.LAYOUT_CHANGE,
+ ].map((notificationType) => request({ notificationRequest: { subscribe: true, notificationType } })));
+ await refreshSessions();
+ };
+
+ const teardown = (reason) => {
+ epoch += 1;
+ clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ clearTimeout(idleTimer);
+ idleTimer = null;
+ idleExpired = false;
+ reconnectDelay = backoffInitialMs;
+ const current = conn;
+ conn = null;
+ if (current) {
+ rejectPending(current, `iTerm2 bridge stopped (${reason})`);
+ try {
+ current.ws.close();
+ } catch (err) {
+ console.error(`❌ ${LOG_PREFIX}: close failed: ${err.message}`);
+ }
+ }
+ clearSessions();
+ setStatus('disconnected');
+ };
+
+ const armIdle = () => {
+ if (idleTimer) return;
+ idleTimer = setTimeout(() => {
+ idleTimer = null;
+ idleExpired = true;
+ reconcileItermBridge({ reason: 'idle' }).catch((err) => {
+ console.error(`❌ ${LOG_PREFIX}: idle reconcile failed: ${err.message}`);
+ });
+ }, idleMs);
+ };
+
+ const reconcileOnce = async (reason) => {
+ const enabled = await Promise.resolve()
+ .then(() => isFeatureEnabled())
+ .catch((err) => {
+ console.error(`❌ ${LOG_PREFIX}: feature check failed: ${err.message}`);
+ return false;
+ });
+ const active = Boolean(conn || reconnectTimer);
+ if (!enabled) {
+ if (active || sessions.size > 0) teardown(reason);
+ } else if (hasDemand()) {
+ clearTimeout(idleTimer);
+ idleTimer = null;
+ idleExpired = false;
+ if (!conn && !reconnectTimer) await connectOnce();
+ } else if (active) {
+ if (idleExpired) teardown(reason);
+ else armIdle();
+ }
+ return { enabled, connected: Boolean(conn), state: status.state };
+ };
+
+ /** Idempotent; serialized so overlapping triggers settle on the last answer. */
+ function reconcileItermBridge({ reason = 'unspecified' } = {}) {
+ const run = () => reconcileOnce(reason).catch((err) => {
+ console.error(`❌ ${LOG_PREFIX}: reconcile (${reason}) failed: ${err.message}`);
+ return { enabled: false, connected: Boolean(conn), state: status.state };
+ });
+ const next = tail.then(run, run);
+ tail = next.then(() => {}, () => {});
+ return next;
+ }
+
+ // --- public surface -----------------------------------------------------------
+
+ async function getItermStatus() {
+ if (conn) return { state: 'connected', detail: null };
+ const install = await detectInstall();
+ if (install.state !== 'ready') return { state: install.state, detail: null };
+ if (!await isRunning()) return { state: 'not-running', detail: null };
+ if (FAILURE_STATES.has(status.state)) return { ...status };
+ return { state: 'disconnected', detail: null };
+ }
+
+ const subscribeList = (socket) => {
+ listSubscribers.add(socket);
+ safeEmit(socket, 'iterm:sessions', { status: { ...status }, sessions: listItermSessions() });
+ return reconcileItermBridge({ reason: 'subscribe' });
+ };
+
+ const unsubscribeList = (socket) => {
+ listSubscribers.delete(socket);
+ return reconcileItermBridge({ reason: 'unsubscribe' });
+ };
+
+ const attachViewer = (id, socket) => {
+ const entry = sessions.get(id);
+ if (!entry) return null;
+ const first = entry.viewers.size === 0;
+ entry.viewers.add(socket);
+ if (first) {
+ subscribeScreen(entry, true).then(() => {
+ if (conn && sessions.get(id) === entry) fetchFrame(entry);
+ });
+ }
+ else if (!entry.lastFrame) fetchFrame(entry);
+ return { id, cols: entry.cols, rows: entry.rows, bufferedOutput: entry.lastFrame ?? '' };
+ };
+
+ const releaseViewer = (entry, socket) => {
+ if (!entry.viewers.delete(socket)) return false;
+ if (entry.viewers.size === 0 && sessions.get(entry.id) === entry) subscribeScreen(entry, false);
+ return true;
+ };
+
+ const detachViewer = (id, socket) => {
+ const entry = sessions.get(id);
+ const released = entry ? releaseViewer(entry, socket) : false;
+ reconcileItermBridge({ reason: 'detach' });
+ return released;
+ };
+
+ const detachSocket = (socket) => {
+ listSubscribers.delete(socket);
+ let released = 0;
+ for (const entry of sessions.values()) {
+ if (releaseViewer(entry, socket)) released += 1;
+ }
+ reconcileItermBridge({ reason: 'socket-disconnect' });
+ return released;
+ };
+
+ const sendInput = (id, data) => {
+ const entry = sessions.get(id);
+ if (!entry || !conn) return false;
+ // Per-session FIFO: each keystroke batch waits for the previous one's
+ // acknowledgement, so order survives however fast the viewer types.
+ entry.inputTail = entry.inputTail
+ .then(() => request({ sendTextRequest: { session: entry.uuid, text: data } }))
+ .catch((err) => console.error(`❌ ${LOG_PREFIX}: send text failed: ${err.message}`));
+ return true;
+ };
+
+ const shutdown = () => {
+ listSubscribers.clear();
+ teardown('shutdown');
+ };
+
+ return {
+ attachViewer,
+ detachSocket,
+ detachViewer,
+ getItermStatus,
+ listItermSessions,
+ reconcileItermBridge,
+ sendInput,
+ shutdown,
+ subscribeList,
+ unsubscribeList,
+ };
+}
+
+const bridge = createItermBridge();
+
+export const {
+ attachViewer: attachItermViewer,
+ detachSocket: detachItermSocket,
+ detachViewer: detachItermViewer,
+ getItermStatus,
+ listItermSessions,
+ reconcileItermBridge,
+ sendInput: sendItermInput,
+ subscribeList: subscribeItermList,
+ unsubscribeList: unsubscribeItermList,
+} = bridge;
diff --git a/server/services/itermBridge.test.js b/server/services/itermBridge.test.js
new file mode 100644
index 0000000000..9b29ccdee0
--- /dev/null
+++ b/server/services/itermBridge.test.js
@@ -0,0 +1,278 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createServer } from 'node:http';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { WebSocketServer } from 'ws';
+import {
+ ITERM_NOTIFICATION,
+ decodeItermClientMessage,
+ encodeItermServerMessage,
+} from '../lib/itermMessages.js';
+import { staticImportClosure } from '../lib/staticImportGraph.js';
+import { createItermBridge } from './itermBridge.js';
+
+// A fake iTerm2 API server speaking the same PortOS-authored schema over a
+// WebSocket on a temp Unix socket. Every fixture below is invented.
+
+const pane = (uuid, width = 80, height = 24) => ({
+ session: { uniqueIdentifier: uuid, gridSize: { width, height }, title: `title-${uuid}` },
+});
+const LAYOUT = {
+ windows: [
+ { windowId: 'win-a', tabs: [{ tabId: 'tab-1', root: { links: [pane('AAAA-1'), { node: { links: [pane('AAAA-2')] } }] } }] },
+ { windowId: 'win-b', tabs: [{ tabId: 'tab-2', root: { links: [pane('BBBB-1', 120, 40)] } }] },
+ ],
+};
+
+const startFakeIterm = async (socketPath) => {
+ const state = {
+ handshakes: [],
+ requests: [],
+ sockets: new Set(),
+ layout: LAYOUT,
+ onGetBuffer: null,
+ };
+ const httpServer = createServer();
+ const wss = new WebSocketServer({ server: httpServer, handleProtocols: (protocols) => (protocols.has('api.iterm2.com') ? 'api.iterm2.com' : false) });
+ const send = (ws, message) => ws.send(encodeItermServerMessage(message));
+ wss.on('connection', (ws, req) => {
+ state.handshakes.push({ headers: req.headers, protocol: ws.protocol });
+ state.sockets.add(ws);
+ ws.on('close', () => state.sockets.delete(ws));
+ ws.on('message', async (data) => {
+ const msg = decodeItermClientMessage(data);
+ state.requests.push(msg);
+ const reply = (body) => send(ws, { id: msg.id, ...body });
+ if (msg.listSessionsRequest) reply({ listSessionsResponse: state.layout });
+ else if (msg.notificationRequest) reply({ notificationResponse: { status: 0 } });
+ else if (msg.variableRequest) {
+ reply({ variableResponse: { status: 0, values: msg.variableRequest.get.map((name) => JSON.stringify(`${name}-${msg.variableRequest.sessionId}`)) } });
+ } else if (msg.sendTextRequest) reply({ sendTextResponse: { status: 0 } });
+ else if (msg.getBufferRequest) {
+ await state.onGetBuffer?.(ws, msg);
+ reply({
+ getBufferResponse: {
+ status: 0,
+ contents: [{ text: `screen of ${msg.getBufferRequest.session}` }, { text: '$ ' }],
+ cursor: { x: 2, y: 501 },
+ windowedCoordRange: { coordRange: { start: { x: 0, y: 500 }, end: { x: 0, y: 502 } } },
+ },
+ });
+ }
+ });
+ });
+ await new Promise((done) => httpServer.listen(socketPath, done));
+ state.notify = (notification) => {
+ for (const ws of state.sockets) send(ws, { notification });
+ };
+ state.dropAll = () => {
+ for (const ws of state.sockets) ws.terminate();
+ };
+ state.close = () => new Promise((done) => {
+ state.dropAll();
+ wss.close();
+ httpServer.close(() => done());
+ });
+ state.count = (key) => state.requests.filter((r) => r[key]).length;
+ return state;
+};
+
+const fakeSocket = (name) => {
+ const events = [];
+ return {
+ name,
+ events,
+ emit: (event, payload) => events.push([event, payload]),
+ last: (event) => events.filter(([e]) => e === event).at(-1)?.[1],
+ all: (event) => events.filter(([e]) => e === event).map(([, p]) => p),
+ };
+};
+
+describe('itermBridge', () => {
+ let dir;
+ let fake;
+ let bridge;
+ let deps;
+
+ beforeEach(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'it2-'));
+ const socketPath = join(dir, 's');
+ fake = await startFakeIterm(socketPath);
+ deps = {
+ socketPath,
+ enabled: true,
+ running: true,
+ auth: vi.fn(async () => ({ cookie: 'cookie-test', key: 'key-test' })),
+ isRunning: vi.fn(async () => deps.running),
+ detectInstall: vi.fn(async () => ({ state: 'ready' })),
+ isFeatureEnabled: vi.fn(async () => deps.enabled),
+ idleMs: 60,
+ backoffInitialMs: 20,
+ backoffMaxMs: 40,
+ libraryVersion: 'node portos-test',
+ };
+ bridge = createItermBridge(deps);
+ });
+
+ afterEach(async () => {
+ bridge.shutdown();
+ await fake.close();
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ const listAndConnect = async () => {
+ const socket = fakeSocket('lister');
+ await bridge.subscribeList(socket);
+ await vi.waitFor(() => expect(socket.last('iterm:sessions')?.sessions?.[0]?.jobName).toBeTruthy());
+ return socket;
+ };
+
+ it('makes no connection until a socket subscribes, then handshakes with every required header', async () => {
+ await bridge.reconcileItermBridge({ reason: 'boot' });
+ expect(deps.auth).not.toHaveBeenCalled();
+ expect(fake.handshakes).toHaveLength(0);
+
+ await listAndConnect();
+ expect(fake.handshakes).toHaveLength(1);
+ const { headers, protocol } = fake.handshakes[0];
+ expect(protocol).toBe('api.iterm2.com');
+ expect(headers).toMatchObject({
+ origin: 'ws://localhost/',
+ 'x-iterm2-library-version': 'node portos-test',
+ 'x-iterm2-disable-auth-ui': 'true',
+ 'x-iterm2-cookie': 'cookie-test',
+ 'x-iterm2-key': 'key-test',
+ 'x-iterm2-advisory-name': 'PortOS',
+ });
+ const types = fake.requests.filter((r) => r.notificationRequest && !r.notificationRequest.variableMonitorRequest)
+ .map((r) => r.notificationRequest.notificationType);
+ expect(types).toEqual(expect.arrayContaining([
+ ITERM_NOTIFICATION.NEW_SESSION, ITERM_NOTIFICATION.TERMINATE_SESSION, ITERM_NOTIFICATION.LAYOUT_CHANGE,
+ ]));
+ // Screen updates are NOT subscribed until someone views a session.
+ expect(types).not.toContain(ITERM_NOTIFICATION.SCREEN_UPDATE);
+ });
+
+ it('builds its own registry in window → tab → pane order', async () => {
+ const socket = await listAndConnect();
+ await vi.waitFor(() => expect(socket.last('iterm:sessions').sessions.every((s) => s.cwd)).toBe(true));
+ const { sessions, status } = socket.last('iterm:sessions');
+ expect(status.state).toBe('connected');
+ expect(sessions.map((s) => [s.id, s.windowIndex, s.tabIndex, s.paneIndex, s.paneCount])).toEqual([
+ ['iterm-AAAA-1', 1, 1, 1, 2],
+ ['iterm-AAAA-2', 1, 1, 2, 2],
+ ['iterm-BBBB-1', 2, 1, 1, 1],
+ ]);
+ expect(sessions[2]).toMatchObject({ cols: 120, rows: 40, label: 'name-BBBB-1', jobName: 'jobName-BBBB-1', cwd: 'path-BBBB-1' });
+ });
+
+ it('never reaches the PortOS shell registry or the Workspaces grouping', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const closure = staticImportClosure(resolve(here, 'itermBridge.js')).files;
+ expect(closure.has(resolve(here, 'shell.js'))).toBe(false);
+ expect(closure.has(resolve(here, 'workspaceContext.js'))).toBe(false);
+ });
+
+ it('subscribes screen updates on first view, streams a rendered frame, and unsubscribes on last detach', async () => {
+ await listAndConnect();
+ const viewerA = fakeSocket('a');
+ const viewerB = fakeSocket('b');
+ expect(bridge.attachViewer('iterm-AAAA-2', viewerA)).toMatchObject({ id: 'iterm-AAAA-2', cols: 80, rows: 24 });
+ await vi.waitFor(() => expect(viewerA.last('iterm:output')?.data).toContain('screen of AAAA-2'));
+ // Cursor y=501 with row 1 at absolute line 500 → screen row 2, col 3.
+ expect(viewerA.last('iterm:output').data).toContain('\x1b[2;3H');
+ const screenSubs = () => fake.requests.filter((r) => r.notificationRequest?.notificationType === ITERM_NOTIFICATION.SCREEN_UPDATE);
+ expect(screenSubs().map((r) => [r.notificationRequest.session, r.notificationRequest.subscribe])).toEqual([['AAAA-2', true]]);
+
+ // A second viewer gets the cached frame without a second subscription.
+ expect(bridge.attachViewer('iterm-AAAA-2', viewerB).bufferedOutput).toContain('screen of AAAA-2');
+ bridge.detachViewer('iterm-AAAA-2', viewerA);
+ expect(screenSubs()).toHaveLength(1);
+ bridge.detachViewer('iterm-AAAA-2', viewerB);
+ await vi.waitFor(() => expect(screenSubs().map((r) => r.notificationRequest.subscribe)).toEqual([true, false]));
+ });
+
+ it('coalesces a burst of screen updates to one in-flight fetch plus one trailing fetch', async () => {
+ await listAndConnect();
+ let first = true;
+ fake.onGetBuffer = () => {
+ if (!first) return;
+ first = false;
+ // Five updates land while the first fetch is still in flight.
+ for (let i = 0; i < 5; i += 1) fake.notify({ screenUpdateNotification: { session: 'AAAA-1' } });
+ };
+ const viewer = fakeSocket('v');
+ bridge.attachViewer('iterm-AAAA-1', viewer);
+ await vi.waitFor(() => expect(viewer.all('iterm:output')).toHaveLength(2));
+ await new Promise((done) => setTimeout(done, 50));
+ expect(fake.count('getBufferRequest')).toBe(2);
+ });
+
+ it('types byte-exact input in order', async () => {
+ await listAndConnect();
+ const inputs = ['l', 's', '\r', '\x1b[A', '\x03', '\x1b[200~line one\nline two\x1b[201~'];
+ for (const data of inputs) expect(bridge.sendInput('iterm-BBBB-1', data)).toBe(true);
+ await vi.waitFor(() => expect(fake.count('sendTextRequest')).toBe(inputs.length));
+ expect(fake.requests.filter((r) => r.sendTextRequest).map((r) => [r.sendTextRequest.session, r.sendTextRequest.text]))
+ .toEqual(inputs.map((text) => ['BBBB-1', text]));
+ expect(bridge.sendInput('iterm-missing', 'x')).toBe(false);
+ });
+
+ it('drops a terminated session and tells its viewers', async () => {
+ const socket = await listAndConnect();
+ const viewer = fakeSocket('v');
+ bridge.attachViewer('iterm-AAAA-1', viewer);
+ fake.notify({ terminateSessionNotification: { sessionId: 'AAAA-1' } });
+ await vi.waitFor(() => expect(viewer.last('iterm:exit')).toEqual({ id: 'iterm-AAAA-1' }));
+ expect(socket.last('iterm:sessions').sessions.map((s) => s.id)).toEqual(['iterm-AAAA-2', 'iterm-BBBB-1']);
+ });
+
+ it('clears the registry when iTerm2 goes away and reconnects without ever launching it', async () => {
+ const socket = await listAndConnect();
+ const viewer = fakeSocket('v');
+ bridge.attachViewer('iterm-AAAA-1', viewer);
+ expect(deps.auth).toHaveBeenCalledTimes(1);
+
+ // iTerm2 quits: the socket drops and the running check now says no.
+ deps.running = false;
+ fake.dropAll();
+ await vi.waitFor(() => expect(viewer.last('iterm:exit')).toEqual({ id: 'iterm-AAAA-1' }));
+ await vi.waitFor(() => expect(socket.last('iterm:sessions').status.state).toBe('not-running'));
+ expect(socket.last('iterm:sessions').sessions).toEqual([]);
+ expect(deps.auth).toHaveBeenCalledTimes(1); // no cookie request while not running
+
+ // iTerm2 relaunches: the backoff loop reconnects on its own.
+ deps.running = true;
+ await vi.waitFor(() => expect(socket.last('iterm:sessions').status.state).toBe('connected'));
+ expect(deps.auth).toHaveBeenCalledTimes(2);
+ expect(fake.handshakes).toHaveLength(2);
+ });
+
+ it('reports a static install problem without probing iTerm2 at all', async () => {
+ deps.detectInstall.mockResolvedValue({ state: 'api-disabled' });
+ const socket = fakeSocket('lister');
+ await bridge.subscribeList(socket);
+ expect(socket.last('iterm:sessions').status.state).toBe('api-disabled');
+ expect(deps.isRunning).not.toHaveBeenCalled();
+ expect(deps.auth).not.toHaveBeenCalled();
+ expect(await bridge.getItermStatus()).toEqual({ state: 'api-disabled', detail: null });
+ });
+
+ it('disconnects immediately when the feature turns off', async () => {
+ const socket = await listAndConnect();
+ deps.enabled = false;
+ await bridge.reconcileItermBridge({ reason: 'feature-toggle' });
+ expect(socket.last('iterm:sessions')).toMatchObject({ status: { state: 'disconnected' }, sessions: [] });
+ await vi.waitFor(() => expect(fake.sockets.size).toBe(0));
+ });
+
+ it('disconnects after the idle window once the last subscriber leaves', async () => {
+ const socket = await listAndConnect();
+ await bridge.unsubscribeList(socket);
+ expect(fake.sockets.size).toBe(1); // still inside the idle window
+ await vi.waitFor(() => expect(fake.sockets.size).toBe(0));
+ expect(await bridge.getItermStatus()).toEqual({ state: 'disconnected', detail: null });
+ });
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index 25c22c3487..f416c4c83e 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -38,6 +38,7 @@ import { registerAppHandlers } from '../sockets/apps.js';
import { registerFableLoomHostedNamespace } from '../sockets/fableLoomHosted.js';
import { cleanupSocketStreams, registerLogHandlers } from '../sockets/logs.js';
import { detachShellSocket, registerShellHandlers } from '../sockets/shell.js';
+import { detachItermSocket, registerItermHandlers } from '../sockets/iterm.js';
import { getBuildId } from '../lib/buildId.js';
import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';
import { runEventLogEvents } from './agentRunEventLog.js';
@@ -169,6 +170,7 @@ function registerLifecycleHandlers(socket, _io) {
if (detached > 0) {
console.log(`🐚 Detached ${detached} shell session(s) (still running)`);
}
+ detachItermSocket(socket);
socket.removeAllListeners();
});
}
@@ -183,6 +185,7 @@ const SOCKET_HANDLER_REGISTRARS = [
registerSubscriptionHandlers,
registerErrorHandlers,
registerShellHandlers,
+ registerItermHandlers,
registerLifecycleHandlers
];
diff --git a/server/sockets/iterm.js b/server/sockets/iterm.js
new file mode 100644
index 0000000000..8d4173b7b3
--- /dev/null
+++ b/server/sockets/iterm.js
@@ -0,0 +1,46 @@
+// Socket events for the Shell page's iTerm2 view (#8114). A namespace of its
+// own (`iterm:*`), backed by services/itermBridge.js — never the PortOS shell
+// registry — so iTerm2 sessions cannot leak into the PortOS tab strip,
+// Workspaces, or agent-run lookups. There is deliberately no resize, start,
+// stop or restart event: iTerm2 owns its sessions' size and lifecycle.
+
+import * as itermBridge from '../services/itermBridge.js';
+import { itermInputSchema, itermSessionRefSchema, validateSocketData } from '../lib/socketValidation.js';
+
+const logRejection = (event) => (err) => {
+ console.error(`❌ Socket handler error [${event}]: ${err?.message ?? err}`);
+};
+
+export const detachItermSocket = (socket) => itermBridge.detachItermSocket(socket);
+
+export const registerItermHandlers = (socket) => {
+ socket.on('iterm:list', () => {
+ itermBridge.subscribeItermList(socket).catch(logRejection('iterm:list'));
+ });
+
+ socket.on('iterm:unlist', () => {
+ itermBridge.unsubscribeItermList(socket).catch(logRejection('iterm:unlist'));
+ });
+
+ socket.on('iterm:attach', (rawData) => {
+ const validated = validateSocketData(itermSessionRefSchema, rawData, socket, 'iterm:attach');
+ if (!validated) return;
+ const attached = itermBridge.attachItermViewer(validated.id, socket);
+ if (attached) socket.emit('iterm:attached', attached);
+ else socket.emit('iterm:error', { id: validated.id, error: 'iTerm2 session not found' });
+ });
+
+ socket.on('iterm:detach', (rawData) => {
+ const validated = validateSocketData(itermSessionRefSchema, rawData, socket, 'iterm:detach');
+ if (!validated) return;
+ itermBridge.detachItermViewer(validated.id, socket);
+ });
+
+ socket.on('iterm:input', (rawData) => {
+ const validated = validateSocketData(itermInputSchema, rawData, socket, 'iterm:input');
+ if (!validated) return;
+ if (!itermBridge.sendItermInput(validated.id, validated.data)) {
+ socket.emit('iterm:error', { id: validated.id, error: 'iTerm2 session not found' });
+ }
+ });
+};