# Integrated terminal and Claude Code launch

1. **xterm.js** or `terminal_use`, by worker ticket
2. preload allowlist, or desktop host
3. **Electron main**
4. **node-pty** login shell or claude

Desktop only. The Web UI exposes no host command execution.

## What was chosen

| Piece | Role |
| --- | --- |
| [node-pty](https://github.com/microsoft/node-pty) | Real PTY in Electron main only (ConPTY on Windows) |
| [xterm.js](https://xtermjs.org/docs/) + FitAddon | Terminal sequences, raw input, cols/rows per pane; no custom protocol |
| [Claude Code CLI](https://code.claude.com/docs/en/overview) | The locally installed `claude`, PATH resolved through a login shell |
| spawn + pipe (not used) | `TERM=dumb`, no terminal device: interactive programs lose cursor, redraw, colors, shortcuts, resize |

## Behaviour

| Topic | Behaviour |
| --- | --- |
| Terminal tab | Login shell (zsh or bash on macOS, PowerShell on Windows) in the project directory. Switching tabs unmounts only the view; closing the tab, destroying the renderer or Stop releases the PTY. |
| Claude Code tab | Runs `claude` directly in the same directory. |
| Project not resolved | After a brief wait the shell starts in home instead of a blank page. A late answer does not restart it. |
| Unavailable | Bridge, PTY module or CLI missing: the tab shows an explicit error. Web mode has no interactive controls. |
| Theme | Background, foreground, cursor, selection and ANSI 16 come from semantic tokens. Theme or Custom CSS changes update xterm only, keeping PTY and buffer. |
| Toolbar | Preset, process state, actual cwd; copy, paste, clear, restart, stop. Compact, borderless. |
| Keys | `Cmd+C` or `Ctrl+Shift+C` copies when a selection exists. `Cmd+V` or `Ctrl+Shift+V` pastes into the PTY. `Ctrl+C` interrupts. `Cmd+K` clears the current viewport only. |

## Shared with the agent

`terminal_use` actions: `list`, `open`, `observe`, `input`, `interrupt`, `resize`, `share`, `release`, `close`. Each runs on a single-use ticket issued by `openprogram/host/resources/terminal.py` and redeemed by the desktop host.

- Needs approval; unsafe in plan mode; cannot bypass a task sandbox. No Desktop: an explicit unavailable result.
- Input is raw keystrokes, not a command API. "Delivered" means reached the shell. Output is untrusted data.
- Human typing does not pause the agent, but a changed input revision forces a new `observe`. Uncertain input is never retried.
- `release` leaves the terminal open; `close` terminates the shell.

## Trust boundaries

| Boundary | Rule |
| --- | --- |
| Executable | The renderer picks only preset `shell` or `claude`; no arbitrary argv. |
| `cwd` | Realpath, must be a directory. The PTY is bound to the renderer sender and terminal id. |
| Limits | Agent input 16 KiB; human 64 KiB; cols 20–500, rows 5–200 from the tool. Replaced processes cannot emit into the new one. |
| Privileges | The local App user's. No remote sandbox. |

## Shell directory and foreground command

Advisory, for macOS zsh and compatible bash 3.2 login shells. Exit zero proves no effect or task success; background jobs may continue. Reports never change ownership, leases, approval, input revisions or cancellation.

```
shell_integration?: {
  status: "starting" | "ready" | "unavailable" | "ended",
  mode: "zsh-hooks" | "bash-debug" | null,
  reason: string | null, event_sequence: number,
  cwd: { value: string, event_sequence: number } | null,
  cycle: { id: number, phase: "running" | "finished" | "unknown",
           exit_code: number | null } | null
}
```

**Metadata semantics**

- Optional on existing reads and events; older hosts omit it. `start_cwd` is immutable. Top-level `exit_code` is the PTY process, nested the matched cycle.
- Initial prompt: ready and cwd, `cycle=null`. Process exit: unfinished cycle becomes unknown, integration ends. Last values are history, not guarantees. Input still returns `phase=delivered` or unconfirmed with `command_complete=null`.
- The Web type accepts the metadata with no renderer, prompt parser, command API or store.

**Startup and compatibility**

| Shell | Integration |
| --- | --- |
| zsh | Native `-l`. Private `.zshenv`, `.zprofile`, `.zshrc`, `.zlogin` forwarders restore `ZDOTDIR` before sourcing each user file, then append preexec/precmd hooks. `RCS` stays authoritative. Existing hooks remain; readonly arrays decline. Global scripts and plugins are not claimed equivalent. |
| bash | Native `-l`, one-time `PROMPT_COMMAND` only if none was set. Bootstrap captures DEBUG before sourcing and installs a minimal DEBUG/prompt pair. Custom DEBUG, readonly `PROMPT_COMMAND`, extdebug, functrace, replaced prompts and bash-preexec get none. Root-parent PID checks stop nested adoption; callbacks reject subshell reports. |
| Others | Usable, reports unavailable. No user config, shell option or history policy is rewritten. No Windows integration. |

**Protocol and lifetime**

```
ESC ] 777 ; OpenProgram ; 1 ; nonce ; rootPid ; eventSequence ; kind ; cycleId ; exitStatus ; cwdHex BEL
```

- Kinds: ready, cwd, start, end. 128-bit nonce per launch. The parser checks the PTY PID, increasing event sequence and cycle, matching completion.
- cwd: UTF-8 absolute, hex by printf/od/tr, 16 KiB limit, no NUL or malformed UTF-8. Frames 36 KB.
- Incremental across chunks; incomplete candidates released after one second. Only accepted frames are removed before delivery and replay; other output is unchanged and cursors count the same filtered stream.
- A later complete prefix before the candidate's BEL keeps the earlier bytes as output and restarts at the new prefix, so malformed output cannot swallow a genuine completion.
- The shell can read or forge its nonce, so metadata grants no authority. No command text or environment dump. Three seconds without ready: unavailable; a later valid handshake recovers. Root exit makes a running cycle unknown, never finished.
- Scripts are extracted through Electron fs to a per-launch 0700 directory with 0600 files; spawn failure or root exit removes them, reattach or lease release does not. Old-generation data cannot update replacements. Asset failure keeps the raw terminal.

`apps/desktop/main/terminal/`: `terminal-shell-protocol.js`, `terminal-shell-integration.js`, `shell-integration/`, `terminal-resource-manager.js`, `terminal-resource-ipc.js`. `apps/web/lib/desktop/terminal-resources.ts` adds the type. `package.json` packs `main/**`, dotfiles included. Checks: `check-shell-metadata.cjs` (manager and parser), `check-shell-pty.cjs` (real macOS PTY through production IPC).

## Scope

Outside it: remote cloud sessions, a general terminal-session manager, shell-profile editors, persistent command history, a Web host terminal. Other tabs are unaffected.

**Implementation status and acceptance**

| Part | Status |
| --- | --- |
| PTY terminals, launcher, theme, toolbar, keys | Implemented on macOS and Windows. |
| `terminal_use` | Implemented; redeemed in `terminal-resource-ipc.js`. |
| Shell observation | Implemented in source; installed-App acceptance pending. Arbitrary global profiles and dynamically replaced hooks unverified. |

1. Terminal runs `pwd`; cwd is the current project, or home after the brief wait.
2. Claude Code shows the local CLI; input and Ctrl+C reach it; closing it does not affect Terminal.
3. Pane width changes sync xterm and PTY cols/rows.
4. PTY pid stays across tab switches and theme changes; ANSI 16 follows dark, light, warm and custom themes.
5. Copy, paste, clear, restart, stop work; toolbar shows running, exited, error.
