diff --git a/src/cmux/commands/profiles/delete.ts b/src/cmux/commands/profiles/delete.ts new file mode 100644 index 0000000000..7b58bc5721 --- /dev/null +++ b/src/cmux/commands/profiles/delete.ts @@ -0,0 +1,48 @@ +import { ProfileNotFoundError, ProfileStore } from "@app/cmux/lib/store"; +import { isInteractive, suggestCommand } from "@app/utils/cli"; +import { withCancel } from "@app/utils/prompts/clack/helpers"; +import * as p from "@clack/prompts"; +import type { Command } from "commander"; +import pc from "picocolors"; + +export function registerDeleteCommand(parent: Command): void { + parent + .command("delete ") + .alias("rm") + .description("Remove a saved profile") + .option("-y, --yes", "Skip the confirmation prompt") + .action(async (name: string, flags: { yes?: boolean }) => { + const store = new ProfileStore(); + try { + const summary = store.summarize(store.read(name)); + if (!flags.yes) { + if (!isInteractive()) { + console.error( + `Refusing to delete in non-interactive mode without --yes. ${suggestCommand(`tools cmux profiles delete ${name} --yes`)}` + ); + process.exitCode = 1; + return; + } + const confirmed = await withCancel( + p.confirm({ + message: `Delete profile "${name}" (${summary.workspaces} workspace(s))?`, + initialValue: false, + }) + ); + if (!confirmed) { + p.cancel("Aborted."); + return; + } + } + store.delete(name); + console.log(`${pc.green("✓")} Deleted profile "${name}".`); + } catch (error) { + if (error instanceof ProfileNotFoundError) { + console.error(error.message); + process.exitCode = 1; + return; + } + throw error; + } + }); +} diff --git a/src/cmux/commands/profiles/edit.ts b/src/cmux/commands/profiles/edit.ts new file mode 100644 index 0000000000..2ac7c09d4a --- /dev/null +++ b/src/cmux/commands/profiles/edit.ts @@ -0,0 +1,45 @@ +import { existsSync } from "node:fs"; +import { ProfileNotFoundError, ProfileStore } from "@app/cmux/lib/store"; +import type { Command } from "commander"; + +export function registerEditCommand(parent: Command): void { + parent + .command("edit ") + .description("Open the profile JSON in $VISUAL or $EDITOR") + .action(async (name: string) => { + try { + const store = new ProfileStore(); + const path = store.pathFor(name); + if (!existsSync(path)) { + throw new ProfileNotFoundError(name, path); + } + + const editor = pickEditor(); + const proc = Bun.spawn([editor.bin, ...editor.args, path], { + stdio: ["inherit", "inherit", "inherit"], + }); + const exitCode = await proc.exited; + if (exitCode !== 0) { + throw new Error(`${editor.bin} exited with code ${exitCode}`); + } + } catch (error) { + if (error instanceof ProfileNotFoundError) { + console.error(error.message); + process.exitCode = 1; + return; + } + throw error; + } + }); +} + +function pickEditor(): { bin: string; args: string[] } { + const fromEnv = process.env.VISUAL || process.env.EDITOR; + if (fromEnv) { + const parts = fromEnv.split(/\s+/).filter(Boolean); + if (parts.length > 0) { + return { bin: parts[0], args: parts.slice(1) }; + } + } + return { bin: "vi", args: [] }; +} diff --git a/src/cmux/commands/profiles/index.ts b/src/cmux/commands/profiles/index.ts new file mode 100644 index 0000000000..f6a7c26fc4 --- /dev/null +++ b/src/cmux/commands/profiles/index.ts @@ -0,0 +1,22 @@ +import type { Command } from "commander"; +import { registerDeleteCommand } from "@app/cmux/commands/profiles/delete"; +import { registerEditCommand } from "@app/cmux/commands/profiles/edit"; +import { registerListCommand } from "@app/cmux/commands/profiles/list"; +import { registerPathCommand } from "@app/cmux/commands/profiles/path"; +import { registerRestoreCommand } from "@app/cmux/commands/profiles/restore"; +import { registerSaveCommand } from "@app/cmux/commands/profiles/save"; +import { registerViewCommand } from "@app/cmux/commands/profiles/view"; + +export function registerProfilesCommand(program: Command): void { + const profiles = program + .command("profiles") + .description("Manage saved cmux workspace profiles"); + + registerSaveCommand(profiles); + registerListCommand(profiles); + registerViewCommand(profiles); + registerRestoreCommand(profiles); + registerEditCommand(profiles); + registerDeleteCommand(profiles); + registerPathCommand(profiles); +} diff --git a/src/cmux/commands/profiles/list.ts b/src/cmux/commands/profiles/list.ts new file mode 100644 index 0000000000..3be4add48e --- /dev/null +++ b/src/cmux/commands/profiles/list.ts @@ -0,0 +1,25 @@ +import { Command } from "commander"; +import pc from "picocolors"; +import { renderProfileList } from "@app/cmux/lib/format"; +import { ProfileStore } from "@app/cmux/lib/store"; + +export function registerListCommand(parent: Command): void { + parent + .command("list") + .alias("ls") + .description("List saved cmux profiles") + .option("--json", "Emit JSON instead of the rendered table") + .action((opts: { json?: boolean }) => { + const store = new ProfileStore(); + const summaries = store.list(); + if (opts.json) { + console.log(JSON.stringify(summaries, null, 2)); + return; + } + console.log(renderProfileList(summaries)); + if (summaries.length > 0) { + console.log(""); + console.log(pc.dim(`profiles dir: ${store.getProfilesDir()}`)); + } + }); +} diff --git a/src/cmux/commands/profiles/path.ts b/src/cmux/commands/profiles/path.ts new file mode 100644 index 0000000000..4e1ed0887f --- /dev/null +++ b/src/cmux/commands/profiles/path.ts @@ -0,0 +1,16 @@ +import { Command } from "commander"; +import { ProfileStore } from "@app/cmux/lib/store"; + +export function registerPathCommand(parent: Command): void { + parent + .command("path [name]") + .description("Print the absolute path of a profile (or the profiles directory if no name)") + .action((name: string | undefined) => { + const store = new ProfileStore(); + if (!name) { + console.log(store.getProfilesDir()); + return; + } + console.log(store.pathFor(name)); + }); +} diff --git a/src/cmux/commands/profiles/restore.ts b/src/cmux/commands/profiles/restore.ts new file mode 100644 index 0000000000..440e25cd6e --- /dev/null +++ b/src/cmux/commands/profiles/restore.ts @@ -0,0 +1,110 @@ +import { buildPlan, type RestoreOptions, restoreProfile } from "@app/cmux/lib/restore"; +import { ProfileNotFoundError, ProfileStore } from "@app/cmux/lib/store"; +import type { Profile } from "@app/cmux/lib/types"; +import logger from "@app/logger"; +import { isInteractive, suggestCommand } from "@app/utils/cli"; +import { withCancel } from "@app/utils/prompts/clack/helpers"; +import * as p from "@clack/prompts"; +import type { Command } from "commander"; +import pc from "picocolors"; + +interface RestoreFlags { + prefix?: string; + replay?: boolean; + yes?: boolean; + dryRun?: boolean; +} + +export function registerRestoreCommand(parent: Command): void { + parent + .command("restore ") + .description("Recreate cmux workspaces from a saved profile (always non-destructive)") + .option("--prefix ", "Workspace name prefix to apply on restore (default '-')") + .option("--no-replay", "Skip queueing the captured shell command — only cd into cwd") + .option("-y, --yes", "Do not ask for confirmation") + .option("--dry-run", "Print the plan without modifying cmux") + .action(async (name: string, flags: RestoreFlags) => { + await runRestore(name, flags); + }); +} + +async function runRestore(name: string, flags: RestoreFlags): Promise { + const store = new ProfileStore(); + let profile: Profile; + try { + profile = store.read(name); + } catch (error) { + if (error instanceof ProfileNotFoundError) { + console.error(error.message); + process.exitCode = 1; + return; + } + throw error; + } + + const opts: RestoreOptions = { + prefix: flags.prefix !== undefined ? flags.prefix : `${name}-`, + replay: flags.replay !== false, + yes: !!flags.yes, + dryRun: !!flags.dryRun, + }; + + const plan = buildPlan(profile, opts); + + p.intro(pc.bgCyan(pc.black(" cmux profiles restore "))); + const planLines = plan.workspaces.map((ws) => { + return ` ${pc.cyan(ws.targetTitle)} ${pc.dim(`(${ws.paneCount} pane(s), ${ws.surfaceCount} surface(s))`)}`; + }); + p.note(planLines.join("\n") || "(empty profile)", `Restore plan for ${pc.cyan(name)}`); + + if (opts.dryRun) { + p.outro(pc.dim("Dry run — nothing changed.")); + return; + } + + if (!opts.yes) { + if (!isInteractive()) { + console.error( + `Pass --yes to skip the confirmation in non-interactive mode. ${suggestCommand(`tools cmux profiles restore ${name} --yes`)}` + ); + process.exitCode = 1; + return; + } + const proceed = await withCancel( + p.confirm({ message: `Create ${plan.workspaces.length} workspace(s)?`, initialValue: true }) + ); + if (!proceed) { + p.cancel("Aborted."); + return; + } + } + + const spinner = p.spinner(); + spinner.start("Recreating workspaces…"); + const startedAt = Date.now(); + + try { + const outcome = await restoreProfile(profile, opts, { + onWorkspaceStart: ({ title, index, total }) => { + spinner.message(`Restoring ${index}/${total}: ${title}`); + }, + }); + spinner.stop(`Restored ${outcome.workspaces.length} workspace(s) in ${Date.now() - startedAt} ms`); + + const summary = outcome.workspaces + .map((w) => { + const status = w.converged ? pc.green("✓") : pc.yellow("≈"); + const dimensionNote = w.converged + ? "exact size match" + : `off by ${w.maxCellDelta} cell${w.maxCellDelta === 1 ? "" : "s"}`; + return ` ${status} ${pc.cyan(w.title)} ${pc.dim(`(${dimensionNote})`)}`; + }) + .join("\n"); + p.note(summary, "Result"); + p.outro(pc.green("Done.")); + } catch (error) { + spinner.stop("Restore failed."); + logger.error({ error }, "[cmux restore] failed"); + throw error; + } +} diff --git a/src/cmux/commands/profiles/save.ts b/src/cmux/commands/profiles/save.ts new file mode 100644 index 0000000000..dc19598a4e --- /dev/null +++ b/src/cmux/commands/profiles/save.ts @@ -0,0 +1,291 @@ +import { captureProfile, getCmuxVersion, type SnapshotOptions } from "@app/cmux/lib/snapshot"; +import { ProfileExistsError, ProfileStore } from "@app/cmux/lib/store"; +import type { ProfileScope, Window } from "@app/cmux/lib/types"; +import logger from "@app/logger"; +import { isInteractive, suggestCommand } from "@app/utils/cli"; +import { withCancel } from "@app/utils/prompts/clack/helpers"; +import * as p from "@clack/prompts"; +import type { Command } from "commander"; +import pc from "picocolors"; + +interface SaveFlags { + scope?: string; + workspace?: string; + window?: string; + cwd?: boolean; + screen?: boolean; + history?: boolean; + note?: string; + force?: boolean; +} + +export function registerSaveCommand(parent: Command): void { + parent + .command("save [name]") + .description("Capture a cmux layout into a named profile (~/.genesis-tools/cmux/profiles/)") + .option("-s, --scope ", "all | window | workspace") + .option("--workspace ", "Target workspace (only with --scope workspace)") + .option("--window ", "Target window (only with --scope window)") + .option("--no-cwd", "Skip per-pane cwd capture") + .option( + "--no-screen", + "Skip per-pane visible-screen capture (default on: each terminal pane's rendered content is captured so restore can paint it back)", + ) + .option( + "--no-history", + "Skip per-pane last-shell-command capture (default on: scrollback is parsed for the most recent shell prompt+command, e.g. `claude --resume `, and that command is pre-typed at the new prompt on restore)", + ) + .option("--note ", "Free-form note stored on the profile") + .option("-f, --force", "Overwrite an existing profile of the same name") + .action(async (name: string | undefined, flags: SaveFlags) => { + await runSave(name, flags); + }); +} + +async function runSave(rawName: string | undefined, flags: SaveFlags): Promise { + const interactive = isInteractive(); + let forceWrite = !!flags.force; + + const scope = await resolveScope(flags, interactive); + rejectIncompatibleScopeFlags(scope, flags); + const { captureCwd, captureScreen, captureHistory } = await resolveCaptureFlags(flags, interactive); + const name = await resolveName(rawName, scope, interactive); + + const store = new ProfileStore(); + if (store.exists(name) && !forceWrite) { + if (!interactive) { + console.error(`Profile "${name}" already exists. Use --force to overwrite.`); + console.error(suggestCommand("tools cmux profiles save", { add: ["--force"] })); + process.exitCode = 1; + return; + } + const overwrite = await withCancel( + p.confirm({ message: `Profile "${name}" exists. Overwrite?`, initialValue: false }) + ); + if (!overwrite) { + p.cancel("Save aborted."); + return; + } + forceWrite = true; + } + + p.intro(pc.bgCyan(pc.black(" cmux profiles save "))); + + const cmuxVersion = await getCmuxVersion(); + + const options: SnapshotOptions = { + name, + scope, + targetWindowRef: flags.window, + targetWorkspaceRef: flags.workspace, + captureCwd, + captureScreen, + captureHistory, + note: flags.note, + cmuxVersion, + }; + + const spinner = p.spinner(); + spinner.start("Capturing cmux state…"); + const startedAt = Date.now(); + + try { + const profile = await captureProfile(options, { + onWorkspaceStart: ({ title, index, total }) => { + spinner.message(`Capturing workspace ${index}/${total}: ${title}`); + }, + }); + + const path = store.write(name, profile, { force: forceWrite }); + spinner.stop(`Captured ${countWorkspaces(profile.windows)} workspace(s) in ${Date.now() - startedAt} ms`); + + const summary = store.summarize(profile); + const lines = [ + `${pc.bold("name:")} ${pc.cyan(summary.name)}`, + `${pc.bold("scope:")} ${summary.scope}`, + `${pc.bold("counts:")} ${summary.windows} window(s) · ${summary.workspaces} workspace(s) · ${summary.panes} pane(s) · ${summary.surfaces} surface(s)`, + `${pc.bold("file:")} ${pc.dim(path)}`, + ]; + if (summary.note) { + lines.push(`${pc.bold("note:")} ${summary.note}`); + } + p.note(lines.join("\n"), "Profile saved"); + + const restoreHint = `tools cmux profiles restore ${name}`; + p.outro(`Restore later with ${pc.cyan(restoreHint)}`); + } catch (error) { + spinner.stop("Capture failed."); + if (error instanceof ProfileExistsError) { + p.cancel(error.message); + process.exitCode = 1; + return; + } + logger.error({ error }, "[cmux save] failed"); + throw error; + } +} + +async function resolveScope(flags: SaveFlags, interactive: boolean): Promise { + if (flags.scope) { + if (flags.scope !== "all" && flags.scope !== "window" && flags.scope !== "workspace") { + throw new Error(`--scope must be one of all|window|workspace, got ${flags.scope}`); + } + return flags.scope; + } + if (!interactive) { + console.error("Non-interactive mode requires --scope ."); + console.error(suggestCommand("tools cmux profiles save", { add: ["--scope", "all"] })); + process.exit(1); + } + const choice = await withCancel( + p.select({ + message: "What should be saved?", + options: [ + { value: "all", label: "All windows", hint: "every window, every workspace" }, + { value: "window", label: "Current window", hint: "all workspaces in this window" }, + { value: "workspace", label: "Current workspace only", hint: "just the focused workspace" }, + ], + initialValue: "all", + }) + ); + return choice; +} + +interface CaptureFlags { + captureCwd: boolean; + captureScreen: boolean; + captureHistory: boolean; +} + +/** + * After scope is picked, ask which per-pane data to capture: cwd, visible screen, + * last shell command. CLI flags (`--no-cwd`/`--no-screen`/`--no-history`) win — they + * skip the prompt and force-include in non-interactive mode. Otherwise default-on, + * displayed as a multiselect so the user can deselect what they don't want. + */ +async function resolveCaptureFlags(flags: SaveFlags, interactive: boolean): Promise { + const flagOverrides: CaptureFlags = { + captureCwd: flags.cwd !== false, + captureScreen: flags.screen !== false, + captureHistory: flags.history !== false, + }; + const anyExplicitlyDisabled = flags.cwd === false || flags.screen === false || flags.history === false; + if (!interactive || anyExplicitlyDisabled) { + return flagOverrides; + } + + type CaptureKey = "cwd" | "screen" | "history"; + const initial: CaptureKey[] = []; + if (flagOverrides.captureCwd) { + initial.push("cwd"); + } + if (flagOverrides.captureScreen) { + initial.push("screen"); + } + if (flagOverrides.captureHistory) { + initial.push("history"); + } + + const picked = await withCancel( + p.multiselect({ + message: "What should be captured per pane?", + options: [ + { + value: "cwd", + label: "Working directory", + hint: "from each pane's tab title — replays as `cd ` on restore", + }, + { + value: "screen", + label: "Visible screen contents", + hint: "the saved scrollback is printed back into the new pane (monochrome)", + }, + { + value: "history", + label: "Last shell command", + hint: "pre-typed (NOT auto-executed) at the new prompt — e.g. `claude --resume `", + }, + ], + initialValues: initial, + required: false, + }) + ); + + const set = new Set(picked); + return { + captureCwd: set.has("cwd"), + captureScreen: set.has("screen"), + captureHistory: set.has("history"), + }; +} + +const NAME_PATTERN = /^[A-Za-z0-9._-]+$/; + +function validateProfileName(input: string): string { + const value = input.trim(); + if (!value) { + throw new Error("Profile name cannot be empty"); + } + if (!NAME_PATTERN.test(value)) { + throw new Error("Profile name must only contain letters, digits, dots, underscores, or dashes"); + } + return value; +} + +async function resolveName(rawName: string | undefined, scope: ProfileScope, interactive: boolean): Promise { + if (rawName) { + return validateProfileName(rawName); + } + if (!interactive) { + console.error("Profile name required as the first positional argument in non-interactive mode."); + console.error(suggestCommand("tools cmux profiles save", { add: [""] })); + process.exit(1); + } + const value = await withCancel( + p.text({ + message: "Profile name", + placeholder: defaultName(scope), + defaultValue: defaultName(scope), + validate: (input) => { + if (!input || !input.trim()) { + return "Name cannot be empty"; + } + if (!NAME_PATTERN.test(input)) { + return "Use letters, digits, dots, underscores, or dashes only"; + } + return undefined; + }, + }) + ); + return validateProfileName(value); +} + +function rejectIncompatibleScopeFlags(scope: ProfileScope, flags: SaveFlags): void { + if (flags.window && flags.workspace) { + throw new Error("Use only one of --window or --workspace, not both"); + } + if (flags.window && scope !== "window") { + throw new Error("--window requires --scope window"); + } + if (flags.workspace && scope !== "workspace") { + throw new Error("--workspace requires --scope workspace"); + } +} + +function defaultName(scope: ProfileScope): string { + if (scope === "all") { + return "all"; + } + if (scope === "window") { + return "window"; + } + return "workspace"; +} + +function countWorkspaces(windows: Window[]): number { + let total = 0; + for (const window of windows) { + total += window.workspaces.length; + } + return total; +} diff --git a/src/cmux/commands/profiles/view.ts b/src/cmux/commands/profiles/view.ts new file mode 100644 index 0000000000..3ab863c760 --- /dev/null +++ b/src/cmux/commands/profiles/view.ts @@ -0,0 +1,29 @@ +import { Command } from "commander"; +import { renderProfileTree } from "@app/cmux/lib/format"; +import { ProfileNotFoundError, ProfileStore } from "@app/cmux/lib/store"; + +export function registerViewCommand(parent: Command): void { + parent + .command("view ") + .alias("show") + .description("Show a saved profile as a rich tree") + .option("--json", "Emit the raw profile JSON") + .action((name: string, opts: { json?: boolean }) => { + const store = new ProfileStore(); + try { + const profile = store.read(name); + if (opts.json) { + console.log(JSON.stringify(profile, null, 2)); + return; + } + console.log(renderProfileTree(profile)); + } catch (error) { + if (error instanceof ProfileNotFoundError) { + console.error(error.message); + process.exitCode = 1; + return; + } + throw error; + } + }); +} diff --git a/src/cmux/docs/Cmux.md b/src/cmux/docs/Cmux.md new file mode 100644 index 0000000000..6c868ef264 --- /dev/null +++ b/src/cmux/docs/Cmux.md @@ -0,0 +1,574 @@ +# cmux Reference for `tools cmux` + +Comprehensive reference for every cmux CLI command and JSON-RPC method this tool relies on. Verified against **cmux 0.63.2 (build 79, commit `179b16ce6`)** on macOS. + +> **Naming.** "cmux" here means [github.com/manaflow-ai/cmux](https://github.com/manaflow-ai/cmux), the AI-native macOS terminal multiplexer (NOT `soheilhy/cmux`, NOT `coder/cmux`). + +--- + +## Table of contents + +1. [Architecture in 60 seconds](#architecture-in-60-seconds) +2. [Two ways in: CLI vs raw socket](#two-ways-in-cli-vs-raw-socket) +3. [Refs, IDs, indices](#refs-ids-indices) +4. [Discovery and identification](#discovery-and-identification) +5. [Windows](#windows) +6. [Workspaces](#workspaces) +7. [Panes](#panes) +8. [Surfaces (tabs)](#surfaces-tabs) +9. [Geometry](#geometry) +10. [Sending input](#sending-input) +11. [Browser surfaces](#browser-surfaces) +12. [Sidebar status / progress / log / notifications](#sidebar-status--progress--log--notifications) +13. [Known sharp edges & cmux 0.63.2 quirks](#known-sharp-edges--cmux-0632-quirks) +14. [What `tools cmux profiles ...` actually does](#what-tools-cmux-profiles--actually-does) + +--- + +## Architecture in 60 seconds + +```text +window ─┬─ workspace ─┬─ pane ─┬─ surface (terminal | browser) + │ │ └─ surface + │ └─ pane ─── surface + └─ workspace ─── pane ─── surface +``` + +- **window** — a macOS window. Contains 1+ workspaces (tabs along the top). +- **workspace** — what the user sees as a "tab" / "project". Contains a 2-D layout of panes. +- **pane** — a rectangular slot in the workspace. Created by splitting another pane. +- **surface** — the contents of a pane. A pane can hold multiple surfaces; only one is active at a time (think tmux window-tabs inside a single split). Surfaces come in two flavors: `terminal` (a pty + shell) or `browser` (an embedded WebKit view). + +Every pane has *current* `columns × rows` and a `pixel_frame` only when its workspace is the rendered one. Background workspaces report stale or zeroed geometry. + +--- + +## Two ways in: CLI vs raw socket + +Both speak the same JSON-RPC protocol; the CLI is just a thin wrapper. + +| Path | Pro | Con | +|------|-----|-----| +| `cmux ` (CLI) | Quoting works the way you'd expect; output is human-readable. | The CLI's `--json` flag is sometimes a passthrough, sometimes filters fields, sometimes returns plain text (`OK `). Inconsistent. | +| Unix socket at `/Users//Library/Application Support/cmux/cmux.sock` | Raw JSON, all fields preserved (incl. geometry). | Have to write a tiny client. | + +**This tool uses the CLI for mutating verbs** (`new-split`, `new-surface`, `rename-tab`, `select-workspace`, `resize-pane`, `send`, `close-workspace`, `rename-workspace`) **and the raw socket for read-time fields** that the CLI strips (`pane.list` geometry, `browser.url.get`, `window.list` refs). See `src/cmux/lib/cli.ts` and `src/cmux/lib/socket.ts`. + +### Resolving the socket path + +The path used to be `/tmp/cmux.sock`; in current builds it lives in your Library. Always resolve dynamically: + +```bash +cmux identify --json | python3 -c 'import json,sys; print(json.load(sys.stdin)["socket_path"])' +``` + +The lib does this once and caches the result (`getSocketPath()` in `socket.ts`). + +### Raw RPC envelope + +```json +// request +{"id":"x","method":"","params":{ ... }}\n + +// success +{"id":"x","ok":true,"result":{ ... }} + +// failure +{"id":"x","ok":false,"error":{"code":"","message":""}} +``` + +Always send a trailing `\n`. The server replies with one line. `capabilities` returns the full method allow-list (159 methods on 0.63.2). + +--- + +## Refs, IDs, indices + +cmux exposes three kinds of handles: + +| Handle | Format | Stable across | Use when | +|--------|--------|---------------|----------| +| **ref** | `window:1`, `workspace:2`, `pane:3`, `surface:4`, `tab:4` | Single cmux session | Day-to-day; what the CLI prints by default. | +| **UUID id** | `6DC71832-2DC6-42F0-8D21-761B87EF5726` | Persists across restarts | Long-term references (e.g. session files). Pass with `--id-format uuids` or use `*_id` fields. | +| **index** | `0`, `1`, `2` | Within parent | Selecting nth tab in a pane. Refs preferred. | + +Tab refs (`tab:N`) are the same numeric id as the surface they wrap; both refer to the same row in the data model. `tab-action` accepts either. + +**Refs reset every cmux relaunch.** Profile JSON stores titles + structure, never raw refs, for that reason. + +--- + +## Discovery and identification + +### `cmux identify [--json]` + +Returns the calling shell's place in the cmux tree, plus the focused surface and the socket path. + +```jsonc +{ + "socket_path": "/Users/Martin/Library/Application Support/cmux/cmux.sock", + "caller": { + "window_ref": "window:1", + "workspace_ref": "workspace:2", + "pane_ref": "pane:5", + "surface_ref": "surface:16", + "tab_ref": "tab:16", + "is_browser_surface": false, + "surface_type": "terminal" + }, + "focused": { /* same shape — what's currently visible */ } +} +``` + +`identify` is the first call this tool makes (`getSocketPath()` reads `socket_path`). + +### `cmux capabilities` + +Lists every JSON-RPC method the daemon understands. Useful for spelunking — `pane.geometry`, `workspace.layout`, etc. are NOT in the list, so don't bother asking for them. + +### `cmux ping` / `cmux version` + +`ping` returns `pong`; `version` prints `cmux X.Y.Z (build N) []` as plain text. The tool parses `cmux (\S+)` for the semver. + +--- + +## Windows + +A cmux process can have multiple top-level macOS windows. `tools cmux profiles` treats them as another nesting level. + +| Operation | CLI | Raw RPC | +|-----------|-----|---------| +| List windows | `cmux list-windows` (lacks `ref`) | `window.list` (has `ref` & `selected_workspace_ref`) | +| Current window | `cmux current-window` | `window.current` | +| New window | `cmux new-window` | `window.create` | +| Focus window | `cmux focus-window --window ` | `window.focus` | +| Close window | `cmux close-window --window ` | `window.close` | +| Move workspace to window | `cmux move-workspace-to-window --workspace --window ` | `workspace.move_to_window` | + +**Important.** `cmux --json list-windows` outputs an array but **does not include `ref`** for each entry — only `id`, `index`, `selected_workspace_id`, `key`, `workspace_count`, `visible`. Use raw `window.list` to get refs. + +```bash +# raw, with refs +python3 -c 'import socket,json +s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) +s.connect("/Users/Martin/Library/Application Support/cmux/cmux.sock") +s.send((json.dumps({"id":"x","method":"window.list","params":{}})+"\n").encode()) +import select; buf=b"" +while select.select([s],[],[],0.5)[0]: + c=s.recv(8192); buf+=c + if not c: break +print(json.loads(buf.decode())["result"]["windows"][0])' +``` + +--- + +## Workspaces + +| Operation | CLI | Raw RPC | Notes | +|-----------|-----|---------|-------| +| List in current window | `cmux list-workspaces` | `workspace.list` | Without `--params.window`, returns only the focused window's workspaces. | +| List in specific window | n/a | `workspace.list {"window":"window:N"}` | Use this for multi-window snapshots. | +| New | `cmux new-workspace [--name X] [--cwd PATH] [--command CMD]` returns `OK ` (plain text) | `workspace.create` returns `{workspace_ref, workspace_id, window_ref, window_id}` | The `name` arg is **best-effort** — cmux frequently overrides it with an auto-generated `user@host:cwd` title. Always follow up with `rename-workspace`. | +| Rename | `cmux rename-workspace [--workspace ] ""` | `workspace.rename` | Sticks. Use this. | +| Select (focus) | `cmux select-workspace --workspace <ref>` | `workspace.select` | **Steals user focus**. The 400 ms after the call is when geometry settles. | +| Reorder | `cmux reorder-workspace --workspace <ref> (--index N \| --before <ref> \| --after <ref>)` | `workspace.reorder` | | +| Close | `cmux close-workspace --workspace <ref>` | `workspace.close` | Surfaces inside die with the workspace. | +| Action (pin / unpin / etc.) | `cmux workspace-action --action <name> [--workspace <ref>]` | `workspace.action` | The set of valid actions is undocumented; `rename` is the only one we use. | + +### Per-workspace fields worth knowing + +A `workspace.list` entry contains: + +```jsonc +{ + "ref": "workspace:1", + "id": "92F762D5-...", + "index": 0, + "title": "reservine", + "selected": false, // is this the focused workspace? + "pinned": false, + "current_directory": "/Users/Martin/Tresors/Projects/ReservineBack", + "description": null, + "listening_ports": [], + "remote": { /* SSH state */ } +} +``` + +`current_directory` is the workspace's "default" cwd — the cwd new shells in this workspace inherit. `tools cmux profiles save` records it on every workspace. (Per-pane cwds for *existing* shells are derived from tab titles instead — see below.) + +--- + +## Panes + +A pane is a rectangle in the workspace. cmux manages them in a binary split tree internally; the CLI exposes the leaves. + +| Operation | CLI | Raw RPC | +|-----------|-----|---------| +| List panes in workspace | `cmux list-panes --workspace <ref>` | `pane.list {"workspace":"<ref>"}` | +| New split (creates a new pane next to the target) | `cmux new-split <left\|right\|up\|down> [--workspace <ref>] [--surface <ref>]` returns `{pane_ref, surface_ref, type, workspace_ref, window_ref}` | `surface.split` (see [the BIG GOTCHA](#the-big-gotcha-surfacesplit-surfacecreate-and-panelist-all-ignore-their-explicit-params)) | +| Focus pane | `cmux focus-pane --pane <ref>` | `pane.focus` | +| Resize pane | `cmux resize-pane --pane <ref> -L\|-R\|-U\|-D --amount <n>` | `pane.resize` | +| Swap panes | `cmux swap-pane --pane <ref> --target-pane <ref>` | `pane.swap` | +| New empty pane | `cmux new-pane [--type terminal\|browser] [--direction ...] [--url ...]` | `pane.create` | +| Break pane out to its own window | (no CLI) | `pane.break` | +| Join two panes | (no CLI) | `pane.join` | + +### `cmux list-panes --workspace <ref>` output (CLI, plain mode) + +```text + pane:23 [1 surface] +* pane:35 [1 surface] [focused] + pane:36 [3 surfaces] + pane:37 [1 surface] [focused] +``` + +### `pane.list` raw RPC output (the shape this tool relies on) + +```jsonc +{ + "workspace_ref": "workspace:2", + "window_ref": "window:1", + "container_frame": { "width": 3193.097, "height": 1378 }, + "panes": [ + { + "ref": "pane:4", + "id": "...", + "index": 0, + "focused": false, + "surface_count": 1, + "surface_refs": ["surface:14"], + "selected_surface_ref": "surface:14", + + // Geometry — only present on cmux 0.63.0+ (verified 0.63.2) + "columns": 199, + "rows": 38, + "cell_width_px": 8, + "cell_height_px": 17, + "pixel_frame": { + "x": 246.902, "y": 32, "width": 1596.548, "height": 689 + } + } + // ... + ] +} +``` + +`columns × rows` is what `stty size` would report inside the shell. `pixel_frame` is in macOS points, including the sidebar offset (so `x: 247` ≈ sidebar width + 0). + +### Resize semantics + +`cmux resize-pane --pane <ref> -R --amount 5` moves the **right boundary** of the pane right by 5 cells (i.e. pane gains 5 columns; the right neighbour loses 5). Dual for `-L/-U/-D`. If a pane has no neighbour in that direction the call fails with: + +```text +invalid_state: No vertical split ancestor for pane +``` + +`tools cmux profiles restore` swallows these failures and logs a warning rather than aborting — they happen when the converge loop overshoots and tries to push past a cmux constraint. + +--- + +## Surfaces (tabs) + +Surfaces are tabs inside a pane. Each pane has 1+ surfaces; clicking a tab makes that surface the visible one. + +| Operation | CLI | Raw RPC | +|-----------|-----|---------| +| List surfaces in a pane | `cmux list-pane-surfaces --workspace <ref> --pane <ref>` | `pane.surfaces` | +| List ALL surfaces in workspace | (no CLI) | `surface.list {"workspace":"<ref>"}` | +| New surface in existing pane | `cmux new-surface --pane <ref> --workspace <ref> [--type terminal\|browser] [--url URL]` returns `{pane_ref, surface_ref, type, ...}` | `surface.create` | +| Close (kill) a surface | `cmux close-surface --surface <ref>` | `surface.close` | +| Rename a tab | `cmux rename-tab [--workspace <ref>] [--surface <ref>] "<title>"` | `tab.action {"action":"rename","title":"..."}` | +| Move surface across panes | `cmux move-surface --surface <ref> [--pane <ref>] [--workspace <ref>] [--window <ref>] [--before <ref>] [--after <ref>] [--index N] [--focus true\|false]` | `surface.move` | +| Reorder tabs in same pane | `cmux reorder-surface --surface <ref> (--index N \| --before <ref> \| --after <ref>)` | `surface.reorder` | +| Refresh (reload everything) | `cmux refresh-surfaces` | `surface.refresh` | +| Surface health check | `cmux surface-health --workspace <ref>` | `surface.health` | +| Drag-target → split | `cmux drag-surface-to-split --surface <ref> <left\|right\|up\|down>` | `surface.drag_to_split` | + +### Surface metadata returned by `list-pane-surfaces` + +```jsonc +[ + { "ref": "surface:1", "type": "terminal", "title": "✳ templates-todo", "index": 0, "selected": false }, + { "ref": "surface:3", "type": "terminal", "title": "Martin@MacBook-Pro:~/Tresors/Projects/X", "index": 1, "selected": false }, + { "ref": "surface:12", "type": "terminal", "title": "tools claude usage", "index": 2, "selected": true } +] +``` + +`index` is **per-pane** (this is what `surface.list` calls `index_in_pane`). `selected` means "active tab in this pane". The CLI uses the short names; the raw socket method `surface.list` uses the long names. Don't mix them. + +### How cmux titles surfaces + +cmux derives a default tab title from whatever is running: + +| Running | Example title | +|---------|---------------| +| Idle shell (zsh) | `Martin@MacBook-Pro:~/Tresors/Projects/Foo` (OSC-7 + OSC-1337 derived) | +| `cd` to a long path, then idle | `…/Projects/Foo/sub/dir` | +| `claude` working | `✳ <session-name>` | +| `claude` idle | `⠐ <session-name>` | +| Shell command | the command line itself | + +`shell-probe.cwdFromTitle()` parses the first two patterns to recover a cwd without intrusively running `pwd` in each shell. + +--- + +## Geometry + +cmux 0.63.0 added `pixel_frame`, `columns`, `rows`, `cell_*_px`, and a top-level `container_frame` to `pane.list`. These are what enable exact 1-to-1 layout duplication. They're stripped from the CLI's `--json` output but present in the raw socket response. + +To verify on your install: + +```bash +echo "cmux $(cmux --version)" +python3 -c 'import socket,json +s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) +s.connect("/Users/Martin/Library/Application Support/cmux/cmux.sock") +s.send((json.dumps({"id":"x","method":"pane.list","params":{"workspace":"workspace:1"}})+"\n").encode()) +import select; buf=b"" +while select.select([s],[],[],0.5)[0]: + c=s.recv(65536); buf+=c + if not c: break +data=json.loads(buf.decode()) +print("container:", data["result"]["container_frame"]) +print("first pane has geometry:", any("pixel_frame" in p for p in data["result"]["panes"]))' +``` + +--- + +## Sending input + +| Operation | CLI | Raw RPC | +|-----------|-----|---------| +| Send literal text to a surface | `cmux send [--workspace <ref>] [--surface <ref>] "<text>"` | `surface.send_text` | +| Send a key | `cmux send-key [--workspace <ref>] [--surface <ref>] <key>` | `surface.send_key` | +| Capture buffer | `cmux capture-pane [--workspace <ref>] [--surface <ref>] [--scrollback] [--lines N]` | `surface.read_text` | +| Read whole screen | `cmux read-screen [--workspace <ref>] [--surface <ref>] [--scrollback] [--lines N]` | (alias of read_text) | +| Trigger a flash | `cmux trigger-flash [--workspace <ref>] [--surface <ref>]` | `surface.trigger_flash` | + +Key names accepted by `send-key`: `enter`, `tab`, `escape`, `up`/`down`/`left`/`right`, `ctrl-c`, `ctrl-d`, `pgup`, `pgdn`, etc. + +`tools cmux profiles restore` uses `cmux send` for two purposes: + +1. `send "cd <cwd>\n"` — actually executes (newline included). +2. `send "<command>"` — without the newline, so the captured shell command sits at the prompt and waits for the user to confirm with Enter. + +--- + +## Browser surfaces + +Browser surfaces are full WKWebViews. `tools cmux profiles save` captures their URL via the JSON-RPC `browser.url.get` call. + +| Verb | CLI | RPC | +|------|-----|-----| +| Open browser surface | `cmux browser open <url>` (opens new split) | `browser.open_split` | +| Get URL | (no CLI on 0.63.2) | `browser.url.get {"surface":"<ref>"}` | +| Navigate | `cmux browser <ref> goto <url>` | `browser.navigate` | +| Reload | `cmux browser <ref> reload` | `browser.reload` | +| Back / forward | `cmux browser <ref> back \| forward` | `browser.back` / `browser.forward` | +| Snapshot DOM | `cmux browser <ref> snapshot --interactive` | `browser.snapshot` | +| Click / fill / type | `cmux browser <ref> click <eN>` etc. | `browser.click` / `browser.fill` / `browser.type` | +| Save / load full state | `cmux browser <ref> state save \| load <path>` | `browser.state.save` / `browser.state.load` | + +cmux's full Playwright-equivalent API has ~85 methods under the `browser.*` namespace. `tools cmux profiles` only needs `browser.url.get`; everything else is left to `tools cmux browser` (future tool) or the user's other automation. + +--- + +## Sidebar status / progress / log / notifications + +Not used by the profile tool, but documented for completeness. These commands write to the cmux sidebar without stealing focus. + +```bash +cmux set-status <key> <value> [--icon <name>] [--color <#hex>] +cmux clear-status <key> +cmux list-status +cmux set-progress <0.0..1.0> [--label <text>] +cmux clear-progress +cmux log [--level info|success|warn|error] [--source <name>] -- <message> +cmux clear-log +cmux list-log [--limit N] +cmux sidebar-state +cmux notify --title <text> [--subtitle <text>] [--body <text>] +cmux list-notifications +cmux clear-notifications +``` + +Icon names are documented at `cmux help set-status`. Some popular ones: `hammer`, `clock`, `checkmark`, `xmark`, `bolt`, `sparkles`, `star`. + +--- + +## Known sharp edges & cmux 0.63.2 quirks + +These bit me during implementation. Don't trust the docs blindly; check. + +### The BIG GOTCHA: `surface.split`, `surface.create`, and `pane.list` all ignore their explicit params + +Three V1-routed methods fall back to `tabManager.selectedTabId` instead of using the explicit ref(s) on the request: + +```json +{"method":"surface.split","params":{"direction":"down","surface":"surface:47","workspace":"workspace:9"}} +// Splits the FOCUSED pane, not the pane containing surface:47. + +{"method":"surface.create","params":{"workspace":"workspace:17","pane":"pane:54","type":"terminal"}} +// Creates the surface in the FOCUSED pane (returns pane_ref of the focused pane, +// not pane:54). Effect for restore: when a saved layout has multi-tab panes, every +// extra tab piles up in the anchor pane instead of going to its target. + +{"method":"pane.list","params":{"workspace":"workspace:1"}} +// Returns the FOCUSED workspace's panes; response even echoes workspace_ref of the +// focused workspace, not the requested one. +``` + +For all three, the CLI counterparts work correctly — they route through V2 and honor the explicit params. So this tool uses: +- `cmux new-split <dir> --surface <ref> --workspace <ref>` instead of raw `surface.split` +- `cmux new-surface --pane <ref> --workspace <ref>` instead of raw `surface.create` +- For `pane.list` there's no V2 CLI alternative that returns geometry; we work around by `cmux select-workspace`-ing to the target before reading (causes focus flicker — same reason save can't run in the background). + +Filed upstream as [manaflow-ai/cmux#3189](https://github.com/manaflow-ai/cmux/issues/3189). + +### `cmux new-workspace`'s `--name` is best-effort + +cmux often replaces it with `Martin@MacBook-Pro:~/path/cwd`. Always follow up: + +```bash +cmux new-workspace --name "my-name" +# → "OK workspace:N" +cmux rename-workspace --workspace workspace:N "my-name" # this sticks +``` + +### `cmux --json` is not consistent + +| Command | `--json` behavior | +|---------|-------------------| +| `cmux --json list-panes` | Returns JSON, **strips geometry fields** (use raw socket for those). | +| `cmux --json identify` | Full JSON with geometry. | +| `cmux --json new-workspace` | Plain text `OK workspace:N`. | +| `cmux --json new-split` | Full JSON `{pane_ref, surface_ref, type, ...}`. | +| `cmux --json version` | Plain text `cmux X.Y.Z (...)`. | + +Treat each command separately. Don't assume `--json` returns JSON. + +### `tab-action --action` allow-list is unwritten + +The error `invalid_params: Unknown tab action` is the discoverer here. Known-good actions: `rename`. Common guesses that DON'T work: `select`, `switch`, `focus`, `activate`, `next`, `previous`, `close`. Use `surface.move`, `surface.close`, `surface.focus` instead. + +### CLI's `tools claude usage` titles indicate a tools binary in your PATH + +Not a cmux quirk — but if your tab titles show `tools claude usage`, that's GenesisTools' claude-usage tool running, not a cmux feature. + +### Refs are session-scoped + +Killing and relaunching cmux assigns brand-new refs. The 4 workspaces I had as `workspace:1..4` may all get different refs after a restart. Profile JSON stores titles + structure only, never raw refs. + +### Pane text reads are ANSI-stripped — colors cannot be captured + +`cmux capture-pane`, `cmux read-screen`, and the raw `surface.read_text` RPC all return **plain text only**. There is no `--ansi` / `--raw` / `--with-escapes` flag, and probing param variants (`ansi:true`, `raw:true`, `include_ansi:true`, `format:"ansi"`) on `surface.read_text` confirms the daemon never emits escape sequences. `read-screen --help` even spells it out: "Read terminal text from a surface as plain text." + +This is why `tools cmux profiles restore` paints back saved screens **monochrome**. The structure (login banner, prompts, command output) is preserved but colors are lost. tmux's equivalent (`tmux capture-pane -e`) does emit ANSI; cmux 0.63.2 has no analogue. + +### `cmux capture-pane --scrollback` returns visible content only (in 0.63.2) + +Despite the help text ("Include scrollback (not just visible viewport)"), `cmux capture-pane --scrollback --lines 5000 --surface <ref>` returns the same N lines as plain `capture-pane --surface <ref>` — i.e. the visible viewport, no real scrollback. The raw `surface.read_text {"scrollback":true}` RPC does return full scrollback (3000+ lines) but is affected by the V1 routing bug (issue #3189) — it always returns the focused surface's content regardless of the `surface` param. Net effect: per-surface scrollback access is currently impossible in 0.63.2 without a focus-switching dance. + +This means `tools cmux profiles save` can only capture the **visible** rows of each pane. For long-running TUIs (Claude Code, vim) where the launching shell command (`claude --resume <id>`) has scrolled past the visible area, the `command` field will be empty — there is nothing for the parser to find. + +--- + +## What `tools cmux profiles ...` actually does + +A walkthrough of the exact cmux calls our CLI makes. + +### `tools cmux profiles save <name>` + +```bash +cmux identify --json # resolve socket path (cached) +cmux --version # for cmux_version field + +# Discover (raw socket — CLI strips refs from list-windows) +RPC window.list # → [{ref, id, index, ...}] +for each window: + RPC workspace.list { window: <ref> } # → workspaces with current_directory + +# Per workspace (sequential): + cmux select-workspace --workspace <ref> # FOCUS FLICKER (~400ms) + RPC pane.list { workspace: <ref> } # geometry, container_frame + for each pane: + cmux --json list-pane-surfaces --workspace <ref> --pane <ref> + for each surface: + if browser: RPC browser.url.get { surface: <ref> } + if terminal: + cwdFromTitle(title) # per-pane cwd from OSC-7 title + cmux capture-pane --workspace <ref> --surface <ref> # visible content, ANSI-stripped + lastCommandFromCapture(text) # parse trailing shell prompt + +# After everything is captured: +cmux select-workspace --workspace <originally-focused-ref> # restore focus + +# Write JSON (atomic rename) +~/.genesis-tools/cmux/profiles/<name>.json +``` + +### `tools cmux profiles restore <name>` + +```bash +read profile JSON + +for each window in profile: + if profile-windows > current-cmux-windows: + cmux new-window + for each workspace in window: + RPC workspace.create { name: "<prefix><orig>" } # → workspace_ref + cmux rename-workspace --workspace <new> "<prefix><orig>" # name actually sticks now + + cmux select-workspace --workspace <new> # FOCUS FLICKER + + # Topology + RPC pane.list { workspace: <new> } # confirm 1 starting pane + buildSplitTree(saved-pane-pixel_frames) # binary tree from rect adjacency, + # each internal node carries the saved + # leftFraction or topFraction (0..1) + applyTree: + for each internal node: + cmux --json new-split <right|down> --surface <anchor> --workspace <new> + # Resize the JUST-CREATED border immediately (one pair of panes shares it now; + # cmux's resize-pane errors with "no adjacent border in direction X" once deeper + # splits exist, so global post-hoc convergence does not work). + # cmux's --amount is in PIXELS (empirically — despite "tmux-compatible alias"), + # so multiply cell-deltas by pane.cell_width_px / cell_height_px. + # Direction must match the pane that has a neighbor in that direction: + # • move border LEFT (shrink old / grow new) → -L on NEW (right pane) + # • move border RIGHT (grow old / shrink new) → -R on OLD (left pane) + # • move border UP (grow new bottom) → -U on NEW (bottom pane) + # • move border DOWN (grow old top) → -D on OLD (top pane) + # Re-read pane.list after each call (cmux clamps to neighbour min size and rounds + # to whole cells) and loop up to 8 attempts; bail when a call doesn't reduce delta. + for each leaf: + record map[savedIndex] = current pane ref + + # Surfaces + for each saved pane: + while current surfaces < saved surfaces: + cmux new-surface --pane <ref> --workspace <new> --type <terminal|browser> [--url ...] + # NOT raw RPC surface.create — that ignores the pane param and creates in the + # focused pane (tabs would all stack into the anchor pane). See gotcha above. + for each saved surface: + cmux rename-tab --workspace <new> --surface <ref> "<title>" + if terminal: + # Single composite shell command, sent as one cmux-send payload: + # cd <cwd> 2>/dev/null ← silently restore working dir + # ; printf '\033[2J\033[3J\033[H' ← clear screen + scrollback + cursor home + # ; printf %s '<base64>' | base64 -d ← print the saved screen text back out + # \n ← execute the line + # <command> ← typed but NOT executed (no \n) + # The end result: the new pane shows exactly the saved screen + a fresh prompt + # below, with the saved last command pre-typed and waiting for Enter. + cmux send --workspace <new> --surface <ref> "<composite payload>" + +cmux select-workspace --workspace <originally-focused> # restore focus +``` + +Limitations baked into this design: + +- **Monochrome.** Saved screen content is ANSI-stripped by cmux 0.63.2 (see "Pane text reads are ANSI-stripped" above). Replay shows the structure but loses colors. +- **Visible-rows only.** Scrollback is not currently retrievable per-surface (CLI `--scrollback` returns visible only; raw RPC `surface.read_text {scrollback:true}` is V1-routing-bugged). Long-running TUI panes lose their pre-TUI shell command. +- **Pre-typed command can be wrong** if the parser hits a non-shell prompt that uses `❯`/`$` glyphs. We mitigate by only matching prompts with directory/git/host context (oh-my-zsh robbyrussell, `[user@host]$`, `user@host:dir$`); bare-glyph prompts are deliberately rejected. + +That's the entire integration surface. Everything else (cookies, network mocking, sidebar UX) is downstream cmux features we don't currently use. diff --git a/src/cmux/index.ts b/src/cmux/index.ts new file mode 100644 index 0000000000..41d3d84a79 --- /dev/null +++ b/src/cmux/index.ts @@ -0,0 +1,39 @@ +#!/usr/bin/env bun + +/** + * cmux profile manager — save, view, restore cmux workspace layouts. + * + * Usage: + * tools cmux profiles save [<name>] + * tools cmux profiles list + * tools cmux profiles view <name> + * tools cmux profiles restore <name> + * tools cmux profiles edit <name> + * tools cmux profiles delete <name> + * tools cmux profiles path <name> + */ + +import { Command } from "commander"; +import { registerProfilesCommand } from "@app/cmux/commands/profiles"; +import { enhanceHelp } from "@app/utils/cli"; +import { handleReadmeFlag } from "@app/utils/readme"; + +handleReadmeFlag(import.meta.url); + +const program = new Command(); + +program + .name("cmux") + .description("Save, inspect, and restore cmux workspace profiles.") + .version("0.1.0") + .showHelpAfterError(true) + .option("-v, --verbose", "Enable debug logging"); + +registerProfilesCommand(program); + +enhanceHelp(program); + +program.parseAsync(process.argv).catch((error) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); +}); diff --git a/src/cmux/lib/__tests__/restore-tree.test.ts b/src/cmux/lib/__tests__/restore-tree.test.ts new file mode 100644 index 0000000000..7239205cc6 --- /dev/null +++ b/src/cmux/lib/__tests__/restore-tree.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "bun:test"; +import { buildSplitTree } from "@app/cmux/lib/restore"; +import type { Pane } from "@app/cmux/lib/types"; + +function pane(index: number, x: number, y: number, width: number, height: number): Pane { + return { + ref: `pane:${index}`, + index, + columns: Math.round(width / 8), + rows: Math.round(height / 18), + pixel_frame: { x, y, width, height }, + selected_surface_index: 0, + surfaces: [], + }; +} + +describe("buildSplitTree", () => { + it("returns a leaf for a single pane", () => { + const tree = buildSplitTree([pane(0, 0, 0, 1000, 800)]); + expect(tree.kind).toBe("leaf"); + if (tree.kind === "leaf") { + expect(tree.savedPaneIndex).toBe(0); + } + }); + + it("recognises a left/right vertical split with 0.5 fraction", () => { + const tree = buildSplitTree([pane(0, 0, 0, 500, 800), pane(1, 500, 0, 500, 800)]); + expect(tree.kind).toBe("vsplit"); + if (tree.kind === "vsplit") { + expect(tree.leftFraction).toBeCloseTo(0.5, 2); + } + }); + + it("recognises a top/bottom horizontal split with 0.5 fraction", () => { + const tree = buildSplitTree([pane(0, 0, 0, 1000, 400), pane(1, 0, 400, 1000, 400)]); + expect(tree.kind).toBe("hsplit"); + if (tree.kind === "hsplit") { + expect(tree.topFraction).toBeCloseTo(0.5, 2); + } + }); + + it("captures non-half fractions for asymmetric splits", () => { + // Left pane is 25% wide, right pane is 75% wide. + const tree = buildSplitTree([pane(0, 0, 0, 250, 800), pane(1, 250, 0, 750, 800)]); + expect(tree.kind).toBe("vsplit"); + if (tree.kind === "vsplit") { + expect(tree.leftFraction).toBeCloseTo(0.25, 2); + } + }); + + it("decomposes the reservine layout (left full + 2 stacked right)", () => { + const tree = buildSplitTree([ + pane(0, 0, 0, 500, 800), // left full-height + pane(1, 500, 0, 500, 400), // top-right + pane(2, 500, 400, 500, 400), // bottom-right + ]); + expect(tree.kind).toBe("vsplit"); + if (tree.kind !== "vsplit") { + return; + } + expect(tree.left.kind).toBe("leaf"); + expect(tree.right.kind).toBe("hsplit"); + }); + + it("decomposes a 2x2 grid", () => { + const tree = buildSplitTree([ + pane(0, 0, 0, 500, 400), + pane(1, 0, 400, 500, 400), + pane(2, 500, 0, 500, 400), + pane(3, 500, 400, 500, 400), + ]); + expect(tree.kind).toBe("vsplit"); + if (tree.kind !== "vsplit") { + return; + } + expect(tree.left.kind).toBe("hsplit"); + expect(tree.right.kind).toBe("hsplit"); + }); + + it("throws when no separator line cleanly partitions 4+ overlapping rects", () => { + // 4 rectangles in a pinwheel pattern with no clean horizontal or vertical separator. + expect(() => + buildSplitTree([ + pane(0, 0, 0, 600, 300), + pane(1, 600, 0, 400, 600), + pane(2, 400, 300, 600, 300), + pane(3, 0, 300, 400, 600), + ]), + ).toThrow(); + }); +}); diff --git a/src/cmux/lib/__tests__/shell-probe.test.ts b/src/cmux/lib/__tests__/shell-probe.test.ts new file mode 100644 index 0000000000..9ceb626172 --- /dev/null +++ b/src/cmux/lib/__tests__/shell-probe.test.ts @@ -0,0 +1,129 @@ +import { homedir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "bun:test"; +import { cwdFromTitle, lastCommandFromCapture } from "@app/cmux/lib/shell-probe"; + +describe("cwdFromTitle", () => { + it("returns undefined for empty/null titles", () => { + expect(cwdFromTitle(null)).toBeUndefined(); + expect(cwdFromTitle(undefined)).toBeUndefined(); + expect(cwdFromTitle("")).toBeUndefined(); + }); + + it("expands user@host:~/path titles", () => { + const out = cwdFromTitle("Martin@MacBook-Pro:~/Tresors/Projects/Foo"); + expect(out).toBe(join(homedir(), "Tresors/Projects/Foo")); + }); + + it("keeps absolute user@host:/abs paths", () => { + const out = cwdFromTitle("user@host:/usr/local/bin"); + expect(out).toBe("/usr/local/bin"); + }); + + it("expands ellipsis prefix titles (cmux abbreviation)", () => { + const out = cwdFromTitle("…/Projects/Bar"); + expect(out).toBe(join(homedir(), "Projects/Bar")); + }); + + it("expands tilde prefix titles", () => { + const out = cwdFromTitle("~/Documents"); + expect(out).toBe(join(homedir(), "Documents")); + }); + + it("returns absolute paths verbatim", () => { + expect(cwdFromTitle("/etc")).toBe("/etc"); + expect(cwdFromTitle("/var/log/system")).toBe("/var/log/system"); + }); + + it("ignores titles that don't look like paths (claude-style busy markers)", () => { + expect(cwdFromTitle("✳ Debug formatting and spacing issues")).toBeUndefined(); + expect(cwdFromTitle("tools claude usage")).toBeUndefined(); + expect(cwdFromTitle("Terminal")).toBeUndefined(); + }); +}); + +describe("lastCommandFromCapture", () => { + it("returns none for empty input", () => { + expect(lastCommandFromCapture("")).toEqual({ value: undefined, source: "none" }); + expect(lastCommandFromCapture(null)).toEqual({ value: undefined, source: "none" }); + }); + + it("captures the most recent oh-my-zsh prompt above an empty trailing prompt", () => { + const text = [ + "Last login: Mon Apr 27 19:24:32 on ttys013", + "You have mail.", + "➜ GenesisTools git:(fix/several) ✗ cd /Users/Martin/Tresors/Projects/GenesisTools", + "➜ GenesisTools git:(feat/cmux) ✗ bun test src/cmux/lib/__tests__/", + "20 pass, 0 fail", + "➜ GenesisTools git:(feat/cmux) ✗", + ].join("\n"); + expect(lastCommandFromCapture(text)).toEqual({ + value: "bun test src/cmux/lib/__tests__/", + source: "scrollback", + }); + }); + + it("intentionally ignores bare-❯ prompts because Claude/Forge input boxes use the same glyph", () => { + const text = "~/path\n❯ git status\nOn branch feat/cmux\n~/path\n❯"; + expect(lastCommandFromCapture(text)).toEqual({ value: undefined, source: "none" }); + }); + + it("captures bracketed bash prompts", () => { + const text = "[user@host ~/projects]$ npm run build\nbuild ok\n[user@host ~/projects]$"; + expect(lastCommandFromCapture(text)).toEqual({ value: "npm run build", source: "scrollback" }); + }); + + it("captures a command currently typed at the prompt (not yet executed)", () => { + const text = "➜ app git:(main) ✗ ./deploy.sh --staging"; + expect(lastCommandFromCapture(text)).toEqual({ + value: "./deploy.sh --staging", + source: "scrollback", + }); + }); + + it("returns none for TUI screens with no shell prompt (Claude Code, vim, etc.)", () => { + const text = [ + "⏺ Now push the worktree commits to remote.", + " 143752 tokens", + "──────────────────────────────────── timely-create-from-memory ──", + " claude-opus-4-7 plans-from-issues feat/cmux", + " ⏵⏵ bypass permissions on (shift+tab to cycle)", + ].join("\n"); + expect(lastCommandFromCapture(text)).toEqual({ value: undefined, source: "none" }); + }); + + it("ignores empty trailing prompts (with or without ✗ dirty mark) and walks upward", () => { + const text = "➜ app git:(main) ✗ ls\nfile.ts\n➜ app git:(main) ✗\n\n"; + expect(lastCommandFromCapture(text)).toEqual({ value: "ls", source: "scrollback" }); + }); + + it("captures a claude --resume command typed at a prior shell prompt before the TUI", () => { + const text = [ + "Last login: Mon Apr 27 14:00:00 on ttys001", + "➜ GenesisTools git:(feat/cmux) ✗ claude --resume acb054fd-a584-4b2f-84ba-ed495b54d3f4", + "Welcome to Claude Code", + "[long TUI rendering follows...]", + ].join("\n"); + expect(lastCommandFromCapture(text)).toEqual({ + value: "claude --resume acb054fd-a584-4b2f-84ba-ed495b54d3f4", + source: "scrollback", + }); + }); + + it("walks past Claude TUI input boxes (bare ❯ chat lines) and finds the launching shell command", () => { + const text = [ + "➜ GenesisTools git:(feat/cmux) ✗ claude --resume abc-123", + "Welcome to Claude Code", + "[lots of TUI rendering...]", + "──────────────────────────────────── timely-create-from-memory ──", + "❯ help me debug this issue with the parser?", + "───────────────────────────────────────────────────────────────────", + " claude-opus-4-7 some-branch feat/cmux", + " ⏵⏵ bypass permissions on (shift+tab to cycle)", + ].join("\n"); + expect(lastCommandFromCapture(text)).toEqual({ + value: "claude --resume abc-123", + source: "scrollback", + }); + }); +}); diff --git a/src/cmux/lib/__tests__/store.test.ts b/src/cmux/lib/__tests__/store.test.ts new file mode 100644 index 0000000000..ad5ea1cc54 --- /dev/null +++ b/src/cmux/lib/__tests__/store.test.ts @@ -0,0 +1,103 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { ProfileExistsError, ProfileNotFoundError, ProfileStore } from "@app/cmux/lib/store"; +import { type Profile, PROFILE_VERSION } from "@app/cmux/lib/types"; + +const sampleProfile: Profile = { + version: PROFILE_VERSION, + name: "demo", + scope: "all", + captured_at: "2026-04-27T15:00:00.000Z", + cmux_version: "0.63.2", + note: "test fixture", + windows: [ + { + ref: "window:1", + title: "Main", + container_frame: { width: 3193, height: 1378 }, + workspaces: [ + { + ref: "workspace:1", + title: "alpha", + selected: true, + panes: [ + { + ref: "pane:1", + index: 0, + columns: 199, + rows: 79, + pixel_frame: { x: 0, y: 0, width: 1597, height: 1378 }, + selected_surface_index: 0, + surfaces: [{ type: "terminal", title: "alpha-1" }], + }, + ], + }, + ], + }, + ], +}; + +let tempDir: string; +let store: ProfileStore; + +beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "cmux-store-test-")); + store = new ProfileStore({ profilesDir: tempDir }); +}); + +afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); +}); + +describe("ProfileStore", () => { + it("round-trips a profile through write + read", () => { + store.write("demo", sampleProfile); + const read = store.read("demo"); + expect(read.name).toBe("demo"); + expect(read.windows).toHaveLength(1); + expect(read.windows[0].workspaces[0].panes[0].surfaces).toHaveLength(1); + }); + + it("rejects duplicate writes without --force", () => { + store.write("demo", sampleProfile); + expect(() => store.write("demo", sampleProfile)).toThrow(ProfileExistsError); + expect(() => store.write("demo", sampleProfile, { force: true })).not.toThrow(); + }); + + it("rejects unsafe profile names", () => { + expect(() => store.pathFor("../escape")).toThrow(); + expect(() => store.pathFor("with/slash")).toThrow(); + expect(() => store.pathFor("with space")).toThrow(); + expect(store.pathFor("safe.dot_under-dash")).toContain("safe.dot_under-dash.json"); + }); + + it("returns ProfileNotFoundError for missing names", () => { + expect(() => store.read("does-not-exist")).toThrow(ProfileNotFoundError); + }); + + it("lists profiles in name-sorted order", () => { + store.write("zeta", { ...sampleProfile, name: "zeta" }); + store.write("alpha", { ...sampleProfile, name: "alpha" }); + store.write("beta", { ...sampleProfile, name: "beta" }); + const summaries = store.list(); + expect(summaries.map((s) => s.name)).toEqual(["alpha", "beta", "zeta"]); + }); + + it("delete returns true on hit, false on miss", () => { + store.write("demo", sampleProfile); + expect(store.delete("demo")).toBe(true); + expect(store.delete("demo")).toBe(false); + }); + + it("summarize counts windows/workspaces/panes/surfaces", () => { + store.write("demo", sampleProfile); + const summary = store.summarize(sampleProfile); + expect(summary.windows).toBe(1); + expect(summary.workspaces).toBe(1); + expect(summary.panes).toBe(1); + expect(summary.surfaces).toBe(1); + expect(summary.bytes).toBeGreaterThan(0); + }); +}); diff --git a/src/cmux/lib/cli.ts b/src/cmux/lib/cli.ts new file mode 100644 index 0000000000..3192618412 --- /dev/null +++ b/src/cmux/lib/cli.ts @@ -0,0 +1,47 @@ +import logger from "@app/logger"; +import { SafeJSON } from "@app/utils/json"; + +export interface CmuxRunResult { + code: number; + stdout: string; + stderr: string; +} + +export async function runCmux(args: string[], opts: { json?: boolean } = {}): Promise<CmuxRunResult> { + const finalArgs = opts.json ? ["--json", ...args] : args; + logger.debug({ args: finalArgs }, "[cmux] spawn"); + const proc = Bun.spawn(["cmux", ...finalArgs], { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + if (exitCode === null) { + throw new Error(`cmux terminated by signal before exiting`); + } + return { code: exitCode, stdout, stderr }; +} + +export async function runCmuxJSON<T = unknown>(args: string[]): Promise<T> { + const result = await runCmux(args, { json: true }); + if (result.code !== 0) { + const message = `cmux ${args.join(" ")} failed (${result.code}): ${result.stderr.trim()}`; + logger.error({ args, code: result.code, stderr: result.stderr }, "[cmux] command failed"); + throw new Error(message); + } + try { + return SafeJSON.parse(result.stdout, { strict: true }) as T; + } catch (error) { + logger.error({ args, stdout: result.stdout.slice(0, 500), error }, "[cmux] non-JSON response on --json call"); + throw new Error(`cmux ${args.join(" ")} returned non-JSON output:\n${result.stdout.slice(0, 500)}\n(${error})`); + } +} + +export async function runCmuxOk(args: string[]): Promise<CmuxRunResult> { + const result = await runCmux(args); + if (result.code !== 0) { + logger.error({ args, code: result.code, stderr: result.stderr }, "[cmux] command failed"); + throw new Error(`cmux ${args.join(" ")} failed (${result.code}): ${result.stderr.trim()}`); + } + return result; +} diff --git a/src/cmux/lib/focus-guard.ts b/src/cmux/lib/focus-guard.ts new file mode 100644 index 0000000000..dc68a181d9 --- /dev/null +++ b/src/cmux/lib/focus-guard.ts @@ -0,0 +1,48 @@ +import logger from "@app/logger"; +import { runCmuxJSON, runCmuxOk } from "@app/cmux/lib/cli"; + +interface IdentifyFocused { + workspace_ref?: string; +} + +interface IdentifyResponse { + focused?: IdentifyFocused; +} + +const FOCUS_SETTLE_MS = 400; + +async function getFocusedWorkspaceRef(): Promise<string | undefined> { + const identify = await runCmuxJSON<IdentifyResponse>(["identify"]); + return identify.focused?.workspace_ref; +} + +async function selectWorkspace(ref: string): Promise<void> { + await runCmuxOk(["select-workspace", "--workspace", ref]); +} + +async function sleep(ms: number): Promise<void> { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export async function withFocusedWorkspace<T>(workspaceRef: string, fn: () => Promise<T>): Promise<T> { + const previous = await getFocusedWorkspaceRef(); + const needSwitch = previous !== workspaceRef; + + if (needSwitch) { + logger.debug({ from: previous, to: workspaceRef }, "[focus-guard] switching workspace"); + await selectWorkspace(workspaceRef); + await sleep(FOCUS_SETTLE_MS); + } + + try { + return await fn(); + } finally { + if (needSwitch && previous && previous !== workspaceRef) { + try { + await selectWorkspace(previous); + } catch (error) { + logger.warn({ error, previous }, "[focus-guard] failed to restore previous workspace"); + } + } + } +} diff --git a/src/cmux/lib/format.ts b/src/cmux/lib/format.ts new file mode 100644 index 0000000000..fbbf315a99 --- /dev/null +++ b/src/cmux/lib/format.ts @@ -0,0 +1,156 @@ +import pc from "picocolors"; +import { formatBytes } from "@app/utils/format"; +import { stripAnsi } from "@app/utils/string"; +import type { Pane, Profile, ProfileSummary, Surface } from "@app/cmux/lib/types"; + +const TREE_VERTICAL = pc.dim("│"); +const TREE_BRANCH = pc.dim("├─"); +const TREE_LAST = pc.dim("└─"); +const TREE_GAP = pc.dim(" "); + +export function renderProfileList(summaries: ProfileSummary[]): string { + if (summaries.length === 0) { + return pc.dim("(no profiles saved yet)"); + } + + const rows: string[][] = [ + [ + pc.bold("name"), + pc.bold("scope"), + pc.bold("captured"), + pc.bold("W"), + pc.bold("Ws"), + pc.bold("P"), + pc.bold("S"), + pc.bold("size"), + pc.bold("note"), + ], + ]; + for (const s of summaries) { + rows.push([ + pc.cyan(s.name), + scopeLabel(s.scope), + pc.dim(relativeIso(s.captured_at)), + String(s.windows), + String(s.workspaces), + String(s.panes), + String(s.surfaces), + pc.dim(formatBytes(s.bytes)), + s.note ? pc.dim(truncate(s.note, 40)) : pc.dim("—"), + ]); + } + return renderTable(rows); +} + +export function renderProfileTree(profile: Profile): string { + const lines: string[] = []; + const header = `${pc.bold(pc.cyan(profile.name))} ${pc.dim(`(${profile.scope})`)} ${pc.dim(profile.captured_at)}`; + lines.push(header); + if (profile.note) { + lines.push(pc.dim(`note: ${profile.note}`)); + } + lines.push(pc.dim(`cmux ${profile.cmux_version} · ${profile.windows.length} window(s)`)); + lines.push(""); + + profile.windows.forEach((window, wi) => { + const isLastWindow = wi === profile.windows.length - 1; + const windowPrefix = isLastWindow ? TREE_LAST : TREE_BRANCH; + lines.push( + `${windowPrefix} ${pc.bold(window.title || window.ref)} ${pc.dim(`${window.container_frame.width.toFixed(0)}×${window.container_frame.height.toFixed(0)} px`)}`, + ); + + const childIndent = isLastWindow ? " " : `${TREE_VERTICAL} `; + window.workspaces.forEach((ws, wsIndex) => { + const isLastWs = wsIndex === window.workspaces.length - 1; + const wsPrefix = isLastWs ? TREE_LAST : TREE_BRANCH; + const wsBadge = ws.selected ? pc.green(" ★") : ""; + lines.push( + `${childIndent}${wsPrefix} ${pc.cyan(ws.title)}${wsBadge} ${pc.dim(`(${ws.panes.length} pane${ws.panes.length === 1 ? "" : "s"})`)}`, + ); + const wsChildIndent = childIndent + (isLastWs ? " " : `${TREE_VERTICAL} `); + ws.panes.forEach((pane, pi) => { + const isLastPane = pi === ws.panes.length - 1; + const panePrefix = isLastPane ? TREE_LAST : TREE_BRANCH; + lines.push(`${wsChildIndent}${panePrefix} ${formatPaneHeader(pane)}`); + const paneChildIndent = wsChildIndent + (isLastPane ? " " : `${TREE_VERTICAL} `); + pane.surfaces.forEach((surface, si) => { + const isLastSurface = si === pane.surfaces.length - 1; + const surfacePrefix = isLastSurface ? TREE_LAST : TREE_BRANCH; + const star = si === pane.selected_surface_index ? pc.green("★") : pc.dim("·"); + lines.push(`${paneChildIndent}${surfacePrefix} ${star} ${formatSurface(surface)}`); + }); + }); + }); + }); + + return lines.join("\n"); +} + +function formatPaneHeader(pane: Pane): string { + const dims = pc.dim(`${pane.columns}×${pane.rows}`); + const px = pc.dim( + `@(${pane.pixel_frame.x.toFixed(0)},${pane.pixel_frame.y.toFixed(0)}) ${pane.pixel_frame.width.toFixed(0)}×${pane.pixel_frame.height.toFixed(0)}px`, + ); + return `${pc.bold(`pane ${pane.index}`)} ${dims} ${px}`; +} + +function formatSurface(surface: Surface): string { + const title = pc.white(truncate(surface.title || "(untitled)", 60)); + if (surface.type === "browser") { + const url = surface.url ? pc.dim(` → ${truncate(surface.url, 60)}`) : pc.dim(" (no url)"); + return `${pc.magenta("browser")} ${title}${url}`; + } + const cwd = surface.cwd ? pc.dim(` cwd=${truncate(surface.cwd, 50)}`) : ""; + const screen = surface.screen + ? pc.dim(` screen=${surface.screen.rows}r/${formatBytes(Buffer.byteLength(surface.screen.text, "utf8"))}`) + : ""; + const cmd = + surface.command && surface.command_source && surface.command_source !== "none" + ? pc.dim(` cmd[${surface.command_source}]=${truncate(surface.command, 40)}`) + : ""; + return `${pc.yellow("term")} ${title}${cwd}${screen}${cmd}`; +} + +function scopeLabel(scope: string): string { + if (scope === "all") { + return pc.green("all"); + } + if (scope === "window") { + return pc.blue("window"); + } + return pc.magenta("workspace"); +} + +function relativeIso(iso: string): string { + return iso.replace("T", " ").replace(/\.\d+Z$/, "Z"); +} + +function truncate(text: string, max: number): string { + if (text.length <= max) { + return text; + } + return `${text.slice(0, max - 1)}…`; +} + +function renderTable(rows: string[][]): string { + const widths: number[] = []; + for (const row of rows) { + row.forEach((cell, i) => { + const visibleLength = stripAnsi(cell).length; + if (widths[i] === undefined || visibleLength > widths[i]) { + widths[i] = visibleLength; + } + }); + } + return rows + .map((row) => + row + .map((cell, i) => { + const visible = stripAnsi(cell).length; + return cell + " ".repeat(widths[i] - visible); + }) + .join(" "), + ) + .join("\n"); +} + diff --git a/src/cmux/lib/restore.ts b/src/cmux/lib/restore.ts new file mode 100644 index 0000000000..af51f619ad --- /dev/null +++ b/src/cmux/lib/restore.ts @@ -0,0 +1,572 @@ +import { runCmuxJSON, runCmuxOk } from "@app/cmux/lib/cli"; +import { withFocusedWorkspace } from "@app/cmux/lib/focus-guard"; +import { paneList, type SurfaceSplitResult, workspaceCreate } from "@app/cmux/lib/socket"; +import type { Pane, Profile, Surface, Workspace } from "@app/cmux/lib/types"; +import logger from "@app/logger"; + +const EDGE_TOLERANCE_PX = 2; + +export interface RestoreOptions { + prefix: string; + replay: boolean; + yes: boolean; + dryRun: boolean; +} + +export interface RestorePlanWorkspace { + sourceTitle: string; + targetTitle: string; + paneCount: number; + surfaceCount: number; +} + +export interface RestorePlan { + workspaces: RestorePlanWorkspace[]; +} + +export interface RestoreOutcome { + workspaces: Array<{ + ref: string; + title: string; + converged: boolean; + /** Largest |saved - actual| over all panes / dimensions, in terminal cells. */ + maxCellDelta: number; + }>; +} + +export interface RestoreEvents { + onWorkspaceStart?: (info: { title: string; index: number; total: number }) => void; + onWorkspaceDone?: (info: { ref: string; title: string }) => void; +} + +export function buildPlan(profile: Profile, opts: RestoreOptions): RestorePlan { + const workspaces: RestorePlanWorkspace[] = []; + for (const window of profile.windows) { + for (const ws of window.workspaces) { + const surfaceCount = ws.panes.reduce((acc, pane) => acc + pane.surfaces.length, 0); + workspaces.push({ + sourceTitle: ws.title, + targetTitle: `${opts.prefix}${ws.title}`, + paneCount: ws.panes.length, + surfaceCount, + }); + } + } + return { workspaces }; +} + +export async function restoreProfile( + profile: Profile, + opts: RestoreOptions, + events: RestoreEvents = {} +): Promise<RestoreOutcome> { + const outcome: RestoreOutcome = { workspaces: [] }; + const totalWorkspaces = profile.windows.reduce((acc, w) => acc + w.workspaces.length, 0); + let visited = 0; + + for (const window of profile.windows) { + for (const ws of window.workspaces) { + visited += 1; + const targetTitle = `${opts.prefix}${ws.title}`; + events.onWorkspaceStart?.({ title: targetTitle, index: visited, total: totalWorkspaces }); + + const created = await workspaceCreate({ name: targetTitle }); + // workspace.create's name param is best-effort; cmux often overrides it with an + // auto-generated user@host:cwd title. Force the desired title explicitly. + try { + await runCmuxOk(["rename-workspace", "--workspace", created.workspace_ref, targetTitle]); + } catch (error) { + logger.warn( + { error, workspaceRef: created.workspace_ref, targetTitle }, + "[restore] rename-workspace failed; continuing with auto-generated title" + ); + } + const result = await withFocusedWorkspace(created.workspace_ref, async () => { + return await materializeWorkspace(ws, created.workspace_ref, opts); + }); + + outcome.workspaces.push({ + ref: created.workspace_ref, + title: targetTitle, + converged: result.converged, + maxCellDelta: result.maxCellDelta, + }); + events.onWorkspaceDone?.({ ref: created.workspace_ref, title: targetTitle }); + } + } + return outcome; +} + +interface MaterializeResult { + converged: boolean; + /** Largest |saved - actual| over all panes / dimensions, in terminal cells. */ + maxCellDelta: number; +} + +async function materializeWorkspace( + ws: Workspace, + workspaceRef: string, + opts: RestoreOptions +): Promise<MaterializeResult> { + if (ws.panes.length === 0) { + return { converged: true, maxCellDelta: 0 }; + } + + const initialLayout = await paneList(workspaceRef); + if (initialLayout.panes.length !== 1) { + throw new Error(`Expected new workspace to start with 1 pane, got ${initialLayout.panes.length}`); + } + const rootPane = initialLayout.panes[0]; + const rootSurface = rootPane.selected_surface_ref; + + const tree = buildSplitTree(ws.panes); + const paneRefByIndex = new Map<number, string>(); + await applyTree(tree, rootSurface, workspaceRef, paneRefByIndex); + + // applyTree resizes the new border immediately after each split, so by the time + // the topology is fully built every saved fraction is already in place. Verify + // and report any panes that ended up off (most likely cmux clamped a resize at + // a minimum-pane-size limit). + const finalLayout = await paneList(workspaceRef); + let maxDelta = 0; + for (const savedPane of ws.panes) { + const newRef = paneRefByIndex.get(savedPane.index); + if (!newRef) { + logger.warn( + { savedIndex: savedPane.index, mappedKeys: [...paneRefByIndex.keys()] }, + "[restore] saved pane index has no new pane mapping" + ); + continue; + } + const live = finalLayout.panes.find((p) => p.ref === newRef); + if (!live) { + continue; + } + const dCols = Math.abs(savedPane.columns - live.columns); + const dRows = Math.abs(savedPane.rows - live.rows); + maxDelta = Math.max(maxDelta, dCols, dRows); + } + + for (const savedPane of ws.panes) { + const paneRef = paneRefByIndex.get(savedPane.index); + if (!paneRef) { + continue; + } + await populatePane(savedPane, paneRef, workspaceRef, opts); + } + + return { converged: maxDelta <= 1, maxCellDelta: maxDelta }; +} + +export type SplitTree = + | { kind: "leaf"; savedPaneIndex: number } + | { + kind: "vsplit"; + left: SplitTree; + right: SplitTree; + /** Saved fraction of the parent's width occupied by the left subtree (0..1). */ + leftFraction: number; + } + | { + kind: "hsplit"; + top: SplitTree; + bottom: SplitTree; + /** Saved fraction of the parent's height occupied by the top subtree (0..1). */ + topFraction: number; + }; + +export interface RectPane { + index: number; + x: number; + y: number; + width: number; + height: number; +} + +export function buildSplitTree(panes: Pane[]): SplitTree { + const rects: RectPane[] = panes.map((p) => ({ + index: p.index, + x: p.pixel_frame.x, + y: p.pixel_frame.y, + width: p.pixel_frame.width, + height: p.pixel_frame.height, + })); + return divideRects(rects); +} + +function divideRects(rects: RectPane[]): SplitTree { + if (rects.length === 1) { + return { kind: "leaf", savedPaneIndex: rects[0].index }; + } + + const minX = Math.min(...rects.map((r) => r.x)); + const maxX = Math.max(...rects.map((r) => r.x + r.width)); + const minY = Math.min(...rects.map((r) => r.y)); + const maxY = Math.max(...rects.map((r) => r.y + r.height)); + + // Try a vertical split — find an x that cleanly separates the rects. + const candidateXs = [...new Set(rects.flatMap((r) => [r.x, r.x + r.width]))] + .filter((x) => x > minX + EDGE_TOLERANCE_PX && x < maxX - EDGE_TOLERANCE_PX) + .sort((a, b) => a - b); + for (const splitX of candidateXs) { + const left = rects.filter((r) => r.x + r.width <= splitX + EDGE_TOLERANCE_PX); + const right = rects.filter((r) => r.x >= splitX - EDGE_TOLERANCE_PX); + if (left.length + right.length === rects.length && left.length > 0 && right.length > 0) { + return { + kind: "vsplit", + left: divideRects(left), + right: divideRects(right), + leftFraction: (splitX - minX) / (maxX - minX), + }; + } + } + + // Fall back to horizontal split. + const candidateYs = [...new Set(rects.flatMap((r) => [r.y, r.y + r.height]))] + .filter((y) => y > minY + EDGE_TOLERANCE_PX && y < maxY - EDGE_TOLERANCE_PX) + .sort((a, b) => a - b); + for (const splitY of candidateYs) { + const top = rects.filter((r) => r.y + r.height <= splitY + EDGE_TOLERANCE_PX); + const bottom = rects.filter((r) => r.y >= splitY - EDGE_TOLERANCE_PX); + if (top.length + bottom.length === rects.length && top.length > 0 && bottom.length > 0) { + return { + kind: "hsplit", + top: divideRects(top), + bottom: divideRects(bottom), + topFraction: (splitY - minY) / (maxY - minY), + }; + } + } + + throw new Error( + `Pane layout is not representable as nested binary splits (${rects.length} rects). ` + + "This usually means the saved layout was modified after capture." + ); +} + +/** + * Walk the split tree and recreate the layout in cmux. After EACH split we resize the + * just-created border to match the saved fraction — at that moment only two panes share + * that border, so cmux's `resize-pane` can move it freely. This is critical because once + * deeper splits exist, `pane.resize` rejects requests with "no adjacent border" for any + * border that isn't directly between this pane and one sibling pane in the binary tree. + * + * Doing the resize at split time means we never need a global convergence loop afterward. + */ +async function applyTree( + tree: SplitTree, + anchorSurface: string, + workspaceRef: string, + map: Map<number, string> +): Promise<void> { + if (tree.kind === "leaf") { + const layout = await paneList(workspaceRef); + const pane = layout.panes.find((p) => p.surface_refs.includes(anchorSurface)); + if (!pane) { + throw new Error(`Could not locate pane containing surface ${anchorSurface}`); + } + logger.debug({ anchor: anchorSurface, paneRef: pane.ref, savedIndex: tree.savedPaneIndex }, "[restore] leaf"); + map.set(tree.savedPaneIndex, pane.ref); + return; + } + + const direction = tree.kind === "vsplit" ? "right" : "down"; + const split = await splitFromSurface(direction, anchorSurface, workspaceRef); + logger.debug( + { direction, anchor: anchorSurface, newPane: split.pane_ref, newSurface: split.surface_ref }, + "[restore] split" + ); + + await resizeNewBorder(tree, anchorSurface, split.pane_ref, workspaceRef); + + if (tree.kind === "vsplit") { + await applyTree(tree.left, anchorSurface, workspaceRef, map); + await applyTree(tree.right, split.surface_ref, workspaceRef, map); + return; + } + + await applyTree(tree.top, anchorSurface, workspaceRef, map); + await applyTree(tree.bottom, split.surface_ref, workspaceRef, map); +} + +/** + * Resize the brand-new border between `anchorSurface`'s pane and the just-split-off + * `newPaneRef` until the saved fraction is reached (within 1 cell). cmux's `resize-pane` + * `--amount` is in PIXELS — not cells, despite the "tmux-compatible alias" framing — and + * each call doesn't necessarily move the border by exactly `amount` pixels (cmux clamps + * to neighbour minimum sizes and rounds to whole cells), so we re-read after each call + * and loop. We always resize the NEW pane: its border opposite the workspace edge IS the + * split boundary we just created, which means cmux always sees an "adjacent border" to + * move (no `invalid_state: no adjacent border` errors). + */ +async function resizeNewBorder( + tree: Exclude<SplitTree, { kind: "leaf" }>, + anchorSurface: string, + newPaneRef: string, + workspaceRef: string, +): Promise<void> { + const MAX_ATTEMPTS = 8; + let lastDelta = Number.POSITIVE_INFINITY; + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) { + const layout = await paneList(workspaceRef); + const oldPane = layout.panes.find((p) => p.surface_refs.includes(anchorSurface)); + const newPane = layout.panes.find((p) => p.ref === newPaneRef); + if (!oldPane || !newPane) { + logger.warn( + { anchorSurface, newPaneRef, kind: tree.kind }, + "[restore] could not locate split pair — aborting resize", + ); + return; + } + + // We pick which pane to resize based on direction. cmux's `resize-pane <dir>` + // requires the pane to have a *neighbor* in that direction: + // -L on a left-edge pane errors ("no adjacent border in direction left") + // -D on a bottom-edge pane errors ("no adjacent border in direction down") + // After a fresh split, the NEW pane is on the right/bottom. So: + // • Move the border to the LEFT (shrink old / grow new) → -L on NEW + // • Move the border to the RIGHT (grow old / shrink new) → -R on OLD + // • Move the border UP (shrink old top / grow new bottom) → -U on NEW + // • Move the border DOWN (grow old top / shrink new bottom) → -D on OLD + // This way the chosen pane is always the one with a guaranteed neighbor in the + // resize direction. + if (tree.kind === "vsplit") { + const totalCols = oldPane.columns + newPane.columns; + const targetOldCols = Math.round(totalCols * tree.leftFraction); + const deltaCells = oldPane.columns - targetOldCols; + if (Math.abs(deltaCells) <= 1) { + return; + } + if (Math.abs(deltaCells) >= lastDelta) { + logger.warn( + { newPane: newPane.ref, deltaCells, lastDelta, attempt }, + "[restore] vsplit resize made no progress — bailing", + ); + return; + } + lastDelta = Math.abs(deltaCells); + const target = deltaCells > 0 ? newPane : oldPane; + const dir = deltaCells > 0 ? "-L" : "-R"; + const cellWidthPx = oldPane.cell_width_px || newPane.cell_width_px || 8; + const amountPx = Math.max(1, Math.abs(deltaCells) * cellWidthPx); + logger.debug( + { + targetPane: target.ref, + dir, + amountPx, + deltaCells, + oldCols: oldPane.columns, + newCols: newPane.columns, + targetCols: targetOldCols, + fraction: tree.leftFraction, + }, + "[restore] vsplit resize", + ); + const moved = await tryResize(workspaceRef, target.ref, dir, amountPx); + if (!moved) { + return; + } + continue; + } + + const totalRows = oldPane.rows + newPane.rows; + const targetOldRows = Math.round(totalRows * tree.topFraction); + const deltaCells = oldPane.rows - targetOldRows; + if (Math.abs(deltaCells) <= 1) { + return; + } + if (Math.abs(deltaCells) >= lastDelta) { + logger.warn( + { newPane: newPane.ref, deltaCells, lastDelta, attempt }, + "[restore] hsplit resize made no progress — bailing", + ); + return; + } + lastDelta = Math.abs(deltaCells); + const target = deltaCells > 0 ? newPane : oldPane; + const dir = deltaCells > 0 ? "-U" : "-D"; + const cellHeightPx = oldPane.cell_height_px || newPane.cell_height_px || 17; + const amountPx = Math.max(1, Math.abs(deltaCells) * cellHeightPx); + logger.debug( + { + targetPane: target.ref, + dir, + amountPx, + deltaCells, + oldRows: oldPane.rows, + newRows: newPane.rows, + targetRows: targetOldRows, + fraction: tree.topFraction, + }, + "[restore] hsplit resize", + ); + const moved = await tryResize(workspaceRef, target.ref, dir, amountPx); + if (!moved) { + return; + } + } + logger.warn({ tree: tree.kind }, "[restore] split resize loop exhausted attempts"); +} + +async function tryResize( + workspaceRef: string, + paneRef: string, + direction: "-L" | "-R" | "-U" | "-D", + amount: number, +): Promise<boolean> { + try { + await runCmuxOk([ + "resize-pane", + "--workspace", + workspaceRef, + "--pane", + paneRef, + direction, + "--amount", + String(amount), + ]); + return true; + } catch (error) { + logger.warn( + { error, paneRef, direction, amount }, + "[restore] split-time resize failed", + ); + return false; + } +} + +async function populatePane( + savedPane: Pane, + paneRef: string, + workspaceRef: string, + opts: RestoreOptions +): Promise<void> { + const expectedCount = savedPane.surfaces.length; + if (expectedCount === 0) { + return; + } + + const currentLayout = await paneList(workspaceRef); + const current = currentLayout.panes.find((p) => p.ref === paneRef); + if (!current) { + throw new Error(`Pane ${paneRef} disappeared mid-restore`); + } + const surfaceRefs = [...current.surface_refs]; + + while (surfaceRefs.length < expectedCount) { + const nextSavedSurface = savedPane.surfaces[surfaceRefs.length]; + // Use CLI `cmux new-surface` instead of raw RPC `surface.create` — the V1 RPC + // ignores its explicit `pane`/`workspace` params and creates the surface in the + // currently focused pane (same routing-bug class as `surface.split`). The CLI + // routes through V2 and honors the params, so additional tabs land in the + // correct pane instead of all stacking into the anchor. + const args = [ + "new-surface", + "--workspace", + workspaceRef, + "--pane", + paneRef, + "--type", + nextSavedSurface.type, + ]; + if (nextSavedSurface.type === "browser" && nextSavedSurface.url) { + args.push("--url", nextSavedSurface.url); + } + const created = await runCmuxJSON<{ surface_ref: string; pane_ref: string }>(args); + if (created.pane_ref !== paneRef) { + logger.warn( + { requested: paneRef, got: created.pane_ref, surfaceRef: created.surface_ref }, + "[restore] new-surface landed in unexpected pane", + ); + } + surfaceRefs.push(created.surface_ref); + } + + // Rename + replay + for (let i = 0; i < expectedCount; i += 1) { + const savedSurface = savedPane.surfaces[i]; + const surfaceRef = surfaceRefs[i]; + if (savedSurface.title) { + await runCmuxOk([ + "rename-tab", + "--workspace", + workspaceRef, + "--surface", + surfaceRef, + savedSurface.title, + ]).catch((error) => { + logger.debug({ error, surfaceRef }, "[restore] rename-tab failed"); + }); + } + if (savedSurface.type === "terminal") { + await replayTerminal(savedSurface, workspaceRef, surfaceRef, opts); + } + } +} + +async function splitFromSurface( + direction: "right" | "down", + surfaceRef: string, + workspaceRef: string +): Promise<SurfaceSplitResult> { + return runCmuxJSON<SurfaceSplitResult>([ + "new-split", + direction, + "--workspace", + workspaceRef, + "--surface", + surfaceRef, + ]); +} + +function shellQuote(path: string): string { + return `'${path.replace(/'/g, "'\\''")}'`; +} + +async function replayTerminal( + surface: Surface & { type: "terminal" }, + workspaceRef: string, + surfaceRef: string, + opts: RestoreOptions +): Promise<void> { + if (!opts.replay) { + if (surface.cwd) { + await runCmuxOk([ + "send", + "--workspace", + workspaceRef, + "--surface", + surfaceRef, + `cd -- ${shellQuote(surface.cwd)}\n`, + ]); + } + return; + } + + // Build a single shell pipeline that: + // 1. cd's to the saved cwd (silently — failures don't abort) + // 2. clears the screen AND scrollback (\033[2J\033[3J\033[H), erasing both the + // shell's startup banner and the typed-input echo of this very command + // 3. base64-decodes the saved screen contents to stdout, faithfully reproducing + // what the pane looked like when the profile was saved + // Then, after the trailing newline, the saved last-typed command is sent (without + // a newline) so it sits queued at the fresh prompt for the user to confirm — this + // is what re-launches `claude --resume <id>`, `vim file`, etc. + const parts: string[] = []; + if (surface.cwd) { + parts.push(`cd -- ${shellQuote(surface.cwd)} 2>/dev/null`); + } + if (surface.screen?.text) { + const b64 = Buffer.from(surface.screen.text, "utf8").toString("base64"); + parts.push("printf '\\033[2J\\033[3J\\033[H'"); + parts.push(`printf %s '${b64}' | base64 -d`); + } + let payload = parts.length > 0 ? `${parts.join("; ")}\n` : ""; + if (surface.command && surface.command_source && surface.command_source !== "none") { + payload += surface.command; + } + if (!payload) { + return; + } + await runCmuxOk(["send", "--workspace", workspaceRef, "--surface", surfaceRef, payload]); +} diff --git a/src/cmux/lib/shell-probe.ts b/src/cmux/lib/shell-probe.ts new file mode 100644 index 0000000000..bfecc87688 --- /dev/null +++ b/src/cmux/lib/shell-probe.ts @@ -0,0 +1,166 @@ +import { homedir } from "node:os"; +import { join } from "node:path"; +import logger from "@app/logger"; +import { runCmux } from "@app/cmux/lib/cli"; +import type { CommandSource, ScreenSnapshot } from "@app/cmux/lib/types"; + +/** + * cmux exposes no PID/tty for surfaces, but it does set tab titles from OSC-7 cwd escapes. + * Idle shells get titles like "…/Tresors/Projects/ReservineBack" — the leading "…" stands + * for $HOME. TUIs (claude, vim) overwrite the title with their own text, so we only treat + * a title as a cwd when it starts with "/" or "…/". + */ +export function cwdFromTitle(title: string | undefined | null): string | undefined { + if (!title) { + return undefined; + } + const trimmed = title.trim(); + // OSC-7 / OSC-1337 titles: "user@host:/abs/path" or "user@host:~/path". The path + // can contain spaces (use `.+$` not `\S+`), but only treat the suffix as a cwd + // when it actually looks like a path — otherwise titles like `user@host:build` + // would round-trip as `cd build` on restore. + const userHostMatch = trimmed.match(/^[^\s@:]+@[^\s:]+:(.+)$/); + if (userHostMatch) { + const suffix = userHostMatch[1]; + if (isPathLike(suffix)) { + return expandHome(suffix); + } + return undefined; + } + if (isPathLike(trimmed)) { + return expandHome(trimmed); + } + return undefined; +} + +function isPathLike(value: string): boolean { + if (value === "~" || value === "…") { + return true; + } + return value.startsWith("/") || value.startsWith("~/") || value.startsWith("…/"); +} + +function expandHome(path: string): string { + if (path.startsWith("…/") || path.startsWith("~/")) { + return join(homedir(), path.slice(2)); + } + if (path === "~" || path === "…") { + return homedir(); + } + return path; +} + +/** + * Patterns we recognise as shell prompts followed by a typed command. Each pattern's + * capture group 1 is the command portion, or `undefined` if the prompt is empty. + * + * We deliberately only match prompts that include directory/git/host context. Bare-glyph + * prompts (`❯ cmd`, `$ cmd`) are excluded because terminal TUIs (Claude Code, Codex + * Forge, etc.) use the same glyphs for their chat input boxes — capturing the user's + * typed chat text as a "shell command" and replaying it on restore would be wrong and + * surprising. Users with bare-glyph shells lose command capture but can hand-edit the + * profile JSON with `command_source: "manual"` if they want it back. + */ +const PROMPT_PATTERNS: RegExp[] = [ + // oh-my-zsh robbyrussell. Every part of the prompt prefix (git suffix, ✗ dirty-tree + // mark, trailing command) is optional so "➜ app git:(main) ✗" with no command + // yields capture-group 1 === undefined, which the parser skips as an empty prompt. + /^➜\s+\S+(?:\s+git:\([^)]*\))?(?:\s+✗)?(?:\s+(.*?))?\s*$/u, + // [user@host dir]$ <command> + /^\[[^\]]+\]\s*[$#%]\s+(\S.*?)\s*$/u, + // user@host:dir$ <command> (typical bash) + /^[\w.\-]+@[\w.\-]+:\S*[$#%]\s+(\S.*?)\s*$/u, +]; + +interface CommandHint { + value: string | undefined; + source: CommandSource; +} + +const NO_COMMAND: CommandHint = { value: undefined, source: "none" }; + +export function lastCommandFromCapture(text: string | undefined | null): CommandHint { + if (!text) { + return NO_COMMAND; + } + const lines = text.split("\n").map((line) => line.replace(/\s+$/u, "")); + for (let i = lines.length - 1; i >= 0; i -= 1) { + const line = lines[i]; + if (!line) { + continue; + } + for (const pattern of PROMPT_PATTERNS) { + const match = line.match(pattern); + if (match?.[1]) { + return { value: match[1], source: "scrollback" }; + } + } + } + return NO_COMMAND; +} + +export interface SurfaceCaptureResult { + screen?: ScreenSnapshot; + command: CommandHint; +} + +/** + * Capture rendered terminal text from a single surface via `cmux capture-pane` (V2 routing). + * Raw socket `surface.read_text` is affected by the V1 routing bug — it returns the + * focused surface's content regardless of the param — so we shell out to the CLI which + * routes per-surface correctly. + * + * The CLI's `--scrollback` flag does NOT actually include scrollback in cmux 0.63.2 + * (see upstream issue) — it returns the same visible content as plain `capture-pane`. + * That means the captured command can only come from the visible area: shell panes + * with a recent prompt are captured fine; long-running Claude/vim sessions whose + * launching `claude --resume <id>` has scrolled past the visible 40-ish rows will + * yield no `command`. Users can hand-edit the profile JSON with `command_source: "manual"` + * to add the right command for those panes. + */ +export async function captureSurfaceState( + workspaceRef: string, + surfaceRef: string, + options: { screen: boolean; history: boolean }, +): Promise<SurfaceCaptureResult> { + if (!options.screen && !options.history) { + return { command: NO_COMMAND }; + } + + const visible = await runCaptureSafely(workspaceRef, surfaceRef); + if (!visible) { + return { command: NO_COMMAND }; + } + + const text = visible.replace(/\s+$/u, ""); + if (!text) { + return { command: NO_COMMAND }; + } + + const screen = options.screen ? { text, rows: text.split("\n").length } : undefined; + const command = options.history ? lastCommandFromCapture(text) : NO_COMMAND; + return { screen, command }; +} + +async function runCaptureSafely(workspaceRef: string, surfaceRef: string): Promise<string | undefined> { + try { + const result = await runCmux([ + "capture-pane", + "--workspace", + workspaceRef, + "--surface", + surfaceRef, + ]); + if (result.code !== 0) { + logger.debug( + { workspaceRef, surfaceRef, stderr: result.stderr.trim() }, + "[shell-probe] capture-pane non-zero exit", + ); + return undefined; + } + return result.stdout; + } catch (error) { + logger.warn({ error, workspaceRef, surfaceRef }, "[shell-probe] capture-pane failed"); + return undefined; + } +} diff --git a/src/cmux/lib/snapshot.ts b/src/cmux/lib/snapshot.ts new file mode 100644 index 0000000000..fe725b4c3a --- /dev/null +++ b/src/cmux/lib/snapshot.ts @@ -0,0 +1,281 @@ +import { runCmux, runCmuxJSON } from "@app/cmux/lib/cli"; +import { withFocusedWorkspace } from "@app/cmux/lib/focus-guard"; +import { captureSurfaceState, cwdFromTitle } from "@app/cmux/lib/shell-probe"; +import { + browserUrl, + paneList, + type WindowEntry, + type WorkspaceEntry, + windowList, + workspaceList, +} from "@app/cmux/lib/socket"; +import type { Pane, Profile, ProfileScope, Surface, Window, Workspace } from "@app/cmux/lib/types"; +import { PROFILE_VERSION } from "@app/cmux/lib/types"; +import logger from "@app/logger"; + +interface SurfaceListEntry { + ref: string; + type: "terminal" | "browser"; + title?: string; + /** Position within the parent pane (0..N-1). Field name is `index` in the CLI's list-pane-surfaces output. */ + index: number; + /** True when this surface is the active tab of its pane. CLI calls this `selected`. */ + selected?: boolean; +} + +interface ListPaneSurfacesResponse { + surfaces: SurfaceListEntry[]; + pane_ref?: string; + workspace_ref?: string; + window_ref?: string; +} + +export interface SnapshotOptions { + name: string; + scope: ProfileScope; + targetWindowRef?: string; + targetWorkspaceRef?: string; + captureCwd: boolean; + captureScreen: boolean; + captureHistory: boolean; + note?: string; + cmuxVersion: string; +} + +export interface SnapshotProgress { + onWorkspaceStart?: (info: { ref: string; title: string; index: number; total: number }) => void; + onWorkspaceDone?: (info: { ref: string; title: string }) => void; +} + +interface CollectedWorkspace extends WorkspaceEntry { + window_ref: string; +} + +export async function captureProfile(options: SnapshotOptions, progress: SnapshotProgress = {}): Promise<Profile> { + const allWindows = await windowList(); + const allWorkspaces = await collectAllWorkspaces(allWindows); + + const ctx = await getIdentifyContext(); + const targetWorkspaces = filterWorkspaces(allWorkspaces, options, ctx.focusedWorkspaceRef); + const targetWindowRefs = new Set(targetWorkspaces.map((ws) => ws.window_ref)); + const targetWindows = allWindows.filter((w) => targetWindowRefs.has(w.ref)); + + const windowsOut: Window[] = []; + let visited = 0; + for (const window of targetWindows) { + const wsForWindow = targetWorkspaces + .filter((ws) => ws.window_ref === window.ref) + .sort((a, b) => (a.index ?? 0) - (b.index ?? 0)); + + const workspacesOut: Workspace[] = []; + let containerFrame = { width: 0, height: 0 }; + + for (const ws of wsForWindow) { + visited += 1; + const title = ws.title ?? ws.ref; + progress.onWorkspaceStart?.({ + ref: ws.ref, + title, + index: visited, + total: targetWorkspaces.length, + }); + + const captured = await withFocusedWorkspace(ws.ref, async () => { + const panes = await capturePanes(ws.ref, options, ctx.callerSurfaceRef); + const fresh = await paneList(ws.ref); + return { panes, container: fresh.container_frame }; + }); + + if (captured.container.width > 0 && captured.container.height > 0) { + containerFrame = captured.container; + } + + workspacesOut.push({ + ref: ws.ref, + title, + selected: ws.selected ?? false, + current_directory: ws.current_directory, + panes: captured.panes, + }); + + progress.onWorkspaceDone?.({ ref: ws.ref, title }); + } + + windowsOut.push({ + ref: window.ref, + title: `Window ${window.index + 1}`, + container_frame: containerFrame, + workspaces: workspacesOut, + }); + } + + return { + version: PROFILE_VERSION, + name: options.name, + scope: options.scope, + captured_at: new Date().toISOString(), + cmux_version: options.cmuxVersion, + note: options.note, + windows: windowsOut, + }; +} + +async function collectAllWorkspaces(windows: WindowEntry[]): Promise<CollectedWorkspace[]> { + const out: CollectedWorkspace[] = []; + for (const window of windows) { + const list = await workspaceList(window.ref); + for (const ws of list.workspaces) { + out.push({ ...ws, window_ref: window.ref }); + } + } + return out; +} + +interface IdentifyContext { + focusedWorkspaceRef?: string; + /** + * Surface where the save command itself is running. Capturing its visible screen + * would record `tools cmux profiles save` as the bottom-of-screen content, which + * then gets replayed verbatim into the restored pane — meta-circular and useless. + * We skip screen capture for this one surface. + */ + callerSurfaceRef?: string; +} + +async function getIdentifyContext(): Promise<IdentifyContext> { + try { + const identify = await runCmuxJSON<{ + focused?: { workspace_ref?: string }; + caller?: { surface_ref?: string }; + }>(["identify"]); + return { + focusedWorkspaceRef: identify.focused?.workspace_ref, + callerSurfaceRef: identify.caller?.surface_ref, + }; + } catch { + return {}; + } +} + +function filterWorkspaces( + all: CollectedWorkspace[], + options: SnapshotOptions, + focusedWorkspaceRef: string | undefined +): CollectedWorkspace[] { + if (options.scope === "all") { + return all; + } + if (options.scope === "window") { + const focusedWindowRef = focusedWorkspaceRef + ? all.find((ws) => ws.ref === focusedWorkspaceRef)?.window_ref + : undefined; + const ref = options.targetWindowRef ?? focusedWindowRef ?? all[0]?.window_ref; + if (!ref) { + throw new Error("scope=window requires a focused workspace or --window <ref>"); + } + const filtered = all.filter((ws) => ws.window_ref === ref); + if (filtered.length === 0 && options.targetWindowRef) { + throw new Error(`No window matches --window ${options.targetWindowRef}`); + } + return filtered; + } + const ref = options.targetWorkspaceRef ?? focusedWorkspaceRef ?? all.find((ws) => ws.selected)?.ref; + if (!ref) { + throw new Error("scope=workspace requires a focused workspace or --workspace <ref>"); + } + const filtered = all.filter((ws) => ws.ref === ref); + if (filtered.length === 0 && options.targetWorkspaceRef) { + throw new Error(`No workspace matches --workspace ${options.targetWorkspaceRef}`); + } + return filtered; +} + +async function capturePanes( + workspaceRef: string, + options: SnapshotOptions, + callerSurfaceRef: string | undefined, +): Promise<Pane[]> { + const layout = await paneList(workspaceRef); + const panes: Pane[] = []; + + for (const paneInfo of layout.panes) { + const surfacesInfo = await runCmuxJSON<ListPaneSurfacesResponse>([ + "list-pane-surfaces", + "--workspace", + workspaceRef, + "--pane", + paneInfo.ref, + ]); + + const sortedEntries = [...surfacesInfo.surfaces].sort((a, b) => a.index - b.index); + const surfaces: Surface[] = []; + let selectedIndex = 0; + for (const surfaceEntry of sortedEntries) { + if (surfaceEntry.selected) { + selectedIndex = surfaces.length; + } + surfaces.push(await captureSurface(surfaceEntry, workspaceRef, options, callerSurfaceRef)); + } + + panes.push({ + ref: paneInfo.ref, + index: paneInfo.index, + columns: paneInfo.columns, + rows: paneInfo.rows, + pixel_frame: paneInfo.pixel_frame, + selected_surface_index: selectedIndex, + surfaces, + }); + } + + return panes; +} + +async function captureSurface( + entry: SurfaceListEntry, + workspaceRef: string, + options: SnapshotOptions, + callerSurfaceRef: string | undefined, +): Promise<Surface> { + const title = entry.title ?? ""; + if (entry.type === "browser") { + const url = await browserUrl(entry.ref); + return { type: "browser", title, url: url ?? undefined }; + } + + const cwd = options.captureCwd ? cwdFromTitle(title) : undefined; + // Skip screen capture for the surface running this very save command — its + // visible content is dominated by the `tools cmux profiles save` invocation + // and the running clack prompts, which would replay back into the restored + // pane verbatim. Other panes still get full screen capture. + const isCaller = callerSurfaceRef !== undefined && entry.ref === callerSurfaceRef; + if (isCaller && options.captureScreen) { + logger.debug({ surfaceRef: entry.ref }, "[snapshot] skipping screen capture for caller surface"); + } + const captured = await captureSurfaceState(workspaceRef, entry.ref, { + screen: options.captureScreen && !isCaller, + history: options.captureHistory, + }); + + return { + type: "terminal", + title, + cwd, + screen: captured.screen, + command: captured.command.value, + command_source: captured.command.value ? captured.command.source : undefined, + }; +} + +export async function getCmuxVersion(): Promise<string> { + try { + const result = await runCmux(["--version"]); + const match = result.stdout.match(/cmux (\S+)/); + if (match) { + return match[1]; + } + } catch (error) { + logger.debug({ error }, "[snapshot] cmux version unavailable"); + } + return "unknown"; +} diff --git a/src/cmux/lib/socket.ts b/src/cmux/lib/socket.ts new file mode 100644 index 0000000000..de1fc01f02 --- /dev/null +++ b/src/cmux/lib/socket.ts @@ -0,0 +1,236 @@ +import { connect } from "node:net"; +import logger from "@app/logger"; +import { runCmuxJSON } from "@app/cmux/lib/cli"; + +interface IdentifyResponse { + socket_path: string; +} + +interface JsonRpcResponse<T> { + id: string; + ok: boolean; + result?: T; + error?: { code: string; message: string }; +} + +let cachedSocketPath: string | null = null; + +export async function getSocketPath(): Promise<string> { + if (cachedSocketPath) { + return cachedSocketPath; + } + const identify = await runCmuxJSON<IdentifyResponse>(["identify"]); + if (!identify.socket_path) { + logger.error({ identify }, "[socket] cmux identify returned no socket_path"); + throw new Error("cmux identify did not return a socket_path. Is cmux running?"); + } + cachedSocketPath = identify.socket_path; + logger.debug({ path: cachedSocketPath }, "[socket] resolved cmux socket path"); + return cachedSocketPath; +} + +export function resetSocketPathCache(): void { + cachedSocketPath = null; +} + +let requestCounter = 0; + +export async function rpc<TResult = unknown>( + method: string, + params: Record<string, unknown> = {}, + opts: { timeoutMs?: number } = {}, +): Promise<TResult> { + const path = await getSocketPath(); + const id = `cmux-${Date.now()}-${++requestCounter}`; + const payload = `${JSON.stringify({ id, method, params })}\n`; + const timeoutMs = opts.timeoutMs ?? 5_000; + + return await new Promise<TResult>((resolve, reject) => { + const sock = connect(path); + let buffer = ""; + let settled = false; + + const settle = (fn: () => void) => { + if (settled) { + return; + } + settled = true; + try { + sock.destroy(); + } catch { + // ignore + } + fn(); + }; + + const timer = setTimeout(() => { + settle(() => reject(new Error(`cmux RPC ${method} timed out after ${timeoutMs}ms`))); + }, timeoutMs); + + sock.on("error", (error) => { + clearTimeout(timer); + settle(() => reject(error)); + }); + + sock.on("connect", () => { + sock.write(payload); + }); + + sock.on("data", (chunk) => { + buffer += chunk.toString(); + const newlineIndex = buffer.indexOf("\n"); + if (newlineIndex === -1) { + return; + } + const line = buffer.slice(0, newlineIndex); + clearTimeout(timer); + try { + const parsed = JSON.parse(line) as JsonRpcResponse<TResult>; + if (!parsed.ok) { + logger.error({ method, params, error: parsed.error }, "[socket] RPC error"); + settle(() => + reject( + new Error( + `cmux RPC ${method} failed: ${parsed.error?.code ?? "unknown"} ${parsed.error?.message ?? ""}`.trim(), + ), + ), + ); + return; + } + settle(() => resolve(parsed.result as TResult)); + } catch (error) { + settle(() => reject(new Error(`Failed to parse cmux RPC response: ${error}\nLine: ${line}`))); + } + }); + }); +} + +export interface PaneListPane { + ref: string; + index: number; + surface_count: number; + surface_refs: string[]; + selected_surface_ref: string; + focused: boolean; + columns: number; + rows: number; + cell_width_px: number; + cell_height_px: number; + pixel_frame: { x: number; y: number; width: number; height: number }; +} + +export interface PaneListResponse { + workspace_ref: string; + window_ref: string; + panes: PaneListPane[]; + container_frame: { width: number; height: number }; +} + +export async function paneList(workspaceRef: string): Promise<PaneListResponse> { + return rpc<PaneListResponse>("pane.list", { workspace: workspaceRef }); +} + +export interface WindowEntry { + ref: string; + id: string; + index: number; + visible: boolean; + key: boolean; + workspace_count: number; + selected_workspace_ref?: string; +} + +export async function windowList(): Promise<WindowEntry[]> { + const result = await rpc<{ windows: WindowEntry[] }>("window.list", {}); + return result.windows; +} + +export interface WorkspaceEntry { + ref: string; + id: string; + index: number; + title?: string; + selected?: boolean; + pinned?: boolean; + current_directory?: string; +} + +export interface WorkspaceListResponse { + window_ref: string; + window_id: string; + workspaces: WorkspaceEntry[]; +} + +export async function workspaceList(windowRef?: string): Promise<WorkspaceListResponse> { + const params: Record<string, unknown> = {}; + if (windowRef) { + params.window = windowRef; + } + return rpc<WorkspaceListResponse>("workspace.list", params); +} + +export interface WorkspaceCreateResult { + workspace_ref: string; + workspace_id: string; + window_ref: string; + window_id: string; +} + +export async function workspaceCreate(opts: { + name?: string; + description?: string; + cwd?: string; + command?: string; + window?: string; +} = {}): Promise<WorkspaceCreateResult> { + const params: Record<string, unknown> = {}; + if (opts.name) { + params.name = opts.name; + } + if (opts.description) { + params.description = opts.description; + } + if (opts.cwd) { + params.cwd = opts.cwd; + } + if (opts.command) { + params.command = opts.command; + } + if (opts.window) { + params.window = opts.window; + } + return rpc<WorkspaceCreateResult>("workspace.create", params); +} + +export interface SurfaceSplitResult { + pane_ref: string; + surface_ref: string; + type: string; + workspace_ref: string; + window_ref: string; +} + +export async function surfaceSplit( + direction: "left" | "right" | "up" | "down", + surfaceRef: string, + workspaceRef: string, +): Promise<SurfaceSplitResult> { + return rpc<SurfaceSplitResult>("surface.split", { + direction, + surface: surfaceRef, + workspace: workspaceRef, + }); +} + +export async function browserUrl(surfaceRef: string): Promise<string | null> { + try { + const result = await rpc<{ url?: string } | string>("browser.url.get", { surface: surfaceRef }); + if (typeof result === "string") { + return result; + } + return result?.url ?? null; + } catch (error) { + logger.debug({ error, surfaceRef }, "[socket] browser.url.get failed"); + return null; + } +} diff --git a/src/cmux/lib/store.ts b/src/cmux/lib/store.ts new file mode 100644 index 0000000000..f6a5cc07f1 --- /dev/null +++ b/src/cmux/lib/store.ts @@ -0,0 +1,171 @@ +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + statSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { PROFILE_VERSION, type Profile, type ProfileSummary } from "@app/cmux/lib/types"; +import logger from "@app/logger"; +import { SafeJSON } from "@app/utils/json"; +import { Storage } from "@app/utils/storage"; + +const NAME_PATTERN = /^[A-Za-z0-9._-]+$/; + +export class ProfileStore { + private profilesDir: string; + + constructor(opts: { profilesDir?: string } = {}) { + if (opts.profilesDir) { + this.profilesDir = opts.profilesDir; + } else { + const storage = new Storage("cmux"); + this.profilesDir = join(storage.getBaseDir(), "profiles"); + } + } + + getProfilesDir(): string { + return this.profilesDir; + } + + pathFor(name: string): string { + if (!NAME_PATTERN.test(name)) { + throw new Error( + `Invalid profile name "${name}". Use letters, digits, dots, underscores, or dashes (no slashes).` + ); + } + return join(this.profilesDir, `${name}.json`); + } + + private ensureDir(): void { + if (!existsSync(this.profilesDir)) { + mkdirSync(this.profilesDir, { recursive: true }); + } + } + + exists(name: string): boolean { + return existsSync(this.pathFor(name)); + } + + list(): ProfileSummary[] { + if (!existsSync(this.profilesDir)) { + return []; + } + const entries = readdirSync(this.profilesDir).filter((f) => f.endsWith(".json")); + const summaries: ProfileSummary[] = []; + for (const entry of entries) { + const filePath = join(this.profilesDir, entry); + try { + const profile = readJson<Profile>(filePath); + summaries.push(summarize(profile, filePath)); + } catch (error) { + logger.warn({ filePath, error }, "[store] skipping unreadable profile"); + } + } + summaries.sort((a, b) => a.name.localeCompare(b.name)); + return summaries; + } + + read(name: string): Profile { + const path = this.pathFor(name); + if (!existsSync(path)) { + throw new ProfileNotFoundError(name, path); + } + const profile = readJson<Profile>(path); + if (profile.version !== PROFILE_VERSION) { + throw new Error( + `Profile "${name}" has version ${profile.version}; this CLI only supports version ${PROFILE_VERSION}.` + ); + } + return profile; + } + + write(name: string, profile: Profile, opts: { force?: boolean } = {}): string { + const path = this.pathFor(name); + if (existsSync(path) && !opts.force) { + throw new ProfileExistsError(name, path); + } + this.ensureDir(); + const normalized: Profile = { ...profile, name, version: PROFILE_VERSION }; + const tmpPath = `${path}.tmp.${process.pid}`; + writeFileSync(tmpPath, `${SafeJSON.stringify(normalized, null, 2)}\n`, "utf8"); + renameSync(tmpPath, path); + return path; + } + + delete(name: string): boolean { + const path = this.pathFor(name); + if (!existsSync(path)) { + return false; + } + unlinkSync(path); + return true; + } + + summarize(profile: Profile): ProfileSummary { + return summarize(profile, this.pathFor(profile.name)); + } +} + +export class ProfileNotFoundError extends Error { + constructor( + public readonly name: string, + public readonly path: string + ) { + super(`No profile named "${name}" at ${path}`); + this.name = "ProfileNotFoundError"; + } +} + +export class ProfileExistsError extends Error { + constructor( + public readonly profileName: string, + public readonly path: string + ) { + super(`Profile "${profileName}" already exists at ${path}. Use --force to overwrite.`); + this.name = "ProfileExistsError"; + } +} + +function readJson<T>(path: string): T { + const raw = readFileSync(path, "utf8"); + return SafeJSON.parse(raw) as T; +} + +function summarize(profile: Profile, path: string): ProfileSummary { + let workspaces = 0; + let panes = 0; + let surfaces = 0; + for (const window of profile.windows) { + workspaces += window.workspaces.length; + for (const ws of window.workspaces) { + panes += ws.panes.length; + for (const pane of ws.panes) { + surfaces += pane.surfaces.length; + } + } + } + let bytes = 0; + try { + bytes = statSync(path).size; + } catch { + // file may not exist yet; bytes stays 0 + } + return { + name: profile.name, + captured_at: profile.captured_at, + scope: profile.scope, + note: profile.note, + cmux_version: profile.cmux_version, + windows: profile.windows.length, + workspaces, + panes, + surfaces, + bytes, + path, + }; +} diff --git a/src/cmux/lib/types.ts b/src/cmux/lib/types.ts new file mode 100644 index 0000000000..be505dbd8c --- /dev/null +++ b/src/cmux/lib/types.ts @@ -0,0 +1,101 @@ +export const PROFILE_VERSION = 1; + +export type ProfileScope = "all" | "window" | "workspace"; + +export type CommandSource = "scrollback" | "manual" | "none"; + +export interface ScreenSnapshot { + /** Raw rendered text returned by `cmux capture-pane` at save time. ANSI-stripped. */ + text: string; + /** Number of rendered rows captured (for display in `view`). */ + rows: number; +} + +export interface PixelFrame { + x: number; + y: number; + width: number; + height: number; +} + +export interface ContainerFrame { + width: number; + height: number; +} + +export interface TerminalSurface { + type: "terminal"; + title: string; + cwd?: string; + /** + * Visible terminal content captured at save time. On restore the new pane is + * cleared and this text is printed back so the pane looks exactly like it did + * when saved (login banner, previous prompts, last command, etc.). + */ + screen?: ScreenSnapshot; + /** + * Most recent shell-prompt+command line found in scrollback at save time. On restore + * this is *typed but not executed* at the new prompt (no trailing newline) so the + * user can review and press Enter — useful for re-launching TUIs like + * `claude --resume <id>` that don't show up cleanly in screen replay. + */ + command?: string; + command_source?: CommandSource; +} + +export interface BrowserSurface { + type: "browser"; + title: string; + url?: string; +} + +export type Surface = TerminalSurface | BrowserSurface; + +export interface Pane { + ref: string; + index: number; + columns: number; + rows: number; + pixel_frame: PixelFrame; + selected_surface_index: number; + surfaces: Surface[]; +} + +export interface Workspace { + ref: string; + title: string; + selected: boolean; + current_directory?: string; + panes: Pane[]; +} + +export interface Window { + ref: string; + title: string; + container_frame: ContainerFrame; + workspaces: Workspace[]; +} + +export interface Profile { + version: typeof PROFILE_VERSION; + name: string; + scope: ProfileScope; + captured_at: string; + cmux_version: string; + note?: string; + windows: Window[]; +} + +export interface ProfileSummary { + name: string; + captured_at: string; + scope: ProfileScope; + note?: string; + cmux_version: string; + windows: number; + workspaces: number; + panes: number; + surfaces: number; + bytes: number; + path: string; +}