diff --git a/CHANGELOG.md b/CHANGELOG.md index 36535428a..c81ed2e0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ [English](CHANGELOG.md) · [Русский](CHANGELOG.ru.md) · [简体中文](CHANGELOG.zh-CN.md) +## Unreleased + +- **Agents you launch run as your terminal would run them.** The OS isolation layer (macOS `sandbox-exec`, Linux bubblewrap) now wraps only subagents, plugin-started agents and the auto of a CLI without an auto mode of its own (its approval bypass). Before, it wrapped every agent outside Manual, and Claude Code's Bash tool and external editor failed with `EPERM`: Claude keeps their files in `/tmp/claude-` whatever `TMPDIR` says. Inside the layer Claude Code may now write that folder. Base protection is unchanged and still on by default. +- CanvasTTY no longer switches Claude Code's own sandbox on in Auto; it follows the person's Claude settings. +- **Settings → Keyboard → Claude editor** (macOS): rebindable keys for Claude Code cards, like the Codex editor. While Claude's prompt box is on screen, Enter breaks the line and Command+Enter submits; in dialogs, confirmations and other screens Enter keeps its usual meaning, and Shift+Enter always breaks the line. Command+A selects the whole draft, then Command+C, Command+X, Delete or typing copy, cut, delete or replace it, and the terminal Paste key replaces it. Submit, line break and select always keep a key; copy, cut and delete can be switched off. Changes apply at once in open cards. The **Claude draft keys** switch at the top of the group (on by default) turns all of it off: the keys reach Claude as they are (Enter submits), and new Claude sessions start with the person's own editor instead of CanvasTTY's `VISUAL`. +- **Settings → Keyboard → Codex editor** (macOS): the keys are now really rebindable, and the owned Codex frontend reads them. Defaults match the Claude editor: Command+Enter submits (or queues, and picks a `/` command), Enter and Shift+Enter break the line, Command+A selects the whole draft, and Command+C, Command+X and Delete copy, cut or delete a selected draft (selected terminal output still copies with the terminal's Copy key). The separate alternate and Command submit rows are gone. Settings still at the old Codex defaults take the new ones; customized submit and line-break keys are kept. Copy, cut and delete can be switched off. A plain Enter that no key uses keeps Codex's own submit; dialogs and embedded editors keep their keys. Changes apply to new or restarted Codex cards. Linux and Windows are unchanged. + ## 1.8.1 - Fixed the Files reader rejecting all regular files on macOS: `/dev/fd` device paths are not treated as resolved file targets, and the opened file's identity is checked against its current path before reading. The 1.8.0 build was not published. diff --git a/CHANGELOG.ru.md b/CHANGELOG.ru.md index 4904afd26..eccf2eb3b 100644 --- a/CHANGELOG.ru.md +++ b/CHANGELOG.ru.md @@ -2,6 +2,13 @@ [English](CHANGELOG.md) · [Русский](CHANGELOG.ru.md) · [简体中文](CHANGELOG.zh-CN.md) +## Не выпущено + +- **Агенты, которых вы запускаете сами, работают так же, как в вашем терминале.** Слой изоляции ОС (macOS `sandbox-exec`, Linux bubblewrap) теперь оборачивает только субагентов, агентов, запущенных плагинами, и auto у CLI без собственного авторежима (его обход подтверждений). Раньше он оборачивал любого агента не в Manual, и у Claude Code падали Bash и внешний редактор с `EPERM`: Claude хранит их файлы в `/tmp/claude-`, что бы ни стояло в `TMPDIR`. Внутри слоя Claude Code теперь может писать в эту папку. Базовая защита не изменилась и по-прежнему включена по умолчанию. +- CanvasTTY больше не включает собственную песочницу Claude Code в Auto: она следует настройкам Claude у человека. +- **Настройки → Горячие клавиши → Редактор Claude** (macOS): переназначаемые клавиши для карточек Claude Code, как у редактора Codex. Пока на экране видно поле ввода Claude, Enter переносит строку, а Command+Enter отправляет; в диалогах, подтверждениях и на других экранах Enter работает как обычно, а Shift+Enter всегда переносит строку. Command+A выделяет весь черновик, затем Command+C, Command+X, Delete или набор текста копируют, вырезают, удаляют или заменяют его, а клавиша «Вставить» терминала заменяет его вставкой. У отправки, переноса строки и выделения клавиша есть всегда; копирование, вырезание и удаление можно отключить. Изменения сразу действуют в открытых карточках. Переключатель **Клавиши черновика Claude** вверху группы (по умолчанию включён) выключает всё это: клавиши уходят в Claude как есть (Enter отправляет), а новые сессии Claude запускаются с редактором человека вместо `VISUAL` от CanvasTTY. +- **Настройки → Горячие клавиши → Редактор Codex** (macOS): клавиши теперь действительно переназначаются, и собственный фронтенд Codex их читает. Умолчания как у редактора Claude: Command+Enter отправляет (или ставит в очередь и выбирает команду `/`), Enter и Shift+Enter переносят строку, Command+A выделяет весь черновик, а Command+C, Command+X и Delete копируют, вырезают или удаляют выделенный черновик (выделенный вывод терминала по-прежнему копируется клавишей копирования терминала). Отдельных строк дополнительной отправки и отправки по Command больше нет. Настройки со старыми умолчаниями Codex получают новые; изменённые клавиши отправки и переноса сохраняются. Копирование, вырезание и удаление можно отключить. Обычный Enter, не занятый ни одной клавишей, остаётся отправкой Codex; диалоги и встроенные редакторы сохраняют свои клавиши. Изменения действуют в новых или перезапущенных карточках Codex. Linux и Windows не меняются. + ## 1.8.1 - Исправлен запрет чтения обычных файлов на macOS: пути устройств `/dev/fd` больше не считаются адресами самих файлов; перед чтением проверяется идентичность открытого файла и текущего пути. Сборка 1.8.0 не была опубликована. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index fda65adbf..d77c9c9cd 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -2,6 +2,13 @@ [English](CHANGELOG.md) · [Русский](CHANGELOG.ru.md) · [简体中文](CHANGELOG.zh-CN.md) +## 未发布 + +- **你自己启动的智能体按你的终端方式运行。** 操作系统隔离层(macOS `sandbox-exec`,Linux bubblewrap)现在只包裹子智能体、插件启动的智能体,以及没有自带自动模式的 CLI 的 auto(其跳过审批)。此前它包裹所有非 Manual 的智能体,导致 Claude Code 的 Bash 工具和外部编辑器以 `EPERM` 失败:无论 `TMPDIR` 如何,Claude 都把这些文件放在 `/tmp/claude-`。现在隔离层内的 Claude Code 可以写入该文件夹。基础防护不变,仍默认开启。 +- CanvasTTY 不再在 Auto 中开启 Claude Code 自身的沙箱,改为遵循用户的 Claude 设置。 +- **设置 → 键盘 → Claude 编辑器**(macOS):为 Claude Code 卡片提供可重新绑定的按键,与 Codex 编辑器相同。当屏幕上显示 Claude 的输入框时,Enter 换行,Command+Enter 发送;在对话框、确认提示和其他界面中 Enter 保持原有含义,Shift+Enter 始终换行。Command+A 选中整段草稿,随后 Command+C、Command+X、Delete 或直接输入会复制、剪切、删除或替换它,终端的粘贴键会用粘贴内容替换它。发送、换行和全选始终保留按键;复制、剪切和删除可以关闭。修改会立即作用于已打开的卡片。分组顶部的 **Claude 草稿按键** 开关(默认开启)可关闭以上全部功能:按键原样发送给 Claude(Enter 发送),新的 Claude 会话使用用户自己的编辑器,而不是 CanvasTTY 的 `VISUAL`。 +- **设置 → 键盘 → Codex 编辑器**(macOS):按键现在可以真正重新绑定,自带的 Codex 前端会读取它们。默认值与 Claude 编辑器一致:Command+Enter 发送(或加入队列,并选择 `/` 命令),Enter 和 Shift+Enter 换行,Command+A 选中整个草稿,Command+C、Command+X 和 Delete 复制、剪切或删除已选中的草稿(选中的终端输出仍用终端的复制键复制)。不再有单独的备用发送和 Command 发送行。仍为旧 Codex 默认值的设置会改用新默认值;自定义的发送和换行按键会保留。复制、剪切和删除可以关闭。未被任何按键占用的普通 Enter 仍是 Codex 自身的发送;对话框和内嵌编辑器保留各自的按键。更改对新建或重启的 Codex 卡片生效。Linux 和 Windows 不变。 + ## 1.8.1 - 修复 macOS 拒绝读取所有普通文件的问题:不再将 `/dev/fd` 设备路径当作文件实际路径,读取前核对已打开文件与当前路径的身份。1.8.0 构建未发布。 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index aa004a203..24ab7d8cf 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -142,7 +142,7 @@ Terminal cards subscribe before requesting a fresh `terminal:read-buffer` snapsh Terminal pointer coordinates are converted from the canvas's visually transformed rectangle back to xterm layout coordinates before selection or wheel handling. Terminal and canvas wheel direction are normalized independently from persisted settings. Clipboard, scrollback search, page scrolling and exited-session restart use the configured terminal shortcuts. Clipboard text enters xterm through `Terminal.paste` rather than synthetic keystrokes. Codex terminals preserve every combination of Shift, Alt, Ctrl, and Super on modified Enter through CSI-u on every platform; unbound plain Enter stays a carriage return, and the CLI decides what each key does. -General Settings owns macOS, Windows, Linux and Custom keyboard presets, with editable canvas, terminal and Codex shortcuts directly below the preset. New profiles use host defaults; existing bindings migrate to Custom. A named preset replaces bindings, and an individual edit selects Custom. SettingsStore validates bindings and duplicates by dispatch context. TerminalManager passes only native Codex editor bindings to the optional frontend through `CANVASTTY_CODEX_KEYBOARD` and publishes the launch snapshot in `SessionMetadata.nativeEditor`. TerminalCard uses that snapshot to encode editor keys with modifiers; changing settings updates canvas/terminal actions immediately but requires a new or restarted process for editor bindings. Ordinary CLI launches retain their own editor keymaps. +General Settings owns macOS, Windows, Linux and Custom keyboard presets, with editable canvas, terminal and Codex shortcuts directly below the preset. New profiles use host defaults; existing bindings migrate to Custom. A named preset replaces bindings, and an individual edit selects Custom. SettingsStore validates bindings and duplicates by dispatch context. TerminalManager passes only native Codex editor bindings to the optional frontend through `CANVASTTY_CODEX_KEYBOARD` (on macOS `submit`, `newline`, `newlineAlternate`, `selectAll`, `copy`, `cut`, `clear`, read once at startup by the owned frontend for the main and startup drafts, which keeps a plain Enter no key uses as Codex's submit and leaves dialogs alone; on Linux `submit`, `submitAlternate`, `submitSuper`, `newline`, `selectAll` as before) and publishes the launch snapshot in `SessionMetadata.nativeEditor`. TerminalCard uses that snapshot to encode editor keys with modifiers; changing settings updates canvas/terminal actions immediately but requires a new or restarted process for editor bindings. Ordinary CLI launches retain their own editor keymaps. On macOS the `claude*` bindings (their own dispatch context) are read live by TerminalCard: while Claude's prompt box is on screen (the rows between its last two rules) the submit key sends `\r` and the line-break key sends Shift+Enter, and the whole-draft keys act through `TerminalManager.draftAction`. The `claudeDraftKeysEnabled` setting turns them off; the draft helper `VISUAL` is given only to Claude sessions started while it is on. Application shortcuts are normalized in `SettingsStore`, matched in `App`, and rendered from the same persisted bindings in the canvas hint. `App` owns the exclusive selected canvas application and the selected terminal session used by window actions such as rename. `TerminalCard` owns xterm focus and only the inline editor; `BrowserService` owns native page focus. Alt+arrow canvas focus navigation yields to terminal surfaces and editable fields on every platform, before preventing the key event, so agent TUIs receive their own shortcuts. Pressing empty canvas clears either selection. Optional hover focus uses the same configured entry/exit delay for terminals and the built-in browser; focus-in/focus-out sequences produced by a terminal's programmatic transition are suppressed before PTY input so agent TUIs do not reset their history position. diff --git a/docs/UI_CONTRACT.md b/docs/UI_CONTRACT.md index 7acaf490d..73f6aa368 100644 --- a/docs/UI_CONTRACT.md +++ b/docs/UI_CONTRACT.md @@ -56,7 +56,7 @@ This contract preserves the approved MVP concept and prevents feature ownership - Terminal cards switch to semantic summary mode below `0.5×`. Summary typography counter-scales as the camera moves farther out so identical cards keep the same readable hierarchy instead of exposing tiny xterm text. - In semantic summary mode, clicking a card still selects it with a visible outline and camera focus follows only the configured Off/Single click/Double click mode. Renderer, xterm, and plugin cards follow the same wheel focus matrix as normal scale: only a focused input-bearing card can keep wheel in Off or released-Key mode; On, an active Key binding, or the held full navigation override gives it to the canvas. A Browser summary or other non-native placeholder is always canvas-owned for wheel/pinch. - Every terminal edge and corner is a resize target. The minimum card size is `420 × 260`; resizing updates the xterm viewport and preserves the opposite edge. -- Live terminal selection follows the visible pointer position at every canvas zoom. Copy and paste use the selected preset's editable terminal bindings: Linux defaults to `Ctrl+C`/`Ctrl+Shift+V`, Windows to `Ctrl+Shift+C`/`Ctrl+Shift+V`, and macOS to `Cmd+C`/`Cmd+V`. Plain `Ctrl+C` without a selection retains the PTY interrupt. Presets use Enter to submit and Shift+Enter for a newline in the optional Codex editor; other CLIs retain their editor policies. +- Live terminal selection follows the visible pointer position at every canvas zoom. Copy and paste use the selected preset's editable terminal bindings: Linux defaults to `Ctrl+C`/`Ctrl+Shift+V`, Windows to `Ctrl+Shift+C`/`Ctrl+Shift+V`, and macOS to `Cmd+C`/`Cmd+V`. Plain `Ctrl+C` without a selection retains the PTY interrupt. In the optional Codex editor macOS uses Cmd+Enter to submit and Enter or Shift+Enter for a newline; Linux and Windows presets use Enter to submit and Shift+Enter for a newline; other CLIs retain their editor policies. - Controls includes an off-by-default **Copy on selection** setting, persisted and applied immediately to every agent and terminal, including fullscreen cards. Completing a non-empty mouse selection copies its text to the system clipboard without clearing the highlight; search results and cleared selections do not copy. With the setting enabled, Shift forces text selection in mouse-reporting TUIs on all desktop platforms; on macOS the terminal mouse adapter translates it to xterm's Option selection without taking the canvas's Option navigation binding. - Canvas plugin apps use the same movable card grammar, `54px` header, resize/snap behavior, and semantic summary below `0.5×`. A `window` contribution opens a separate CanvasTTY-owned sandboxed window; arbitrary native window embedding is not part of the contract. - The built-in Browser is one movable, resizable core canvas card, not a plugin contribution. It uses the same `54px` outer window header as other canvas cards, with its identity and hide-card action isolated from the internal tab strip below. Its trusted DOM chrome owns compact tabs/favicons, address/search, back/forward/reload, downloads, per-tab provider badges, site dialogs, and explicit Close tab/Close all. Hiding the card keeps its tabs and shared authenticated Chromium profile alive. Below `0.5×`, during Edit HOME, behind trusted dialogs/popovers, and while overlapped by a higher renderer-owned canvas window, the native page is hidden and replaced with a stable semantic surface. During card or camera motion it remains live and follows frame-coalesced viewport geometry. @@ -67,7 +67,7 @@ This contract preserves the approved MVP concept and prevents feature ownership - One trusted context dispatcher owns right-clicks on the canvas. Truly empty canvas offers region creation, a sticky note, the Settings-configured launcher submenu, Browser, and Settings. Holding RMB on empty canvas also opens the configurable radial quick launcher: moving toward an action and releasing activates it, while a stationary right-click continues to open the standard empty-canvas menu. Region and note right-clicks remain context-specific. A region offers rename, color, a note at the pressed point, and region-only deletion. A note frame offers edit, bring-to-front, and deletion. Terminal, Browser, plugin, textarea/input, and contenteditable surfaces keep their native context menus; middle-button panning is unchanged. `Cmd/Ctrl+K` opens a searchable palette over live sessions and the same global creation/launch actions. Regions persist independently of terminal restore, render behind HOME and windows, resize from every edge/corner, and move every terminal, plugin, Browser, or note whose complete bounds were inside the region at drag start. Attached contents follow the region continuously during the gesture and persist once at pointer release; deleting a region never deletes its contents. Sticky notes persist bounded text and geometry, snap like other windows, and resize from every edge/corner. General Settings exposes independent **Save colored regions after exit** and **Save notes after exit** controls. Both default on to preserve existing profiles. Turning either off removes only that collection from disk persistence without deleting its live canvas objects; turning it back on saves the current collection, while leaving it off starts the next launch with that collection empty. - Context menus, region editors, the radial launcher, and the command palette use official Lucide/provider assets and shared application color tokens. Their dimensions follow root `--ui-scale`. Appearance owns the `0.85–1.25` scale in `0.05` steps and the sage/lilac/night system palette; the scale changes UI chrome rather than canvas zoom or terminal font size. Agents owns the independent context-menu and radial-launcher subsets and their safe reset defaults. - Settings uses the approved two-pane modal grammar: a persistent icon-labelled sidebar for all seven sections, a separate current-section header, and a scrollable content pane. Settings must not fall back to the legacy light slide-over with one horizontal segmented tab strip. Simple settings use compact copy/control rows; all Settings chrome reads the active system tokens, official Lucide assets, and root `--ui-scale`. -- General Settings places the macOS/Windows/Linux/Custom keyboard preset after language, followed by an expandable Keyboard shortcuts section for canvas, terminal, Codex editor and canvas navigation bindings. Recording a shortcut selects Custom; choosing a named preset replaces bindings. Optional commands can be disabled, while submit, newline and whole-draft selection remain bound. Canvas and terminal bindings update immediately; native Codex editor bindings apply to new or restarted cards. Focused terminal and text inputs retain ownership of canvas keyboard shortcuts on every platform. +- General Settings places the macOS/Windows/Linux/Custom keyboard preset after language, followed by an expandable Keyboard shortcuts section for canvas, terminal, Codex editor and canvas navigation bindings. Recording a shortcut selects Custom; choosing a named preset replaces bindings. Optional commands can be disabled, while submit, newline and whole-draft selection remain bound. On macOS the Codex editor group lists submit, line break, alternate line break, select draft and copy, cut and delete draft (Cmd+C/X, Delete; these act on a selected draft, can be switched off and do not clash with the terminal Copy key, which keeps copying selected output); macOS settings still at the old Codex defaults (Enter submit, Ctrl+Enter and Cmd+Enter aliases, Shift+Enter newline) take the new ones. Linux and Windows keep their Codex rows and keys. Canvas and terminal bindings update immediately; native Codex editor bindings apply to new or restarted cards. On macOS a Claude editor group follows, headed by the Claude draft keys switch: submit (Cmd+Enter), line break (Enter, alternate Shift+Enter), select, copy, cut and delete the draft (Cmd+A/C/X, Delete). Its keys form their own conflict context, apply immediately, and change Enter only while Claude's prompt box is on screen; submit, both line breaks and select remain bound. Focused terminal and text inputs retain ownership of canvas keyboard shortcuts on every platform. - Empty-canvas drag and middle-button drag pan the canvas. On fresh profiles ordinary scroll over empty canvas pans on both axes; pinch and `Cmd/Ctrl + scroll` zoom around the pointer. **Use scroll wheel to zoom** restores historical ordinary-wheel zoom and is enabled by migration for existing profiles. Only a focused input widget interrupts canvas wheel/pinch, except the HOME session list keeps ordinary local scrolling without a focus precondition; unfocused or non-focusable widgets otherwise leave those events to the canvas. **Wheel/pinch capture over widgets** has Off, On, and Key modes: Off preserves local ownership, On always transfers only wheel/pinch to the canvas, and Key transfers only wheel/pinch while its binding is held. Key and full-navigation bindings accept modifier chords or Mouse3/Mouse4/Mouse5. A focused live Browser page therefore scrolls normally in Off or released-Key mode; unfocused Browser content, On, an active Key binding, the full override, pinch, and `Cmd/Ctrl + scroll` are canvas-owned. The owner selected for a Browser wheel sequence is held until 250 ms of wheel inactivity. Browser summaries and placeholders are always canvas-owned. Fresh profiles use Key with `Command` on macOS or `Ctrl` elsewhere. A separate configurable **Canvas navigation override** (default `Option` on macOS and `Alt` elsewhere) transfers wheel/pinch and drag while held. While full override is held all canvas surfaces show `grab`; an owned drag shows `grabbing` until pointer up/cancel even after the binding is released. - The minimap fits both the camera viewport and the occupied workspace: HOME, regions, terminal/agent windows, renderable plugin cards, Files cards, the visible Browser card, materials, and sticky notes. It uses one uniform scale with padding, so every rectangle preserves its real proportions and relative size. Window stacking follows the Canvas. Sessions have no text labels; their existing provider icons appear only when they fit inside the projected rectangle, without enlarging it. Pan and zoom refit the overview to keep the entire camera viewport and all objects visible together. Moving or resizing an individual window or HOME updates the layout after pointer release. Adding, closing, or repositioning objects also refits the overview; a distant object or camera can therefore make all rectangles smaller. Controls chooses between two mutually exclusive modes: **Click** (the default, which recentres without changing zoom) and **Drag**. Drag mirrors empty-canvas grab semantics: pointer-down never jumps the camera, moving right/down pulls the scene right/down from the gesture's starting camera, and pointer capture continues outside the minimap. Drag uses the overview scale captured at pointer-down so refitting during the gesture cannot accelerate movement. Pressing and releasing without movement in Drag mode never recentres the camera. Arrow keys always pan it from keyboard focus. Minimap, passive shortcut hints, and Home/zoom controls share four corner slots and stack instead of overlapping when assigned to the same corner. - The white camera frame represents the full viewport and stays entirely inside the minimap's padded perimeter. It does not replace the viewport with a clipped rectangle or an edge marker. HOME and object projections retain their real proportions. diff --git a/docs/agent-orchestration.md b/docs/agent-orchestration.md index 0e8b6e3f4..d808630e3 100644 --- a/docs/agent-orchestration.md +++ b/docs/agent-orchestration.md @@ -52,7 +52,7 @@ The core applies these to every way an agent can start another one: `spawn_agent ## Agent isolation -Settings → Agents → Agent isolation (on by default) wraps an agent's whole process tree (the CLI, its commands, its MCP servers and hooks) in an operating-system layer. It applies to every subagent, every agent a plugin starts, and every agent in a profile other than normal (manual), whoever launched it. Inside it: +Settings → Agents → Agent isolation (on by default) wraps an agent's whole process tree (the CLI, its commands, its MCP servers and hooks) in an operating-system layer. It applies to every subagent, every agent a plugin starts, and a CLI's auto that is only its approval bypass (a CLI without an auto mode of its own). An agent the person launches, in any other profile, runs as their own terminal would run it: their environment and temporary folders, and the CLI's own sandbox as its own settings say. Inside the layer, Claude Code may also write its fixed scratch folder `/tmp/claude-` (its Bash tool and external editor use it whatever `TMPDIR` says). Inside it: - files can be written only in the project folder (both spellings), the launch's own temporary folder (`TMPDIR`), the CLI's own state, configuration and cache folders, and the npm/bun caches; the project's git hooks and an existing repository's git config, and the CLI's own permission settings files (`~/.codex/config.toml`, `~/.claude/settings.json`, OpenCode's config) are not writable; - SSH, cloud and package-registry credentials, other CLIs' folders (their credentials) and CanvasTTY's own tokens, secret stores, account homes and launch files are unreadable, except what this launch was handed (its own control connection, its account home); @@ -103,7 +103,7 @@ node scripts/canvastty-control.mjs interrupt SESSION_ID Output is JSON; `--json` is accepted explicitly too. `providers` lists the agents CanvasTTY can create workers for (the same entries as `list_providers`, without plugin launch options); an unknown `--provider` is refused with a pointer to it. `create --model --effort ` sets the worker's model and reasoning effort like `spawn_agent`. Save the returned session ID. For each send, use its returned `resultRevisionBefore` as `result --after`, rather than repeatedly using zero. -From the person's own terminal, `create` defaults to **YOLO** and passes Codex's real `--dangerously-bypass-approvals-and-sandbox` flag, only for a CLI the person acknowledged YOLO for in the launcher (otherwise it is refused with that reason); inside agent isolation (below) YOLO still cannot write outside the project. Workers can edit files and run tests. Their global settings are unchanged. Specify `--profile normal` to use the ordinary provider configuration instead, or `--profile auto` (Codex, Claude Code, Grok) for the CLI's own auto mode inside its sandbox (see [Launch contributors](plugins.md#launch-contributors-launchcontribute)). Scope tasks and external actions explicitly: full access is not filesystem isolation. A control API with no deletion command does not prevent a full-access model from deleting files. Base protection (Settings → Agents, on by default) still refuses elevation, pipes into a shell, disk commands, and writes or deletes outside the working folder before the tool call runs, YOLO included; it is a guard through the agent's own hook, not a sandbox. Screens, results and failure details returned to a controller are masked for known keys and common key shapes. +From the person's own terminal, `create` defaults to **YOLO** and passes Codex's real `--dangerously-bypass-approvals-and-sandbox` flag, only for a CLI the person acknowledged YOLO for in the launcher (otherwise it is refused with that reason); inside agent isolation (below) YOLO still cannot write outside the project. Workers can edit files and run tests. Their global settings are unchanged. Specify `--profile normal` to use the ordinary provider configuration instead, or `--profile auto` (Codex, Claude Code, Grok) for the CLI's own auto mode (see [Launch contributors](plugins.md#launch-contributors-launchcontribute)). Scope tasks and external actions explicitly: full access is not filesystem isolation. A control API with no deletion command does not prevent a full-access model from deleting files. Base protection (Settings → Agents, on by default) still refuses elevation, pipes into a shell, disk commands, and writes or deletes outside the working folder before the tool call runs, YOLO included; it is a guard through the agent's own hook, not a sandbox. Screens, results and failure details returned to a controller are masked for known keys and common key shapes. The backend uses `TerminalManager` and the existing native provider path. `cwd`, title and profile apply at creation. YOLO is retained by ordinary native restart/restore. Creation does not activate a canvas window or request UI focus. diff --git a/docs/installing-and-security.md b/docs/installing-and-security.md index c81480251..de62de4b1 100644 --- a/docs/installing-and-security.md +++ b/docs/installing-and-security.md @@ -89,7 +89,7 @@ Agents work in their own mode; CanvasTTY's layers sit outside it as a quiet safe | The agent's own permission system | What its CLI promises in the chosen mode (Claude Code, Codex, OpenCode, Grok…). | Anything the CLI's own classifier or reviewer lets through. | | Base protection (hooks) | Denies elevation, pipes into a shell, disk commands, fork bombs, writes and deletes outside the project and access to CanvasTTY's private data, before the tool call runs, for agents whose CLI has hooks (Claude Code, Codex, Qwen Code, OpenCode). A decision plugin's "ask" is shown by Claude Code; for a CLI that cannot ask it is a deny with the reason. | It reads commands; code that hides what it does, or a CLI without hooks, is not covered. It is a guard, not a sandbox. | | Delegation rules | A subagent never gets more than its orchestrator (never YOLO), works only in its orchestrator's project folder, within the depth and count limits the person set; orchestrators get a control connection of their own; no agent-facing tool changes settings, protection, profiles, trust or isolation; plugin launch options from an agent only where the plugin declared them delegable. | What a plugin the person trusted does with its own permissions. | -| Agent isolation (OS layer) | On macOS (sandbox-exec) and Linux (bubblewrap), for subagents, plugin-started agents and every agent not in Manual: the whole process tree writes only in the project, its own temporary folder and its CLI's own folders; keys, other CLIs' credentials and CanvasTTY's tokens are unreadable; no other process, app, Apple event, preference write, launchd job or foreign Unix socket (Docker, tmux, SSH agent) is reachable. Fails closed. | Network is not restricted. Linux cannot filter Unix sockets, only hide the user runtime folder. The CLI's own sandbox cannot run inside the layer on macOS, so it is switched off there (approvals unchanged) and commands can use the network. A Claude launch may rewrite the login keychain file to save a refreshed sign-in, so it could also damage that file (other items stay behind their own access lists). Windows has no layer yet: subagents run in Manual there unless the person turns isolation off. | +| Agent isolation (OS layer) | On macOS (sandbox-exec) and Linux (bubblewrap), for subagents, plugin-started agents and a CLI's auto that is only its approval bypass (agents the person launches otherwise run without it): the whole process tree writes only in the project, its own temporary folder and its CLI's own folders; keys, other CLIs' credentials and CanvasTTY's tokens are unreadable; no other process, app, Apple event, preference write, launchd job or foreign Unix socket (Docker, tmux, SSH agent) is reachable. Fails closed. | Network is not restricted. Linux cannot filter Unix sockets, only hide the user runtime folder. The CLI's own sandbox cannot run inside the layer on macOS, so it is switched off there (approvals unchanged) and commands can use the network. A Claude launch may rewrite the login keychain file to save a refreshed sign-in, so it could also damage that file (other items stay behind their own access lists). Windows has no layer yet: subagents run in Manual there unless the person turns isolation off. | Isolation keeps approval configuration read-only, including OpenCode's project and custom config files and its `agent`/`agents` directories. CLI state and caches remain writable. A moved CLI home is refused if its real path overlaps host credentials or private CanvasTTY data; a selected account folder below `account-homes` remains available. Credential exclusions use the host environment captured before launch contributions, even if the launch changes `HOME`. diff --git a/docs/plugins.md b/docs/plugins.md index 0047ad17b..a8c1c6d9c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -223,7 +223,7 @@ Rules the host enforces, none of which is ever skipped: - No answer within 5 s, an error, an invalid answer, a missing secret, or a plugin that is disabled, removed or no longer trusted refuses the launch with the reason on the card. The agent is never started without a contribution the person chose. A restored card whose plugin is unavailable comes back stopped with that reason and keeps its record until the plugin returns or the card is closed. - A plain terminal takes no launch options. -**Launch profiles.** `profile` is `normal` (the default), `yolo`, or `auto`. `auto` exists only for agents whose CLI has a native auto mode, checked against each CLI's `--help`: Codex `--approve-for-me` (its own reviewer, in its `workspace-write` sandbox), Claude Code `--permission-mode auto` with its sandbox (`{"sandbox":{"enabled":true,"autoAllowBashIfSandboxed":false}}` merged into the one `--settings`), and Grok `--permission-mode auto` (no Grok sandbox is relied on). Base protection and decision services keep answering in front of it (Codex, Claude Code). When any contributor answers `thirdPartyModel: true`, `auto` becomes the CLI's accept-edits mode in the same sandbox (Codex `--sandbox workspace-write --ask-for-approval on-request`, Claude Code and Grok `--permission-mode acceptEdits`): the native reviewer would be that same model, and a weak model's own classifier is not a safety boundary. +**Launch profiles.** `profile` is `normal` (the default), `yolo`, or `auto`. `auto` exists only for agents whose CLI has a native auto mode, checked against each CLI's `--help`: Codex `--approve-for-me` (its own reviewer, in its `workspace-write` sandbox), Claude Code `--permission-mode auto` (its own sandbox follows the person's Claude settings; CanvasTTY adds none), and Grok `--permission-mode auto` (no Grok sandbox is relied on). Base protection and decision services keep answering in front of it (Codex, Claude Code). When any contributor answers `thirdPartyModel: true`, `auto` becomes the CLI's accept-edits mode (Codex `--sandbox workspace-write --ask-for-approval on-request`, Claude Code and Grok `--permission-mode acceptEdits`): the native reviewer would be that same model, and a weak model's own classifier is not a safety boundary. **Trusted folder.** A subagent on this computer whose folder is the one the person chose for its top-level agent, or inside it, gets `"trustedFolder"`: that folder's real path. CanvasTTY itself answers Codex's "Trust this folder?" for it with a per-run `-c projects=…` override (nothing is written to `~/.codex`); a plugin that keeps the agent's own config home (an account's `CLAUDE_CONFIG_DIR`, say) may mark the folder trusted there. Codex also gets per-run trust for the hooks CanvasTTY itself adds (`-c hooks.state=…`), so it does not stop at "Hooks need review"; a project's or the person's own hooks still ask. Plugins cannot pass `-c hooks…`. diff --git a/docs/plugins.ru.md b/docs/plugins.ru.md index 5d2cfe9d1..beff9a9c6 100644 --- a/docs/plugins.ru.md +++ b/docs/plugins.ru.md @@ -204,7 +204,7 @@ host.service.onEvent(({ serviceId, event, data }) => { /* … */ }); - Нет ответа за 5 с, ошибка, неверный ответ, отсутствующий секрет или выключенный, удалённый либо переставший быть доверенным плагин отклоняют запуск, и причина видна в окне. Агент никогда не запускается без выбранного вклада. Восстановленное окно с недоступным плагином возвращается остановленным с этой причиной и сохраняет запись, пока плагин не вернётся или окно не закроют. - Обычный терминал параметров запуска не принимает. -**Профили запуска.** `profile` — это `normal` (по умолчанию), `yolo` или `auto`. `auto` есть только у агентов, чей CLI имеет собственный авторежим, проверенный по `--help` каждого CLI: Codex `--approve-for-me` (его собственная проверка в песочнице `workspace-write`), Claude Code `--permission-mode auto` с его песочницей (`{"sandbox":{"enabled":true,"autoAllowBashIfSandboxed":false}}` сливается в единственный `--settings`) и Grok `--permission-mode auto` (на песочницу Grok не полагаемся). Базовая защита и сервисы решений отвечают перед ним (Codex, Claude Code). Если хотя бы один вклад ответил `thirdPartyModel: true`, `auto` превращается в режим «только правки» того же CLI в той же песочнице (Codex `--sandbox workspace-write --ask-for-approval on-request`, Claude Code и Grok `--permission-mode acceptEdits`): собственной проверкой была бы та же модель, а классификатор слабой модели — не граница безопасности. +**Профили запуска.** `profile` — это `normal` (по умолчанию), `yolo` или `auto`. `auto` есть только у агентов, чей CLI имеет собственный авторежим, проверенный по `--help` каждого CLI: Codex `--approve-for-me` (его собственная проверка в песочнице `workspace-write`), Claude Code `--permission-mode auto` (его собственная песочница — по настройкам Claude у человека, CanvasTTY её не добавляет) и Grok `--permission-mode auto` (на песочницу Grok не полагаемся). Базовая защита и сервисы решений отвечают перед ним (Codex, Claude Code). Если хотя бы один вклад ответил `thirdPartyModel: true`, `auto` превращается в режим «только правки» того же CLI (Codex `--sandbox workspace-write --ask-for-approval on-request`, Claude Code и Grok `--permission-mode acceptEdits`): собственной проверкой была бы та же модель, а классификатор слабой модели — не граница безопасности. **Доверенная папка.** Субагент на этом компьютере, чья папка — та, что человек выбрал для его агента верхнего уровня, или внутри неё, получает `"trustedFolder"`: реальный путь этой папки. CanvasTTY сам отвечает за него на вопрос Codex «Trust this folder?» переопределением `-c projects=…` только на этот запуск (в `~/.codex` ничего не пишется); плагин, который держит собственную папку конфигурации агента (например, `CLAUDE_CONFIG_DIR` аккаунта), может отметить папку доверенной там. Codex также получает доверие на этот запуск к хукам, которые добавляет сам CanvasTTY (`-c hooks.state=…`), и не останавливается на «Hooks need review»; хуки проекта или самого человека по-прежнему спрашивают. Плагины не могут передавать `-c hooks…`. diff --git a/docs/plugins.zh-CN.md b/docs/plugins.zh-CN.md index c91ff2c60..919896f85 100644 --- a/docs/plugins.zh-CN.md +++ b/docs/plugins.zh-CN.md @@ -202,7 +202,7 @@ host.service.onEvent(({ serviceId, event, data }) => { /* … */ }); - 5 秒内无应答、出错、应答无效、缺少机密,或插件被禁用、删除或不再受信任,都会拒绝启动并在卡片上显示原因。智能体绝不会在缺少用户所选贡献的情况下启动。插件不可用的恢复卡片以停止状态返回并显示该原因,记录保留到插件恢复或卡片被关闭。 - 普通终端不接受启动选项。 -**启动配置档。** `profile` 为 `normal`(默认)、`yolo` 或 `auto`。`auto` 仅适用于 CLI 自带自动模式的智能体,均按各 CLI 的 `--help` 核实:Codex `--approve-for-me`(其自身审查,运行于 `workspace-write` 沙箱),Claude Code `--permission-mode auto` 及其沙箱(`{"sandbox":{"enabled":true,"autoAllowBashIfSandboxed":false}}` 合并进唯一的 `--settings`),以及 Grok `--permission-mode auto`(不依赖 Grok 沙箱)。基础保护和决策服务仍在其前面作答(Codex、Claude Code)。只要任一贡献者回答 `thirdPartyModel: true`,`auto` 就改为同一沙箱中 CLI 的“仅接受编辑”模式(Codex `--sandbox workspace-write --ask-for-approval on-request`,Claude Code 和 Grok `--permission-mode acceptEdits`):原生审查者将是同一个模型,而弱模型自己的分类器不是安全边界。 +**启动配置档。** `profile` 为 `normal`(默认)、`yolo` 或 `auto`。`auto` 仅适用于 CLI 自带自动模式的智能体,均按各 CLI 的 `--help` 核实:Codex `--approve-for-me`(其自身审查,运行于 `workspace-write` 沙箱),Claude Code `--permission-mode auto`(其自身沙箱遵循用户的 Claude 设置,CanvasTTY 不额外添加),以及 Grok `--permission-mode auto`(不依赖 Grok 沙箱)。基础保护和决策服务仍在其前面作答(Codex、Claude Code)。只要任一贡献者回答 `thirdPartyModel: true`,`auto` 就改为 CLI 的“仅接受编辑”模式(Codex `--sandbox workspace-write --ask-for-approval on-request`,Claude Code 和 Grok `--permission-mode acceptEdits`):原生审查者将是同一个模型,而弱模型自己的分类器不是安全边界。 **受信任文件夹。** 在本机运行、其文件夹是用户为其顶层智能体选择的文件夹(或位于其中)的子智能体,会收到 `"trustedFolder"`:该文件夹的真实路径。CanvasTTY 会以仅限此次运行的 `-c projects=…` 覆盖替它回答 Codex 的 “Trust this folder?”(不会写入 `~/.codex`);自行保存智能体配置目录的插件(例如账户的 `CLAUDE_CONFIG_DIR`)可以在那里将该文件夹标记为受信任。Codex 还会获得对 CanvasTTY 自己添加的 hook 的本次运行信任(`-c hooks.state=…`),因此不会停在 “Hooks need review”;项目或用户自己的 hook 仍会询问。插件不能传递 `-c hooks…`。 diff --git a/electron-builder.yml b/electron-builder.yml index ab72403ef..c09bd23fa 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -99,6 +99,7 @@ extraResources: to: agent-runtime filter: - "*.mjs" + - "*.sh" - from: agent/browser to: agent/browser filter: diff --git a/src/agent-runtime/draft-editor.sh b/src/agent-runtime/draft-editor.sh new file mode 100644 index 000000000..b4cbc83a7 --- /dev/null +++ b/src/agent-runtime/draft-editor.sh @@ -0,0 +1,61 @@ +#!/bin/sh +# $VISUAL for macOS Claude sessions. Claude Code exposes no select-all, so CanvasTTY +# acts on the whole prompt draft through Claude's external-editor round trip (Ctrl+G). +# Each action is a file req. in CANVASTTY_DRAFT_DIR, claimed here by renaming it. +# A cancel. stands for a Ctrl+G that Claude took too long to pick up: when no request +# is waiting, one is used up and nothing changes, so a late Ctrl+G opens no editor. +# With neither, this is an ordinary Ctrl+G and the person's own editor opens. +# +# A background Claude session may be shown by another card than the one that started it, +# so after this card's own folder the other cards' folders are looked at for a request +# (inside agent isolation they are hidden, and only the own folder is seen). A cancel is +# only ever this card's own: another card's never costs a Ctrl+G here. +file=$1 +dir=$CANVASTTY_DRAFT_DIR +# Only Claude's own prompt file: a program Claude runs (git commit, crontab -e) gets the person's editor. +case "${file##*/}" in + claude-prompt-*.md) ;; + *) dir= ;; +esac +# Sets found (a folder) and id to the oldest . in the given folders, in order. +find_oldest() { + kind=$1 + shift + for found in "$@"; do + [ -d "$found" ] || continue + id=$(ls "$found" 2>/dev/null | sed -n "s/^$kind\.\([0-9][0-9]*\)\$/\1/p" | sort -n | head -n 1) + [ -n "$id" ] && return 0 + done + return 1 +} +if [ -n "$dir" ]; then + while find_oldest req "$dir" "${dir%/*}"/*; do + # Renaming is atomic: CanvasTTY cancels a request the same way, so only one side gets it. + if ! mv "$found/req.$id" "$found/claimed.$id" 2>/dev/null; then + { [ -e "$found/req.$id" ] || [ -L "$found/req.$id" ]; } && exit 1 + continue + fi + action=$(head -n 1 "$found/claimed.$id") + rm -f "$found/claimed.$id" + case "$action" in + copy|cut|clear) ;; + *) exit 0 ;; + esac + rm -f "$found/draft.$id" + # Without a saved copy the draft is left as it was. + cp "$file" "$found/draft.$id" || exit 1 + case "$action" in + cut|clear) : > "$file" ;; + esac + : > "$found/done.$id" + exit 0 + done + # A cancel that cannot be removed is not used up: this Ctrl+G opens the editor. + if find_oldest cancel "$dir" && rm "$found/cancel.$id" 2>/dev/null; then + exit 0 + fi +fi +if [ -n "$CANVASTTY_DRAFT_EDITOR" ]; then + exec /bin/sh -c "$CANVASTTY_DRAFT_EDITOR \"\$1\"" canvastty-editor "$file" +fi +exec vi "$file" diff --git a/src/main/index.ts b/src/main/index.ts index b9832dcee..4e3777870 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -6,7 +6,7 @@ import { randomUUID } from "node:crypto"; import { dirname, isAbsolute } from "node:path"; import { EvenG2Controller } from "./services/companion/EvenG2Controller"; import { join } from "node:path"; -import { app, BrowserWindow, dialog, Menu, net, Notification, protocol, safeStorage, session } from "electron"; +import { app, BrowserWindow, clipboard, dialog, Menu, net, Notification, protocol, safeStorage, session } from "electron"; import { IPC, type LocaleId, @@ -28,7 +28,8 @@ import { SettingsStore } from "./services/SettingsStore"; import { FileAccessService } from "./services/FileAccessService"; import { SkinRegistry } from "./services/SkinRegistry"; import { PixelSkinPackRegistry } from "./services/PixelSkinPackRegistry"; -import { TerminalManager, reachesObservers, reachesRenderer } from "./services/TerminalManager"; +import { TerminalManager, reachesObservers, reachesRenderer, setTerminalSystemLocale } from "./services/TerminalManager"; +import { ClaudeDraftEditor } from "./services/ClaudeDraftEditor"; import { TerminalRendererOutbox } from "./services/TerminalRendererOutbox"; import { AgentControlGateway } from "./services/agent-control/AgentControlGateway"; import { TerminalSessionStore } from "./services/TerminalSessionStore"; @@ -642,6 +643,18 @@ async function initializeServices(ipc: IpcRegistrar): Promise { terminalManager.configureYoloAcknowledgement((provider) => settings.get().acknowledgedDangerousProfiles.includes(provider as AgentProviderId)); // OpenCode's auto profile runs shell commands without asking only while base protection guards them. terminalManager.configureBaseProtection(() => settings.get().baseProtectionEnabled); + if (process.platform === "darwin") setTerminalSystemLocale(app.getSystemLocale()); + const draftEditor = new ClaudeDraftEditor({ + root: join(userDataPath, "claude-draft"), + helperPath: app.isPackaged + ? join(process.resourcesPath, "agent-runtime", "draft-editor.sh") + : join(app.getAppPath(), "src", "agent-runtime", "draft-editor.sh"), + writeClipboard: (text) => clipboard.writeText(text), + readClipboard: () => ({ image: !clipboard.readImage().isEmpty(), text: clipboard.readText() }) + }); + draftEditor.removeLeftovers(); + terminalManager.configureDraftEditor(draftEditor); + terminalManager.configureDraftKeys(() => settings.get().claudeDraftKeysEnabled); const terminalSessionStore = new TerminalSessionStore(userDataPath); terminalManager.configureSessionPersistence(terminalSessionStore, settings.get().sessionRestoreMode); agentChatHistory = new AgentChatHistoryService(settings, providerClis, terminalManager, hermesHomeDirectory); diff --git a/src/main/ipc/registerIpc.ts b/src/main/ipc/registerIpc.ts index 00d3feb6c..a50614d42 100644 --- a/src/main/ipc/registerIpc.ts +++ b/src/main/ipc/registerIpc.ts @@ -33,6 +33,7 @@ import type { TerminalManager } from "../services/TerminalManager"; import type { AgentChatHistoryService } from "../services/AgentChatHistoryService"; import { withoutAccountScope, type LimitsService } from "../services/LimitsService"; import type { UsageHistoryService } from "../services/UsageHistoryService"; +import { isClaudeDraftAction } from "../services/ClaudeDraftEditor"; import type { PluginManager } from "../services/PluginManager"; import type { MascotManager } from "../services/MascotManager"; import type { PluginServiceSupervisor } from "../services/PluginServiceSupervisor"; @@ -954,6 +955,12 @@ export function registerIpc(ipcMain: IpcRegistrar, { if (!isMainRenderer(event, getMainWindow)) return; terminals.input(id, data); }); + ipcMain.handle(IPC.terminalDraftAction, (event, id: unknown, action: unknown, followUp: unknown, paste: unknown) => { + assertMainRenderer(event, getMainWindow); + if (typeof id !== "string" || !isClaudeDraftAction(action)) return false; + return terminals.draftAction(id, action, typeof followUp === "string" ? followUp : "", + paste === "plain" || paste === "bracketed" ? paste : null); + }); ipcMain.on(IPC.terminalResize, (event, id: string, cols: number, rows: number) => { if (!isMainRenderer(event, getMainWindow) || typeof id !== "string") return; terminals.resize(id, cols, rows); diff --git a/src/main/services/CanvasNavigationOverride.ts b/src/main/services/CanvasNavigationOverride.ts index a8f15c67d..e053ec4f6 100644 --- a/src/main/services/CanvasNavigationOverride.ts +++ b/src/main/services/CanvasNavigationOverride.ts @@ -237,8 +237,8 @@ export class CanvasNavigationInputController { /** * The renderer reports whether a terminal surface or shortcut recorder has keyboard focus. Both consume - * Command+C/V/A themselves, so those shortcuts bypass the Edit menu. The terminal-named API covers both; - * ordinary fields and plugin pages keep the menu's native Copy, Paste and Select All. + * Command+C/V/A/X themselves, so those shortcuts bypass the Edit menu. The terminal-named API covers both; + * ordinary fields and plugin pages keep the menu's native Copy, Paste, Select All and Cut. */ setTerminalEditFocus(contents: WebContents, focused: boolean): void { if (focused) this.terminalEditFocus.add(contents); @@ -317,7 +317,7 @@ export class CanvasNavigationInputController { && this.terminalEditFocus.has(contents) && topFrameFocused(contents) && input.type === "keyDown" && input.meta && !input.control && !input.alt && !input.shift - && (input.code === "KeyA" || input.code === "KeyC" || input.code === "KeyV"); + && (input.code === "KeyA" || input.code === "KeyC" || input.code === "KeyV" || input.code === "KeyX"); const shouldCaptureMenuShortcuts = this.wheelTracker.shouldCaptureMenuShortcuts || this.navigationTracker.shouldCaptureMenuShortcuts || macEditShortcut; diff --git a/src/main/services/ClaudeDraftEditor.ts b/src/main/services/ClaudeDraftEditor.ts new file mode 100644 index 000000000..9191b4848 --- /dev/null +++ b/src/main/services/ClaudeDraftEditor.ts @@ -0,0 +1,240 @@ +import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import type { ClaudeDraftAction } from "../../shared/contracts.ts"; + +export const CLAUDE_DRAFT_ACTIONS: readonly ClaudeDraftAction[] = ["copy", "cut", "clear"]; +export function isClaudeDraftAction(value: unknown): value is ClaudeDraftAction { + return CLAUDE_DRAFT_ACTIONS.includes(value as ClaudeDraftAction); +} + +const EXTERNAL_EDITOR_KEY = "\u0007"; +const DONE_TIMEOUT_MS = 3000; +const POLL_MS = 15; + +export interface ClaudeDraftEditorOptions { + /** Private folder for the per-session request/done files; created on demand. */ + root: string; + /** draft-editor.sh; its path becomes part of $VISUAL, so it must be a plain path. */ + helperPath: string; + writeClipboard: (text: string) => void; + /** The clipboard at the moment a paste that replaces the draft is typed. */ + readClipboard: () => { image: boolean; text: string }; + timeoutMs?: number; +} + +/** How a paste is typed: as xterm types it, bracketed when Claude turned bracketed paste on. */ +export type ClaudeDraftPaste = "plain" | "bracketed"; + +type Step = + | { data: string } + | { action: ClaudeDraftAction; followUp: string; paste: ClaudeDraftPaste | null; resolve: (done: boolean) => void }; + +interface SessionQueue { + steps: Step[]; + write: (data: string) => boolean; +} + +/** + * Whole-draft copy/cut/clear for Claude Code on macOS. Claude has no select-all and + * no draft API, but its Ctrl+G external-editor round trip hands the full draft (hidden + * lines and pasted text included) to $VISUAL and reloads whatever $VISUAL leaves. + * Claude drops keystrokes that arrive while the editor runs, so a session's actions run + * one at a time and its input is held until they finish, then delivered in order. + * + * Each action is a file req.. The helper claims the oldest one by renaming it, so a + * request is either claimed or cancelled, never both. A Ctrl+G Claude has not picked up + * by the deadline turns its request into cancel.: a Ctrl+G that finds no request uses + * up one cancel and changes nothing, so a late one opens no editor. + */ +export class ClaudeDraftEditor { + private readonly queues = new Map(); + private readonly granted = new Set(); + private readonly options: ClaudeDraftEditorOptions; + private readonly timeoutMs: number; + private sequence = 0; + + constructor(options: ClaudeDraftEditorOptions) { + this.options = options; + this.timeoutMs = options.timeoutMs ?? DONE_TIMEOUT_MS; + } + + /** Drops what an earlier run of CanvasTTY left: its Claude sessions are gone, and so are their requests. */ + removeLeftovers(): void { + try { + rmSync(this.options.root, { recursive: true, force: true }); + } catch { + // Each session's folder is cleared again at its launch. + } + } + + /** + * Launch variables for one Claude session, or none when the helper cannot be used safely. They are given to + * Claude twice: in its environment and in its --settings env, which is what a background session (/bg, + * /resume, agent view) gets: such a session runs under Claude's own supervisor, not under this process. + */ + environment(sessionId: string, source: Readonly>): Record { + this.forget(sessionId); + // $VISUAL may go through a shell: no whitespace, quoting or shell syntax in the helper's path. + if (/[\s'"\\$`;&|<>(){}[\]*?!#~]/.test(this.options.helperPath) || !isSafeId(sessionId)) return {}; + // A new Claude process has no Ctrl+G outstanding from an earlier one. + try { + rmSync(this.directory(sessionId), { recursive: true, force: true }); + } catch { + return {}; + } + this.granted.add(sessionId); + return { + VISUAL: `/bin/sh ${this.options.helperPath}`, + CANVASTTY_DRAFT_DIR: this.directory(sessionId), + CANVASTTY_DRAFT_EDITOR: source.VISUAL || source.EDITOR || "" + }; + } + + /** Whether this session's Claude was launched with the helper as its editor. */ + isGranted(sessionId: string): boolean { + return this.granted.has(sessionId); + } + + /** The folder the helper of a session launched with it answers in; null for any other session. */ + folderOf(sessionId: string): string | null { + return this.granted.has(sessionId) ? this.directory(sessionId) : null; + } + + /** Queues input written while actions run; true when the caller must not write it now. */ + hold(sessionId: string, data: string): boolean { + const queue = this.queues.get(sessionId); + if (!queue) return false; + queue.steps.push({ data }); + return true; + } + + /** + * Queues one action; once earlier ones finish it runs, then writes followUp (the key or + * paste that replaces a selected draft). Resolves true when Claude's editor round trip ran. + */ + run( + sessionId: string, + action: ClaudeDraftAction, + followUp: string, + write: (data: string) => boolean, + paste: ClaudeDraftPaste | null = null + ): Promise { + if (!isSafeId(sessionId) || !this.granted.has(sessionId)) return Promise.resolve(false); + return new Promise((resolve) => { + const step: Step = { action, followUp, paste, resolve }; + const queue = this.queues.get(sessionId); + if (queue) { + queue.steps.push(step); + return; + } + const started: SessionQueue = { steps: [step], write }; + this.queues.set(sessionId, started); + void this.drain(sessionId, started); + }); + } + + /** Drops the session's queue and files; queued actions resolve false and held input is discarded. */ + forget(sessionId: string): void { + this.granted.delete(sessionId); + const queue = this.queues.get(sessionId); + this.queues.delete(sessionId); + for (const step of queue?.steps.splice(0) ?? []) if ("action" in step) step.resolve(false); + if (!isSafeId(sessionId)) return; + try { + rmSync(this.directory(sessionId), { recursive: true, force: true }); + } catch { + // Rebuilt with the next launch. + } + } + + private async drain(sessionId: string, queue: SessionQueue): Promise { + const live = () => this.queues.get(sessionId) === queue; + while (live() && queue.steps.length > 0) { + const step = queue.steps.shift()!; + if ("data" in step) { + queue.write(step.data); + continue; + } + const done = await this.roundTrip(sessionId, step.action, queue.write, live).catch(() => false); + // A paste reads the clipboard only now, so keys typed after it still come after it. + const followUp = step.paste ? this.pasteData(step.paste) : step.followUp; + if (live() && followUp) queue.write(followUp); + step.resolve(done); + } + if (live()) this.queues.delete(sessionId); + } + + private pasteData(paste: ClaudeDraftPaste): string { + try { + const clipboard = this.options.readClipboard(); + // An image goes the way Claude reads it: Ctrl+V makes Claude read the clipboard itself. + if (clipboard.image) return "\u0016"; + if (!clipboard.text) return ""; + const text = clipboard.text.replace(/\r?\n/g, "\r"); + return paste === "bracketed" ? `\u001b[200~${text}\u001b[201~` : text; + } catch { + return ""; + } + } + + private async roundTrip( + sessionId: string, + action: ClaudeDraftAction, + write: (data: string) => boolean, + live: () => boolean + ): Promise { + const directory = this.directory(sessionId); + const id = String(++this.sequence); + const request = join(directory, `req.${id}`); + const done = join(directory, `done.${id}`); + const draft = join(directory, `draft.${id}`); + mkdirSync(directory, { recursive: true, mode: 0o700 }); + // Written aside and renamed in, so the helper never sees a half-written request. + const staged = join(directory, `staged.${id}`); + rmSync(staged, { force: true }); + writeFileSync(staged, `${action}\n`, { mode: 0o600, flag: "wx" }); + renameSync(staged, request); + try { + if (!write(EXTERNAL_EDITOR_KEY)) { + rmSync(request, { force: true }); + return false; + } + if (!(await this.waitFor(done, live))) { + try { + // Not claimed yet: the Ctrl+G still on its way must change nothing. + renameSync(request, join(directory, `cancel.${id}`)); + return false; + } catch { + // Claimed just now; the helper is finishing this very request. + if (!(await this.waitFor(done, live))) return false; + } + } + if (action !== "clear") { + const stat = lstatSync(draft, { throwIfNoEntry: false }); + const text = stat?.isFile() ? readFileSync(draft, "utf8") : ""; + if (text) this.options.writeClipboard(text); + } + return true; + } finally { + rmSync(done, { force: true }); + rmSync(draft, { force: true }); + } + } + + private async waitFor(path: string, live: () => boolean): Promise { + const deadline = Date.now() + this.timeoutMs; + while (live() && !existsSync(path)) { + if (Date.now() >= deadline) return false; + await new Promise((resolve) => setTimeout(resolve, POLL_MS)); + } + return live(); + } + + private directory(sessionId: string): string { + return join(this.options.root, sessionId); + } +} + +function isSafeId(sessionId: string): boolean { + return /^[A-Za-z0-9_-]{1,128}$/.test(sessionId); +} diff --git a/src/main/services/SettingsStore.ts b/src/main/services/SettingsStore.ts index a4828a440..598188bc8 100644 --- a/src/main/services/SettingsStore.ts +++ b/src/main/services/SettingsStore.ts @@ -52,6 +52,8 @@ import { DEFAULT_HOME_LAYOUT, DEFAULT_RADIAL_LAUNCHER_ITEMS, keyboardPresetShortcuts, + REQUIRED_SHORTCUTS, + CODEX_DRAFT_SHORTCUTS, shortcutsShareContext, DEFAULT_UI_SCALE, HOME_GRID_MAX_COLUMNS, @@ -177,6 +179,7 @@ export class SettingsStore { || !("radialLauncherEnabled" in source) || !("agentLifecycleHooksEnabled" in source) || !("baseProtectionEnabled" in source) + || !("claudeDraftKeysEnabled" in source) || !("uiScale" in source) || !("canvasColor" in source) || !("canvasBackground" in source) @@ -375,6 +378,7 @@ function createDefaults(systemLocale: string, platform: string): AppSettings { radialLauncherEnabled: false, agentLifecycleHooksEnabled: true, baseProtectionEnabled: true, + claudeDraftKeysEnabled: true, uiScale: DEFAULT_UI_SCALE, canvasColor: "sage", canvasBackground: "none", @@ -616,6 +620,10 @@ export function normalizeSettings( baseProtectionEnabled: typeof source.baseProtectionEnabled === "boolean" ? source.baseProtectionEnabled : fallback.baseProtectionEnabled ?? true, + // On unless the person turned it off; an install from before it existed gets it on. + claudeDraftKeysEnabled: typeof source.claudeDraftKeysEnabled === "boolean" + ? source.claudeDraftKeysEnabled + : fallback.claudeDraftKeysEnabled ?? true, uiScale: normalizeUiScale(source.uiScale, fallback.uiScale ?? DEFAULT_UI_SCALE), canvasColor, canvasBackground, @@ -1156,15 +1164,15 @@ function normalizeBrowserCanvas(candidate: unknown, fallback: BrowserCanvasState } function normalizeShortcuts(candidate: unknown, fallback: ShortcutBindings): ShortcutBindings { - const source = candidate && typeof candidate === "object" - ? candidate as Partial - : {}; + const saved = candidate && typeof candidate === "object" ? candidate as Partial : {}; + // Only a macOS host's defaults bind the alternate line break: elsewhere the Codex keys stay as they were. + const source = fallback.codexNewlineAlternate ? migrateCodexShortcuts(saved) : saved; const shortcuts = { ...fallback }; for (const action of Object.keys(fallback) as Array) { const binding = source[action]; const keyboardOnly = !["home", "renameWindow", "toggleFullscreen"].includes(action); if (isValidShortcut(binding) && !(keyboardOnly && binding.includes("Mouse"))) shortcuts[action] = binding; - else if (binding === "" && !["codexSubmit", "codexNewline", "codexSelectAll"].includes(action)) shortcuts[action] = ""; + else if (binding === "" && !REQUIRED_SHORTCUTS.includes(action)) shortcuts[action] = ""; } const accepted: Array = []; @@ -1174,13 +1182,33 @@ function normalizeShortcuts(candidate: unknown, fallback: ShortcutBindings): Sho && shortcuts[action].toLowerCase() === shortcuts[other].toLowerCase()); if (conflict) { // Preserve old customized actions; newly added defaults can be rebound in Settings. - if (source[action] === undefined && !action.startsWith("codex")) shortcuts[action] = ""; + if (source[action] === undefined && !REQUIRED_SHORTCUTS.includes(action) + && (!action.startsWith("codex") || CODEX_DRAFT_SHORTCUTS.includes(action))) shortcuts[action] = ""; else return { ...fallback }; } else accepted.push(action); } return shortcuts; } +/** + * On macOS the Codex editor once had three submit keys (Enter, Ctrl+Enter, Command+Enter) and Shift+Enter + * for a line break; it now has one submit key and two line breaks. Settings from before (extra submit keys, + * no alternate line break) still at those old defaults take the new ones; customized submit and line-break keys are kept, + * the extra submit keys go, and the alternate line break takes the first of its keys still free. + */ +function migrateCodexShortcuts(source: Partial): Partial { + if (source.codexNewlineAlternate || (!source.codexSubmitAlternate && !source.codexSubmitSuper)) return source; + const { codexSubmitAlternate, codexSubmitSuper, ...rest } = source; + const oldDefaults = rest.codexSubmit === "Enter" && codexSubmitAlternate === "Ctrl+Enter" + && codexSubmitSuper === "Meta+Enter" && rest.codexNewline === "Shift+Enter"; + if (oldDefaults) { + const { codexSubmit: _submit, codexNewline: _newline, ...migrated } = rest; + return migrated; + } + const alternate = ["Shift+Enter", "Enter", "Alt+Enter"].find((key) => key !== rest.codexSubmit && key !== rest.codexNewline); + return { ...rest, codexNewlineAlternate: alternate }; +} + function isValidShortcut(value: unknown): value is string { if (typeof value !== "string" || value.length === 0 || value.length > 40) return false; const parts = value.split("+"); diff --git a/src/main/services/TerminalManager.ts b/src/main/services/TerminalManager.ts index 2b70689de..7430c9df1 100644 --- a/src/main/services/TerminalManager.ts +++ b/src/main/services/TerminalManager.ts @@ -1,10 +1,11 @@ import { randomUUID } from "node:crypto"; -import { realpathSync, statSync } from "node:fs"; +import { existsSync, realpathSync, statSync } from "node:fs"; import { basename, dirname } from "node:path"; import { isPathInside } from "../../agent-runtime/path-inside.mjs"; import * as pty from "node-pty"; import type { IPty } from "node-pty"; import type { + ClaudeDraftAction, CreateSessionRequest, GitRiskReport, Point, @@ -58,10 +59,11 @@ import { onDiskPath } from "./onDiskPath.ts"; import { RESULT_CAPTURE_PROVIDERS } from "./resultCapture.ts"; import { launchEffortProblem, launchModelProblem, type ReasoningEffort } from "../../shared/launchModel.ts"; import { SecretRedactionRegistry } from "./safety/SecretRedaction.ts"; +import type { ClaudeDraftEditor, ClaudeDraftPaste } from "./ClaudeDraftEditor.ts"; import type { DecisionSession } from "./DecisionHooks.ts"; import { tryPtyOperation } from "./ptySafety.ts"; import { terminalFailureDetails } from "./terminalFailureDetails.ts"; -import { canResumeThreadById, resolveTerminalLaunch } from "./terminalLaunch.ts"; +import { canResumeThreadById, parseInlineSettings, resolveTerminalLaunch } from "./terminalLaunch.ts"; import { isLaunchProfile, PROFILE_RANK, profileAvailable, profileCeiling, type LaunchProfile } from "../../shared/autoMode.ts"; import type { AgentIsolation, IsolationDecision } from "./isolation/AgentIsolation.ts"; import { controlGrantFolder } from "./isolation/AgentIsolation.ts"; @@ -245,6 +247,10 @@ export class TerminalManager { private environments: EnvironmentService | null = null; // Every text an agent reads from another card passes through it (EP-8). private redaction = new SecretRedactionRegistry(); + // macOS Claude cards: whole-draft copy/cut/clear through Claude's Ctrl+G editor round trip. + private draftEditor: ClaudeDraftEditor | null = null; + // Settings → Agents → Claude draft keys: off, a new Claude gets no helper and the keys do nothing. + private draftKeysOn: () => boolean = () => true; // Where each running card was actually started (an environment may move it) and its agent config folder. private readonly launchContexts = new Map(); private modelCheck: (provider: ProviderId, model: string) => string | null = () => null; @@ -277,6 +283,7 @@ export class TerminalManager { private readonly startingOwners = new Map(); // What a card's first launch found in its CLI's own configuration, before the card exists. private readonly pendingConfiguredModes = new Map(); + private readonly pendingClaudeDrafts = new Set(); // Whether the person acknowledged YOLO for a CLI (Settings: acknowledgedDangerousProfiles); unset allows it. private yoloAcknowledged: (provider: ProviderId) => boolean = () => true; // Set and cleared around a single synchronous session emit (see emitSession): @@ -323,6 +330,14 @@ export class TerminalManager { this.keyboardShortcuts = { ...shortcuts }; } + configureDraftKeys(enabled: () => boolean): void { + this.draftKeysOn = () => { try { return enabled() !== false; } catch { return true; } }; + } + + configureDraftEditor(editor: ClaudeDraftEditor | null): void { + this.draftEditor = editor; + } + /** Plugin agent tools: a session any of them applies to gets the canvastty_agents bridge. */ configureAgentTools(names: ((role: SessionRole, provider: ProviderId) => string[]) | null): void { this.pluginToolNames = names ?? (() => []); @@ -695,7 +710,7 @@ export class TerminalManager { this.initialCodexInputs.set(id, { prompt: request.initialPrompt, imagePath: request.initialImagePath }); } if (control.ownerPluginId !== undefined) this.startingOwners.set(id, control.ownerPluginId); - let launched: ReturnType | { process: null; agentBrowser: null; agentRuntime: null; agentOrchestration: null; failure: null }; + let launched: ReturnType; try { launched = awaitMeasuredGrid || contributed ? { process: null, agentBrowser: null, agentRuntime: null, agentOrchestration: null, failure: null } @@ -710,6 +725,8 @@ export class TerminalManager { const configured = this.pendingConfiguredModes.get(id); this.pendingConfiguredModes.delete(id); if (configured) metadata.configuredMode = configured; + if (launched.nativeEditor) metadata.nativeEditor = launched.nativeEditor; + if (this.pendingClaudeDrafts.delete(id)) metadata.claudeDraft = true; const session: ManagedSession = { metadata, @@ -854,6 +871,8 @@ export class TerminalManager { session.metadata.parentSessionId ); session.process = launched.process; + if (launched.nativeEditor) session.metadata.nativeEditor = launched.nativeEditor; + else delete session.metadata.nativeEditor; session.agentBrowser = launched.agentBrowser; session.agentRuntime = launched.agentRuntime; session.agentOrchestration = launched.agentOrchestration; @@ -949,12 +968,26 @@ export class TerminalManager { if (typeof data !== "string" || data.length === 0) return false; const session = this.sessions.get(id); if (!session || session.metadata.exitCode !== null || !session.process) return false; + if (this.draftEditor?.hold(id, data)) return true; const process = session.process; const written = tryPtyOperation(() => process.write(data)); if (written && ANSWERS_PROMPT.test(data)) this.settleAnsweredPrompt(id, session); return written; } + draftAction(id: string, action: ClaudeDraftAction, followUp: string, paste: ClaudeDraftPaste | null = null): Promise { + const session = this.sessions.get(id); + const process = session?.process; + if (!this.draftEditor || !this.draftKeysOn() || !session || !process || session.metadata.exitCode !== null + || session.metadata.provider !== "claude" || !session.metadata.claudeDraft) return Promise.resolve(false); + return this.draftEditor.run(id, action, followUp, (data) => { + const written = this.sessions.get(id) === session && session.process === process + && tryPtyOperation(() => process.write(data)); + if (written && ANSWERS_PROMPT.test(data)) this.settleAnsweredPrompt(id, session); + return written; + }, paste); + } + /** * A hooked Claude card waits at its permission prompt (needs_approval) and the person answered it. When they declined * (Esc, or "No"), Claude interrupts the turn and runs no Stop hook, and its «✳» title defers to the hooks, so the card @@ -1162,6 +1195,8 @@ export class TerminalManager { this.initialCodexInputs.delete(id); this.redaction.clear(`session:${id}`); this.releaseIsolation(id); + this.draftEditor?.forget(id); + this.pendingClaudeDrafts.delete(id); session.launchToken += 1; void session.launchCleanup?.().catch(() => undefined); session.launchCleanup = null; @@ -1315,6 +1350,7 @@ export class TerminalManager { this.startingModels.delete(descriptor.id); } process = launched.process; + if (launched.nativeEditor) metadata.nativeEditor = launched.nativeEditor; agentBrowser = launched.agentBrowser; agentRuntime = launched.agentRuntime; agentOrchestration = launched.agentOrchestration; @@ -1511,6 +1547,8 @@ export class TerminalManager { session.metadata.parentSessionId ); session.process = launched.process; + if (launched.nativeEditor) session.metadata.nativeEditor = launched.nativeEditor; + else delete session.metadata.nativeEditor; session.agentBrowser = launched.agentBrowser; session.agentRuntime = launched.agentRuntime; session.agentOrchestration = launched.agentOrchestration; @@ -1555,6 +1593,7 @@ export class TerminalManager { agentRuntime: PreparedAgentRuntimePtyLaunch | null; agentOrchestration: PreparedOrchestrationPtyLaunch | null; failure: LaunchFailure | null; + nativeEditor?: SessionMetadata["nativeEditor"]; } { const none = { process: null, agentBrowser: null, agentRuntime: null, agentOrchestration: null }; const decision = this.launchIsolation(id, provider, profile, role, null); @@ -1566,6 +1605,7 @@ export class TerminalManager { return { ...none, failure: planned.failure }; } this.noteConfiguredMode(id, provider, profile, planned.env, planned.cwd); + this.noteClaudeDraft(id, planned.launchEnvironment); let spawn: { command: string; args: string[] | string; env: Record } = planned; if (decision.apply) { try { @@ -1585,6 +1625,9 @@ export class TerminalManager { agentBrowser: planned.agentBrowser, agentRuntime: planned.agentRuntime, agentOrchestration: planned.agentOrchestration, + // The renderer must encode the same editor keys that this local frontend received. + ...(globalThis.process.platform === "darwin" && planned.launchEnvironment.CANVASTTY_CODEX_KEYBOARD + ? { nativeEditor: JSON.parse(planned.launchEnvironment.CANVASTTY_CODEX_KEYBOARD) } : {}), failure: null }; } catch (error) { @@ -1606,6 +1649,19 @@ export class TerminalManager { } } + /** Only a Claude launched with the draft helper as its editor gets the whole-draft keys. */ + private noteClaudeDraft(id: string, launchEnvironment: Readonly>): void { + const granted = Boolean(launchEnvironment.CANVASTTY_DRAFT_DIR); + const target = this.sessions.get(id)?.metadata; + this.pendingClaudeDrafts.delete(id); + if (target) { + if (granted) target.claudeDraft = true; + else delete target.claudeDraft; + } else if (granted) { + this.pendingClaudeDrafts.add(id); + } + } + /** Delegated: a subagent, or a card a plugin started (not the person). */ private isDelegated(id: string, role: SessionRole): boolean { return role === "subagent" || Boolean(this.sessions.get(id)?.extras.ownerPluginId ?? this.startingOwners.get(id)); @@ -1637,6 +1693,8 @@ export class TerminalManager { if (!this.isolation) throw new LaunchRefusal("agent isolation is not configured; the agent was not started without it."); if (typeof planned.args === "string") throw new LaunchRefusal("a Windows batch launcher cannot run inside agent isolation."); const grant = controlGrantFolder(planned.env); + // Claude's draft helper writes its answers in this card's own folder (never another card's). + const draftFolder = this.draftEditor?.folderOf(id) ?? null; const wrapped = this.isolation.wrap({ sessionId: id, provider, @@ -1645,7 +1703,8 @@ export class TerminalManager { args: planned.args, env: planned.env, profile, - ...(grant ? { grantedPrivate: [grant] } : {}) + ...(grant ? { grantedPrivate: [grant] } : {}), + ...(draftFolder ? { ownWritable: [draftFolder] } : {}) }); this.releaseIsolation(id); this.isolationCleanups.set(id, wrapped.cleanup); @@ -1750,7 +1809,28 @@ export class TerminalManager { }; // OpenCode: the project folder in its other Unicode spelling is still this folder, not an external one. if (provider === "opencode") Object.assign(providerEnvironment, openCodeProjectFolderEnvironment({ ...baseEnvironment, ...providerEnvironment }, cwd)); + // A plugin or a remote environment that sets its own editor (in the environment or in its --settings env) keeps + // it; the helper only exists locally. + const contributedNames = new Set([...Object.keys(contribution?.env ?? {}), ...inlineSettingsEnvironmentNames(contribution?.args ?? [])]); + const contributesEditor = ["VISUAL", "EDITOR"].some((key) => contributedNames.has(key)); + let draftEnvironment: Record = {}; + if (provider === "claude" && process.platform === "darwin" && !environmentWrapped && !contributesEditor && this.draftEditor && this.draftKeysOn()) { + draftEnvironment = this.draftEditor.environment(id, baseEnvironment); + } else { + // Whatever ran in this card before has no helper now. + this.draftEditor?.forget(id); + } + Object.assign(providerEnvironment, draftEnvironment); const providerArgs = [...(agentRuntime?.args ?? []), ...(agentBrowser?.args ?? [])]; + // A background Claude session (/bg, /resume, agent view) runs under Claude's own supervisor and gets this + // launch's --settings, not its environment: the helper and the locale go there too. + if (Object.keys(draftEnvironment).length > 0) { + const launched = { ...baseEnvironment, ...providerEnvironment }; + // A locale a plugin or a remote environment sets is its own. + const locale = Object.fromEntries(["LANG", "LC_ALL", "LC_CTYPE"] + .filter((key) => launched[key] && !contributedNames.has(key)).map((key) => [key, launched[key]!])); + providerArgs.push("--settings", JSON.stringify({ env: { ...draftEnvironment, ...locale } })); + } // Stable terminal observations for the CLI controller; leave ordinary launches unchanged. if (captureResult && provider === "codex") providerArgs.push("-c", "tui.animations=false"); // A Codex subagent in the person's folder is not asked to trust it again (this run only, never ~/.codex). @@ -2064,6 +2144,8 @@ export class TerminalManager { return "failed"; } session.process = process; + if (planned.launchEnvironment.CANVASTTY_DRAFT_DIR) metadata.claudeDraft = true; + else delete metadata.claudeDraft; if (planned.launchEnvironment.CANVASTTY_CODEX_KEYBOARD) { metadata.nativeEditor = JSON.parse(planned.launchEnvironment.CANVASTTY_CODEX_KEYBOARD); } else { @@ -2300,7 +2382,8 @@ export function launchSearchPath( } export function terminalEnvironment( - source: Readonly> = process.env + source: Readonly> = process.env, + platform: NodeJS.Platform = process.platform ): Record { const reserved = new Set([ ...Object.values(AGENT_BROWSER_ENV), @@ -2317,13 +2400,40 @@ export function terminalEnvironment( typeof entry[1] === "string" && !reserved.has(entry[0]) && !entry[0].startsWith("CANVASTTY_PLUGIN_HOOK_") + && !entry[0].startsWith("CANVASTTY_DRAFT_") + // A Claude card's draft helper never becomes the editor of a launch made from inside one. + && !(entry[0] === "VISUAL" && entry[1].endsWith("/draft-editor.sh")) && entry[0] !== "CANVASTTY_LIFECYCLE_HOOKS_ENABLED" && entry[0] !== "ELECTRON_RUN_AS_NODE" )) ); + // A Finder-launched app gets no locale, and macOS tools such as pbcopy then + // read UTF-8 as the legacy region encoding (Cyrillic turns into mojibake). + // Like Terminal.app, set LANG to the system's own locale: a full name ssh can pass on. + const hasLocale = ["LC_ALL", "LC_CTYPE", "LANG"].some((name) => environment[name]); + if (platform === "darwin" && !hasLocale) environment.LANG = systemLocale; return { ...environment, TERM: "xterm-256color", COLORTERM: "truecolor" }; } +/** The names a launch's inline --settings set in Claude's env (`--settings ` or `--settings=`). */ +function inlineSettingsEnvironmentNames(args: readonly string[]): string[] { + return args.flatMap((argument, index) => { + const value = argument.startsWith("--settings=") ? argument.slice("--settings=".length) + : args[index - 1] === "--settings" ? argument : null; + const env = value === null ? null : parseInlineSettings(value)?.env; + return env && typeof env === "object" && !Array.isArray(env) ? Object.keys(env) : []; + }); +} + +let systemLocale = "en_US.UTF-8"; + +/** The macOS system locale (such as "ru-RU") as a UTF-8 locale name, or en_US.UTF-8 when the system lacks it. */ +export function setTerminalSystemLocale(locale: string, exists: (path: string) => boolean = existsSync): void { + const match = /^([a-z]{2,3})[-_]([A-Z]{2})(?![A-Za-z])/.exec(locale); + const name = match ? `${match[1]}_${match[2]}.UTF-8` : ""; + systemLocale = name && exists(`/usr/share/locale/${name}`) ? name : "en_US.UTF-8"; +} + function defaultTitle(provider: ProviderId, cwd: string): string { const project = basename(cwd) || cwd; if (provider === "terminal") return `Terminal · ${project}`; diff --git a/src/main/services/isolation/AgentIsolation.ts b/src/main/services/isolation/AgentIsolation.ts index 5d648c290..0a6c78668 100644 --- a/src/main/services/isolation/AgentIsolation.ts +++ b/src/main/services/isolation/AgentIsolation.ts @@ -75,6 +75,8 @@ export interface IsolationLaunch { env: Record; /** Folders under CanvasTTY's private data this launch was handed (its control grant, its account home). */ grantedPrivate?: readonly string[]; + /** Folders under CanvasTTY's private data this launch may also write (its Claude draft folder). */ + ownWritable?: readonly string[]; /** The launch profile: in plan the project is not writable. */ profile?: LaunchProfile; } @@ -90,8 +92,10 @@ export interface WrappedLaunch { /** * CanvasTTY's operating-system isolation layer around an agent's whole process tree (the CLI, its tools, MCP servers * and hooks): macOS seatbelt through sandbox-exec, Linux bubblewrap. It applies to agents the person did not launch - * directly (subagents, plugin-started agents) and to every launch in a profile other than normal (manual), unless - * the person turned it off. It fails closed: when it cannot be set up, the launch is refused, never run without it. + * directly (subagents, plugin-started agents) and to a CLI's contained auto (a bypass that exists only inside the + * layer), unless the person turned it off. An agent the person launched runs as their terminal would run it, with its + * own sandbox and the person's temporary folders. It fails closed: when it cannot be set up, the launch is refused, + * never run without it. */ export class AgentIsolation { private readonly options: AgentIsolationOptions; @@ -139,9 +143,9 @@ export class AgentIsolation { const { provider, delegated } = input; let profile = input.profile; if (provider === "terminal") return { apply: false, profile }; - const wanted = delegated || profile !== "normal"; - if (!wanted) return { apply: false, profile }; const containedAuto = profile === "auto" && autoKind(provider) === "contained"; + const wanted = delegated || containedAuto; + if (!wanted) return { apply: false, profile }; if (input.environment?.isolated) { return { apply: false, profile, isolation: { state: "environment", reason: `Runs in ${input.environment.label}; the isolation layer of this computer does not apply there.` } }; } @@ -192,7 +196,9 @@ export class AgentIsolation { hostEnvironment: this.hostEnvironment, userDataPath: this.options.userDataPath, sessionId: launch.sessionId, + ...(typeof process.getuid === "function" ? { uid: process.getuid() } : {}), ...(launch.grantedPrivate ? { grantedPrivate: launch.grantedPrivate } : {}), + ...(launch.ownWritable ? { ownWritable: launch.ownWritable } : {}), ...(launch.profile === "plan" ? { readOnlyProject: true } : {}) }); // `git init` and `git clone` copy git's template, sample hooks included: an empty one writes no hooks. diff --git a/src/main/services/isolation/isolationPaths.ts b/src/main/services/isolation/isolationPaths.ts index 5cdcb9a5e..88cdb09c0 100644 --- a/src/main/services/isolation/isolationPaths.ts +++ b/src/main/services/isolation/isolationPaths.ts @@ -26,10 +26,14 @@ export interface IsolationPathInput { sessionId: string; /** Folders under CanvasTTY's private data this launch was handed (its own control grant, its account home). */ grantedPrivate?: readonly string[]; + /** Folders under CanvasTTY's private data this launch may also write (its Claude draft folder); read again too. */ + ownWritable?: readonly string[]; /** Extra socket folders this launch may connect to (the control grant's endpoint folder). */ socketFolders?: readonly string[]; /** Plan: the project is readable only (the CLI's own folders stay writable). */ readOnlyProject?: boolean; + /** The person's user id: Claude Code keeps its scratch files in /tmp/claude-, whatever TMPDIR says. */ + uid?: number; } export interface IsolationPaths { @@ -144,7 +148,7 @@ function sensitiveHomeFolders(home: string, xdgConfig: string): string[] { * token-authenticated sockets and per-run hook settings the CLI must read. */ export function privateAppData(userDataPath: string): string[] { - return ["agent-control", "provider-secrets.bin", "plugin-secrets", "account-homes", "github-oauth.json", "launch-runs"] + return ["agent-control", "provider-secrets.bin", "plugin-secrets", "account-homes", "github-oauth.json", "launch-runs", "claude-draft"] .map((name) => join(userDataPath, name)); } @@ -212,7 +216,8 @@ export function isolationPaths(input: IsolationPathInput): IsolationPaths { // variable pointing at HOME or above the project would hide them, so it is not followed. .filter((folder) => !ownFolders.includes(folder) && !hides(folder)); const privateData = privateAppData(input.userDataPath); - const grants = [...(input.grantedPrivate ?? []), join(input.userDataPath, "launch-runs", safeSegment(input.sessionId))]; + const ownWritable = input.ownWritable ?? []; + const grants = [...(input.grantedPrivate ?? []), ...ownWritable, join(input.userDataPath, "launch-runs", safeSegment(input.sessionId))]; const project = input.cwd; const trustedOwn = providerFolders(input.provider, {}, hostHome); const trustedOthers = AGENT_PROVIDERS.filter((provider) => provider !== input.provider).flatMap((provider) => { @@ -259,6 +264,9 @@ export function isolationPaths(input: IsolationPathInput): IsolationPaths { ...(input.readOnlyProject ? [] : [project]), input.sessionTemp, ...ownFolders, + ...ownWritable, + // Claude Code's Bash tool and external editor write here, not in TMPDIR; without it every shell call fails. + ...(input.provider === "claude" && input.uid !== undefined ? [join("/tmp", `claude-${input.uid}`)] : []), join(home, ".npm"), join(home, ".bun"), join(xdg.cache, "npm"), join(xdg.cache, "bun") ]), writableFiles: all(own.files), diff --git a/src/main/services/terminalLaunch.ts b/src/main/services/terminalLaunch.ts index c97d193a8..115ce5037 100644 --- a/src/main/services/terminalLaunch.ts +++ b/src/main/services/terminalLaunch.ts @@ -3,7 +3,7 @@ import { posix, win32 } from "node:path"; import type { ProviderId, ShortcutBindings } from "../../shared/contracts.ts"; import { normalizeThreadId } from "../../agent-runtime/runtime-protocol.mjs"; import { openCodeAutoEnvironment, openCodeYoloEnvironment } from "./openCodeConfig.ts"; -import { autoKind, CLAUDE_SANDBOX_SETTINGS, profileArguments, type LaunchProfile } from "../../shared/autoMode.ts"; +import { autoKind, profileArguments, type LaunchProfile } from "../../shared/autoMode.ts"; import { providerEffortArguments, providerModelArguments, type ReasoningEffort } from "../../shared/launchModel.ts"; import { providerTerminalBatchCommandLine, @@ -86,9 +86,6 @@ export function resolveTerminalLaunch( ...(options.cwd ? { cwd: options.cwd } : {}) }) : undefined; - // Claude Code's own sandbox where CanvasTTY's layer does not run (and the CLI has one on this platform). - const claudeSandbox = provider === "claude" && (profile === "auto" || profile === "acceptEdits") && options.isolated !== true - && (platform === "darwin" || platform === "linux"); const providerArgs = [ ...(provider === "codex" && agentBrowserArgs.includes("-c") ? ["--no-daemon"] : []), ...((profile === "yolo" || containedAuto) && provider !== "opencode" ? DANGEROUS_ARGUMENTS[provider] : []), @@ -96,10 +93,8 @@ export function resolveTerminalLaunch( ? codexInsideIsolation(profile, options.thirdPartyModel === true) : profile !== "normal" && profile !== "yolo" && !containedAuto ? profileArguments(provider, profile, options.thirdPartyModel === true) : []), // Claude Code keeps only the last inline --settings: a plugin's (after the hooks') would silently drop the hooks. - // Its sandbox joins the same one. - ...(provider === "claude" - ? mergeClaudeInlineSettings(claudeSandbox ? [...agentBrowserArgs, "--settings", JSON.stringify({ sandbox: CLAUDE_SANDBOX_SETTINGS })] : agentBrowserArgs) - : agentBrowserArgs), + // Claude's own sandbox is left to the person's Claude settings. + ...(provider === "claude" ? mergeClaudeInlineSettings(agentBrowserArgs) : agentBrowserArgs), ...providerModelArguments(provider, options.model), ...providerEffortArguments(provider, options.effort), ...(options.resumePrevious ? resolveResumeArguments(provider, options.resumeThreadId) : []), @@ -130,7 +125,16 @@ export function resolveTerminalLaunch( args: [launcher, "--backend", providerCli.executable, "--frontend", frontend, "--", ...providerArgs], environment: { ...combinedEnvironment, ELECTRON_RUN_AS_NODE: "1", - ...(options.shortcuts ? { CANVASTTY_CODEX_KEYBOARD: JSON.stringify({ + // The owned macOS frontend reads one submit key and two line breaks; the Linux one, three submit keys. + ...(options.shortcuts ? { CANVASTTY_CODEX_KEYBOARD: JSON.stringify(platform === "darwin" ? { + submit: options.shortcuts.codexSubmit, + newline: options.shortcuts.codexNewline, + newlineAlternate: options.shortcuts.codexNewlineAlternate, + selectAll: options.shortcuts.codexSelectAll, + copy: options.shortcuts.codexCopy, + cut: options.shortcuts.codexCut, + clear: options.shortcuts.codexClear + } : { submit: options.shortcuts.codexSubmit, submitAlternate: options.shortcuts.codexSubmitAlternate, submitSuper: options.shortcuts.codexSubmitSuper, diff --git a/src/preload/index.ts b/src/preload/index.ts index 32f38cf65..d6633cbf3 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -12,6 +12,7 @@ import type { CanvasNavigationOverrideStateEvent, CanvasNavigationPointerBindingInput, CanvasTTYApi, + ClaudeDraftAction, CustomTerminalBorderSkinId, CreateSessionRequest, FileRootReference, @@ -312,6 +313,8 @@ const api: CanvasTTYApi = { create: (request: CreateSessionRequest) => ipcRenderer.invoke(IPC.terminalCreate, request), restart: (id: string, options?: { resume?: boolean }) => ipcRenderer.invoke(IPC.terminalRestart, id, options), input: (id: string, data: string) => ipcRenderer.send(IPC.terminalInput, id, data), + draftAction: (id: string, action: ClaudeDraftAction, followUp?: string, paste?: "plain" | "bracketed") => + ipcRenderer.invoke(IPC.terminalDraftAction, id, action, followUp ?? "", paste ?? null), resize: (id: string, cols: number, rows: number) => ipcRenderer.send(IPC.terminalResize, id, cols, rows), setBounds: (id: string, bounds: SessionBounds) => ipcRenderer.send(IPC.terminalBounds, id, bounds), rename: (id: string, title: string) => ipcRenderer.invoke(IPC.terminalRename, id, title), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index cb72f6485..89575abad 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -144,6 +144,7 @@ const FALLBACK_SETTINGS: AppSettings = { radialLauncherEnabled: false, agentLifecycleHooksEnabled: true, baseProtectionEnabled: true, + claudeDraftKeysEnabled: true, uiScale: DEFAULT_UI_SCALE, canvasColor: "sage", canvasBackground: "none", diff --git a/src/renderer/src/components/ShortcutReference.tsx b/src/renderer/src/components/ShortcutReference.tsx index 2f736c8af..d9c650735 100644 --- a/src/renderer/src/components/ShortcutReference.tsx +++ b/src/renderer/src/components/ShortcutReference.tsx @@ -43,13 +43,30 @@ export function ShortcutReference({ settings, onClose }: { [[bindings.terminalPageUp, bindings.terminalPageDown], "shortcutScrollPages"], [["Enter", "Shift+Enter"], "shortcutSearchMatches"] ] }, - { title: "keyboardCodex", shortcuts: [ + { title: "keyboardCodex", shortcuts: mac ? [ + [[bindings.codexSubmit], "keyboardSubmit"], + [[bindings.codexNewline], "keyboardNewline"], + [[bindings.codexNewlineAlternate], "keyboardNewlineAlternate"], + [[bindings.codexSelectAll], "keyboardSelectDraft"], + [[bindings.codexCopy], "keyboardClaudeCopy"], + [[bindings.codexCut], "keyboardClaudeCut"], + [[bindings.codexClear], "keyboardClaudeClear"] + ] : [ [[bindings.codexSubmit], "keyboardSubmit"], [[bindings.codexSubmitAlternate], "keyboardSubmitAlternate"], [[bindings.codexSubmitSuper], "keyboardSubmitSuper"], [[bindings.codexNewline], "shortcutLineBreak"], [[bindings.codexSelectAll], "keyboardSelectAll"] - ] } + ] }, + ...(mac && settings.claudeDraftKeysEnabled ? [{ title: "keyboardClaude" as const, shortcuts: [ + [[bindings.claudeSubmit], "keyboardSubmit"], + [[bindings.claudeNewline], "keyboardNewline"], + [[bindings.claudeNewlineAlternate], "keyboardNewlineAlternate"], + [[bindings.claudeSelectAll], "keyboardSelectDraft"], + [[bindings.claudeCopy], "keyboardClaudeCopy"], + [[bindings.claudeCut], "keyboardClaudeCut"], + [[bindings.claudeClear], "keyboardClaudeClear"] + ] as [string[], TranslationKey][] }] : []) ]; const contexts: [string[], TranslationKey][] = [ [["↑ ↓", "Enter"], "shortcutPaletteNavigation"], diff --git a/src/renderer/src/features/settings/SettingsPanel.tsx b/src/renderer/src/features/settings/SettingsPanel.tsx index db4619189..c74ae4f42 100644 --- a/src/renderer/src/features/settings/SettingsPanel.tsx +++ b/src/renderer/src/features/settings/SettingsPanel.tsx @@ -52,6 +52,7 @@ import type { import { BROWSER_PROVIDER_COLORS, keyboardPresetShortcuts, + REQUIRED_SHORTCUTS, shortcutsShareContext, BUNDLED_CANVAS_BACKGROUND_IDS, CANVAS_LAUNCHER_ITEMS, @@ -130,7 +131,11 @@ const SHORTCUT_LABELS = { terminalCopy: "shortcutCopySelection", terminalPaste: "shortcutPaste", terminalSearch: "terminalSearch", terminalRestart: "shortcutRestartExited", terminalPageUp: "keyboardPageUp", terminalPageDown: "keyboardPageDown", codexSubmit: "keyboardSubmit", codexSubmitAlternate: "keyboardSubmitAlternate", codexSubmitSuper: "keyboardSubmitSuper", - codexNewline: "shortcutLineBreak", codexSelectAll: "keyboardSelectAll" + codexNewline: "shortcutLineBreak", codexNewlineAlternate: "keyboardNewlineAlternate", codexSelectAll: "keyboardSelectAll", + codexCopy: "keyboardClaudeCopy", codexCut: "keyboardClaudeCut", codexClear: "keyboardClaudeClear", + claudeSubmit: "keyboardSubmit", claudeNewline: "keyboardNewline", claudeNewlineAlternate: "keyboardNewlineAlternate", + claudeSelectAll: "keyboardSelectDraft", + claudeCopy: "keyboardClaudeCopy", claudeCut: "keyboardClaudeCut", claudeClear: "keyboardClaudeClear" } as const; const SETTINGS_SECTIONS: ReadonlyArray<{ @@ -591,7 +596,7 @@ export function SettingsPanel({ setCapturing(null); setShortcutError(null); void onChange({ keyboardPreset, ...(keyboardPreset === "custom" ? {} : { - shortcuts: keyboardPresetShortcuts(keyboardPreset), + shortcuts: keyboardPresetShortcuts(keyboardPreset, window.canvasTTY.window.isMacOS), canvasWheelOverride: keyboardPreset === "macos" ? "Meta" : "Ctrl", canvasNavigationOverride: "Alt" }) }); @@ -603,10 +608,22 @@ export function SettingsPanel({ {([ ["keyboardCanvas", ["home", "renameWindow", "toggleFullscreen", "commandPalette", "openSettings", "focusUp", "focusDown", "focusLeft", "focusRight", "toggleDetail"]], ["keyboardTerminal", ["terminalCopy", "terminalPaste", "terminalSearch", "terminalRestart", "terminalPageUp", "terminalPageDown"]], - ["keyboardCodex", ["codexSubmit", "codexSubmitAlternate", "codexSubmitSuper", "codexNewline", "codexSelectAll"]] - ] as const).map(([group, actions]) => ( + ["keyboardCodex", window.canvasTTY.window.isMacOS + ? ["codexSubmit", "codexNewline", "codexNewlineAlternate", "codexSelectAll", "codexCopy", "codexCut", "codexClear"] as ShortcutAction[] + : ["codexSubmit", "codexSubmitAlternate", "codexSubmitSuper", "codexNewline", "codexSelectAll"] as ShortcutAction[]], + ["keyboardClaude", ["claudeSubmit", "claudeNewline", "claudeNewlineAlternate", "claudeSelectAll", "claudeCopy", "claudeCut", "claudeClear"]] + ] as const).filter(([group]) => group !== "keyboardClaude" || window.canvasTTY.window.isMacOS).map(([group, actions]) => (

{t(locale, group)}

+ {group === "keyboardClaude" && ( + + void onChange({ claudeDraftKeysEnabled: value === "on" })} + /> + + )} {actions.map((action) => ( captureShortcut(action, event)} onPointerDown={(event) => capturePointerShortcut(action, event)} disableLabel={t(locale, "disabled")} - onDisable={["codexSubmit", "codexNewline", "codexSelectAll"].includes(action) ? undefined : () => { + onDisable={REQUIRED_SHORTCUTS.includes(action) ? undefined : () => { setCapturing(null); setShortcutError(null); void onChange({ keyboardPreset: "custom", shortcuts: { ...settings.shortcuts, [action]: "" } }); diff --git a/src/renderer/src/features/terminal/TerminalCard.tsx b/src/renderer/src/features/terminal/TerminalCard.tsx index b32ada7a6..5bd37f521 100644 --- a/src/renderer/src/features/terminal/TerminalCard.tsx +++ b/src/renderer/src/features/terminal/TerminalCard.tsx @@ -35,6 +35,9 @@ import { attachTerminalCopyOnSelect } from "./terminalCopyOnSelect"; import { CODEX_SELECT_ALL_SEQUENCE, SHIFT_ENTER_SEQUENCE, + claudeDraftKeyIntent, + claudeEnterSequence, + claudePromptRows, codexEnterSequence, codexShortcutSequence, shouldCopyTerminalSelection, @@ -84,6 +87,8 @@ interface TerminalCardProps { focusActivation: FocusActivation; invertTerminalWheel: boolean; copyOnSelect: boolean; + /** Settings → Agents → Claude draft keys; off, the keys reach Claude as they are. */ + claudeDraftKeys: boolean; captureCanvasWheelOverWidgets: boolean; focused: boolean; focusChangeSource: "explicit" | "hover"; @@ -164,6 +169,7 @@ function TerminalCardView({ focusActivation, invertTerminalWheel, copyOnSelect, + claudeDraftKeys, captureCanvasWheelOverWidgets, focused, focusChangeSource, @@ -212,6 +218,12 @@ function TerminalCardView({ sessionExited.current = session.exitCode !== null; const sessionStartedAt = useRef(session.startedAt); sessionStartedAt.current = session.startedAt; + const claudeDraftSelected = useRef(false); + const claudeDraftRef = useRef(session.claudeDraft === true && claudeDraftKeys); + claudeDraftRef.current = session.claudeDraft === true && claudeDraftKeys; + // The Claude editor's Enter keys need no draft helper: they follow the setting in every Claude card. + const claudeKeysRef = useRef(claudeDraftKeys); + claudeKeysRef.current = claudeDraftKeys; const restartAction = useRef<(resume?: boolean) => Promise>(async () => undefined); const invertTerminalWheelRef = useRef(invertTerminalWheel); invertTerminalWheelRef.current = invertTerminalWheel; @@ -555,9 +567,102 @@ function TerminalCardView({ } }; fitRef.current = fit; + const pasteClipboard = (withImages: boolean): void => { + const pasteStartedAt = sessionStartedAt.current; + const acceptsPaste = () => terminalRef.current === terminal && !sessionExited.current + && sessionStartedAt.current === pasteStartedAt; + if (!acceptsPaste()) return; + void (withImages ? window.canvasTTY.clipboard.hasImage() : Promise.resolve(false)) + .then(async (hasImage) => { + if (!acceptsPaste()) return; + if (hasImage) { + window.canvasTTY.terminal.input(session.id, "\u0016"); + return; + } + const text = await window.canvasTTY.clipboard.readText(); + if (text && acceptsPaste()) terminal.paste(text); + }) + .catch(() => undefined); + }; + // Claude runs fullscreen with mouse reporting on, where xterm drops its own selection at the + // first mouse move, so the draft selection is a CanvasTTY layer over the prompt rows instead. + const draftHighlight = document.createElement("div"); + draftHighlight.className = "terminal-card__draft-highlight"; + draftHighlight.hidden = true; + screen?.append(draftHighlight); + const visiblePromptRows = () => { + const buffer = terminal.buffer.active; + return claudePromptRows(Array.from({ length: terminal.rows }, (_, row) => ( + buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? "" + ))); + }; + // The launch the selection belongs to; a restarted Claude has a new draft. + let draftSelectedAt = 0; + const placeDraftHighlight = (): void => { + // The visible prompt rows show the selection; the action always covers the whole draft. + const rows = claudeDraftSelected.current ? visiblePromptRows() : null; + const rowHeight = (draftHighlight.parentElement?.clientHeight ?? 0) / terminal.rows; + draftHighlight.hidden = !rows || !rowHeight; + if (!rows || !rowHeight) return; + draftHighlight.style.top = `${rows.first * rowHeight}px`; + draftHighlight.style.height = `${(rows.last - rows.first + 1) * rowHeight}px`; + }; + const deselectClaudeDraft = (): void => { + claudeDraftSelected.current = false; + draftHighlight.hidden = true; + }; + const selectClaudeDraft = (): void => { + // Only a prompt on screen can be selected: no hidden selection behind a dialog or a startup screen. + if (!visiblePromptRows()) { + deselectClaudeDraft(); + return; + } + claudeDraftSelected.current = true; + draftSelectedAt = sessionStartedAt.current; + placeDraftHighlight(); + }; + // Claude repaints the prompt as it streams or resizes; the layer follows it. + const draftRepaint = terminal.onWriteParsed(() => { + if (claudeDraftSelected.current) placeDraftHighlight(); + }); + const draftResize = terminal.onResize(() => { + if (claudeDraftSelected.current) placeDraftHighlight(); + }); + // A click or a mouse selection replaces the draft selection; moving the mouse does not. + const draftMouseDown = (): void => deselectClaudeDraft(); + terminal.element?.addEventListener("mousedown", draftMouseDown, true); terminal.attachCustomKeyEventHandler((event) => { + if (claudeDraftSelected.current && (draftSelectedAt !== sessionStartedAt.current || !claudeDraftRef.current)) { + deselectClaudeDraft(); + } + let draftIntent = claudeDraftKeyIntent(event, window.canvasTTY.window.isMacOS && claudeDraftRef.current, + session.provider, claudeDraftSelected.current, shortcutsRef.current); + // The prompt gave way to a dialog: the key is the dialog's, not an edit of the draft. + if (draftIntent !== null && draftIntent !== "select" && draftIntent !== "swallow" + && claudeDraftSelected.current && !visiblePromptRows()) draftIntent = "deselect"; + if (draftIntent === "deselect") deselectClaudeDraft(); + else if (draftIntent !== null) { + event.preventDefault(); + event.stopPropagation(); + if (draftIntent === "select") selectClaudeDraft(); + else if (draftIntent === "copy") void window.canvasTTY.terminal.draftAction(session.id, "copy"); + else if (draftIntent !== "swallow") { + deselectClaudeDraft(); + const action = draftIntent === "cut" ? "cut" : "clear"; + const followUp = draftIntent === "replace" ? event.key : ""; + // The paste is typed in turn after the clear, so keys pressed meanwhile stay after it. + const paste = draftIntent !== "paste" ? undefined : terminal.modes.bracketedPasteMode ? "bracketed" : "plain"; + void window.canvasTTY.terminal.draftAction(session.id, action, followUp, paste); + } + return false; + } const editor = nativeEditorRef.current; - if (editor && Object.values(editor).some((binding) => matchesShortcut(event, binding))) { + const editorKeys = editor ? Object.entries(editor).filter(([, binding]) => matchesShortcut(event, binding)) : []; + // Selected output text keeps the terminal's Copy; a plain delete key reaches Codex as it is. + const editorKey = editor && editorKeys.length > 0 + && !(terminal.hasSelection() && matchesShortcut(event, shortcutsRef.current.terminalCopy)) + && !(editorKeys.length === 1 && editorKeys[0]![0] === "clear" && !editorKeys[0]![1].includes("+")); + if (editor && editorKey) { const sequence = codexShortcutSequence(event); if (sequence !== null) { event.preventDefault(); @@ -574,6 +679,15 @@ function TerminalCardView({ window.canvasTTY.terminal.input(session.id, codexEnter); return false; } + const claudeEnter = claudeKeysRef.current + ? claudeEnterSequence(event, window.canvasTTY.window.isMacOS, session.provider, shortcutsRef.current) : null; + // Only Claude's prompt box takes the editor's submit and newline; a dialog or a menu keeps Enter. + if (claudeEnter !== null && visiblePromptRows()) { + event.preventDefault(); + event.stopPropagation(); + window.canvasTTY.terminal.input(session.id, claudeEnter); + return false; + } const selectCodexDraft = nativeEditorRef.current ? false : shouldSelectCodexDraft(event, window.canvasTTY.window.isMacOS, session.provider); if (selectCodexDraft) { @@ -633,21 +747,7 @@ function TerminalCardView({ event.preventDefault(); event.stopPropagation(); - const pasteStartedAt = sessionStartedAt.current; - const acceptsPaste = () => terminalRef.current === terminal && !sessionExited.current - && sessionStartedAt.current === pasteStartedAt; - if (!acceptsPaste()) return false; - void (event.metaKey ? window.canvasTTY.clipboard.hasImage() : Promise.resolve(false)) - .then(async (hasImage) => { - if (!acceptsPaste()) return; - if (hasImage) { - window.canvasTTY.terminal.input(session.id, "\u0016"); - return; - } - const text = await window.canvasTTY.clipboard.readText(); - if (text && acceptsPaste()) terminal.paste(text); - }) - .catch(() => undefined); + pasteClipboard(event.metaKey); return false; }); const detachMouseCoordinateAdapter = screen @@ -724,6 +824,10 @@ function TerminalCardView({ pinnedScroll.dispose(); pinnedCursor.dispose(); pinnedOutput.dispose(); + draftRepaint.dispose(); + draftResize.dispose(); + terminal.element?.removeEventListener("mousedown", draftMouseDown, true); + draftHighlight.remove(); pinnedRefresh.dispose(); if (pinnedFitFrame !== null) cancelAnimationFrame(pinnedFitFrame); if (pinnedInputRefreshRef.current === updatePinnedInput) pinnedInputRefreshRef.current = null; diff --git a/src/renderer/src/features/terminal/terminalShortcuts.ts b/src/renderer/src/features/terminal/terminalShortcuts.ts index 340845cef..17f300411 100644 --- a/src/renderer/src/features/terminal/terminalShortcuts.ts +++ b/src/renderer/src/features/terminal/terminalShortcuts.ts @@ -45,6 +45,76 @@ export function codexEnterSequence(event: TerminalKeyEvent, provider: string): s return modifiers === 1 ? "\r" : `\u001b[13;${modifiers}u`; } +/** True for the Claude editor keys on a macOS Claude card ("Claude draft keys" on); other platforms keep theirs. */ +function claudeEditorKey(event: TerminalKeyEvent, isMacOS: boolean, provider: string): boolean { + return isMacOS && provider === "claude" && event.type === "keydown" && !event.isComposing; +} + +/** + * What the Claude editor's submit and newline keys send while Claude's prompt box is on screen: submit is + * Claude's own Enter, newline is Shift+Enter. The caller checks the prompt box; elsewhere (dialogs, menus + * without a prompt) Enter keeps its usual meaning. null: not one of these keys. + */ +export function claudeEnterSequence( + event: TerminalKeyEvent, + isMacOS: boolean, + provider: string, + bindings: Pick +): string | null { + if (!claudeEditorKey(event, isMacOS, provider)) return null; + if (bindings.claudeSubmit && matchesShortcut(event, bindings.claudeSubmit)) return "\r"; + if ([bindings.claudeNewline, bindings.claudeNewlineAlternate].some((binding) => binding && matchesShortcut(event, binding))) { + return SHIFT_ENTER_SEQUENCE; + } + return null; +} + +/** + * What a key does to a macOS Claude card's whole-draft selection (Claude editor "select" key, Command+A by + * default). Claude has no selection of its own, so CanvasTTY keeps it: the copy key copies the draft, the cut + * key cuts it, typing, the terminal paste key or the delete key replace it, any other key drops the selection + * and reaches Claude as usual. Without a selection the cut key does nothing. An empty binding is switched off. + * null: not a draft key, handle the event normally. + */ +export type ClaudeDraftKeyIntent = "select" | "copy" | "cut" | "clear" | "replace" | "paste" | "swallow" | "deselect"; + +export type ClaudeDraftBindings = Pick; + +const MODIFIER_KEYS = new Set(["Shift", "Meta", "Alt", "Control", "CapsLock", "Fn"]); + +export function claudeDraftKeyIntent( + event: TerminalKeyEvent, + isMacOS: boolean, + provider: string, + selected: boolean, + bindings: ClaudeDraftBindings +): ClaudeDraftKeyIntent | null { + if (!claudeEditorKey(event, isMacOS, provider) || MODIFIER_KEYS.has(event.key)) return null; + const pressed = (binding: string) => binding !== "" && matchesShortcut(event, binding); + // A held shortcut repeats; only its first press acts, so holding the cut key cannot fire a burst of cuts. + const once = (intent: ClaudeDraftKeyIntent): ClaudeDraftKeyIntent => event.repeat ? "swallow" : intent; + if (pressed(bindings.claudeSelectAll)) return once("select"); + if (pressed(bindings.claudeCut)) return selected ? once("cut") : "swallow"; + if (!selected) return null; + if (pressed(bindings.claudeCopy)) return once("copy"); + if (pressed(bindings.terminalPaste)) return once("paste"); + // The Mac delete key is Backspace; forward delete (fn+delete) clears the selection with it. + if (pressed(bindings.claudeClear) || (bindings.claudeClear === "Backspace" && pressed("Delete"))) return "clear"; + if (event.metaKey || event.ctrlKey) return "deselect"; + return [...event.key].length === 1 ? "replace" : "deselect"; +} + +/** Rows of Claude's prompt box on screen: between the last two horizontal rules. */ +export function claudePromptRows(lines: readonly string[]): { first: number; last: number } | null { + const rules: number[] = []; + for (let row = lines.length - 1; row >= 0 && rules.length < 2; row -= 1) { + if (/^─{20,}/.test(lines[row]!.trimStart())) rules.push(row); + } + if (rules.length < 2 || rules[0]! - rules[1]! < 2) return null; + return { first: rules[1]! + 1, last: rules[0]! - 1 }; +} + export function shouldSelectCodexDraft(event: TerminalKeyEvent, isMacOS: boolean, provider: string): boolean { return isMacOS && provider === "codex" && event.type === "keydown" diff --git a/src/renderer/src/features/workspace/WorkspaceCanvas.tsx b/src/renderer/src/features/workspace/WorkspaceCanvas.tsx index 6fef8d6a7..0672a4408 100644 --- a/src/renderer/src/features/workspace/WorkspaceCanvas.tsx +++ b/src/renderer/src/features/workspace/WorkspaceCanvas.tsx @@ -1208,6 +1208,7 @@ export function WorkspaceCanvas(props: WorkspaceCanvasProps): React.JSX.Element focusActivation={settings.focusActivation} invertTerminalWheel={settings.invertTerminalWheel} copyOnSelect={settings.copyOnSelect} + claudeDraftKeys={settings.claudeDraftKeysEnabled} captureCanvasWheelOverWidgets={routeWidgetWheelToCanvas || widgetFocus.id !== terminalCanvasWidgetId(session.id)} focused={widgetFocus.id === terminalCanvasWidgetId(session.id)} focusChangeSource={widgetFocus.source} @@ -1401,6 +1402,7 @@ export function WorkspaceCanvas(props: WorkspaceCanvasProps): React.JSX.Element focusActivation={settings.focusActivation} invertTerminalWheel={settings.invertTerminalWheel} copyOnSelect={settings.copyOnSelect} + claudeDraftKeys={settings.claudeDraftKeysEnabled} captureCanvasWheelOverWidgets={false} focused={widgetFocus.id === terminalCanvasWidgetId(session.id)} focusChangeSource={widgetFocus.source} diff --git a/src/renderer/src/lib/i18n.ts b/src/renderer/src/lib/i18n.ts index b69e9190a..7a0c2f072 100644 --- a/src/renderer/src/lib/i18n.ts +++ b/src/renderer/src/lib/i18n.ts @@ -139,6 +139,13 @@ const ru = { keyboardSubmitAlternate: "Отправка — дополнительное сочетание", keyboardSubmitSuper: "Отправка — Command/Super", keyboardSelectAll: "Выделить весь черновик", + keyboardClaude: "Редактор Claude", + keyboardNewline: "Перенос строки", + keyboardNewlineAlternate: "Перенос строки — дополнительное сочетание", + keyboardSelectDraft: "Выделить черновик", + keyboardClaudeCopy: "Копировать черновик", + keyboardClaudeCut: "Вырезать черновик", + keyboardClaudeClear: "Удалить черновик", appearance: "Оформление", agents: "Агенты", about: "О приложении", @@ -1028,7 +1035,8 @@ const ru = { filesNoMatches: "Нет совпадающих файлов", filesError: "Не удалось прочитать", baseProtection: "Базовая защита", - baseProtectionDescription: "Запрещает агентам (Claude Code, Codex, Qwen Code, OpenCode на этом компьютере) sudo, curl | sh, запуск скачанного, команды для дисков, форк-бомбы и запись или удаление вне рабочей папки, включая /tmp. Только запрещает, ничего не разрешает. Действует для агентов, запущенных после изменения." + baseProtectionDescription: "Запрещает агентам (Claude Code, Codex, Qwen Code, OpenCode на этом компьютере) sudo, curl | sh, запуск скачанного, команды для дисков, форк-бомбы и запись или удаление вне рабочей папки, включая /tmp. Только запрещает, ничего не разрешает. Действует для агентов, запущенных после изменения.", + claudeDraftKeys: "Клавиши черновика Claude" } as const; const en: Record = { @@ -1170,6 +1178,13 @@ const en: Record = { keyboardSubmitAlternate: "Submit — alternate shortcut", keyboardSubmitSuper: "Submit — Command/Super shortcut", keyboardSelectAll: "Select entire draft", + keyboardClaude: "Claude editor", + keyboardNewline: "Line break", + keyboardNewlineAlternate: "Line break — alternate shortcut", + keyboardSelectDraft: "Select draft", + keyboardClaudeCopy: "Copy draft", + keyboardClaudeCut: "Cut draft", + keyboardClaudeClear: "Delete draft", appearance: "Appearance", agents: "Agents", about: "About", @@ -2059,7 +2074,8 @@ const en: Record = { filesNoMatches: "No files matched", filesError: "Failed to read", baseProtection: "Base protection", - baseProtectionDescription: "Blocks agents (Claude Code, Codex, Qwen Code, OpenCode on this computer) from sudo, curl | sh, running downloads, disk commands, fork bombs, and writing or deleting outside the working folder, /tmp included. It only blocks and never allows. Applies to agents started after a change." + baseProtectionDescription: "Blocks agents (Claude Code, Codex, Qwen Code, OpenCode on this computer) from sudo, curl | sh, running downloads, disk commands, fork bombs, and writing or deleting outside the working folder, /tmp included. It only blocks and never allows. Applies to agents started after a change.", + claudeDraftKeys: "Claude draft keys" }; export type TranslationKey = keyof typeof ru; diff --git a/src/renderer/src/lib/shortcuts.ts b/src/renderer/src/lib/shortcuts.ts index 0b037c770..b44601f35 100644 --- a/src/renderer/src/lib/shortcuts.ts +++ b/src/renderer/src/lib/shortcuts.ts @@ -63,7 +63,7 @@ export function isRenameInputTarget(target: EventTarget | null): boolean { } /** - * Renderer-owned editing includes terminal surfaces and shortcut recorders: both need Command+C/V/A delivered + * Renderer-owned editing includes terminal surfaces and shortcut recorders: both need Command+C/V/A/X delivered * as keyboard events. The terminal-named focus API also covers these recorder controls. Ordinary fields and plugin * pages (an iframe is the active element) use the menu's native editing. */ diff --git a/src/renderer/src/styles/app.css b/src/renderer/src/styles/app.css index f4786c22b..1296bb3ce 100644 --- a/src/renderer/src/styles/app.css +++ b/src/renderer/src/styles/app.css @@ -615,6 +615,15 @@ button { border: 0; } Keep the surface and terminal geometry while suspending the screen's renderer. */ .terminal-card__surface[data-suspended="true"] .xterm-screen { display: none; } .terminal-card__surface .xterm-viewport { background-color: var(--terminal-background, #202430); } +/* Claude draft selection (Command+A); same tint as the terminal selection. */ +.terminal-card__draft-highlight { + position: absolute; + left: 0; + right: 0; + z-index: 5; + background: #7b789966; + pointer-events: none; +} .terminal-card__summary { position: absolute; inset: var(--card-header-height) 0 0; width: 100%; height: calc(100% - var(--card-header-height)); display: none; align-items: center; justify-content: center; overflow: hidden; padding: 0; color: white; background: var(--terminal-background, #202430); cursor: zoom-in; text-align: left; } .terminal-card__summary[data-focus-activation="off"] { cursor: pointer; } .terminal-card__summary:hover { background: #242936; } diff --git a/src/shared/autoMode.ts b/src/shared/autoMode.ts index fe17cc28d..e745c3448 100644 --- a/src/shared/autoMode.ts +++ b/src/shared/autoMode.ts @@ -38,7 +38,7 @@ export interface AutoModeFlags { readonly plan: readonly string[]; } -/** The native flag table. Claude's sandbox is not a flag but an inline settings block (CLAUDE_SANDBOX_SETTINGS). */ +/** The native flag table. Claude's own sandbox follows the person's Claude settings; CanvasTTY does not switch it on. */ export const AUTO_MODE: Readonly>> = Object.freeze({ // claude --help: `--permission-mode ` (choices: "acceptEdits", "auto", "bypassPermissions", "manual", // "dontAsk", "plan"). @@ -64,15 +64,7 @@ export const AUTO_MODE: Readonly>> = O acceptEdits: ["--permission-mode", "acceptEdits"], plan: ["--permission-mode", "plan"] } -}); - -/** - * Claude Code's sandbox, merged into the one inline `--settings` CanvasTTY passes, where CanvasTTY's own isolation - * layer does not run (macOS does not let a sandbox start inside another one). `autoAllowBashIfSandboxed` defaults to - * true, which would run every sandboxed command without its classifier or a prompt, so it is off; so is - * `allowUnsandboxedCommands`, which would let a command leave the sandbox. - */ -export const CLAUDE_SANDBOX_SETTINGS = Object.freeze({ enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: false }); + }); /** * Agents whose modes are a per-run permission configuration instead of a flag: OpenCode (1.18) has no auto flag, so its diff --git a/src/shared/contracts.ts b/src/shared/contracts.ts index 12db40b04..31a5b6b9e 100644 --- a/src/shared/contracts.ts +++ b/src/shared/contracts.ts @@ -188,10 +188,25 @@ export interface ShortcutBindings { terminalPageUp: string; terminalPageDown: string; codexSubmit: string; + /** Linux and Windows only; off on macOS. */ codexSubmitAlternate: string; codexSubmitSuper: string; codexNewline: string; + /** The owned macOS frontend only; off elsewhere. */ + codexNewlineAlternate: string; codexSelectAll: string; + /** The owned macOS frontend only, on a selected draft; off elsewhere. */ + codexCopy: string; + codexCut: string; + codexClear: string; + /** macOS Claude cards while Claude's prompt box is on screen ("Claude draft keys" on). */ + claudeSubmit: string; + claudeNewline: string; + claudeNewlineAlternate: string; + claudeSelectAll: string; + claudeCopy: string; + claudeCut: string; + claudeClear: string; } export const DEFAULT_SHORTCUTS: ShortcutBindings = { @@ -215,10 +230,34 @@ export const DEFAULT_SHORTCUTS: ShortcutBindings = { codexSubmitAlternate: "Ctrl+Enter", codexSubmitSuper: "Meta+Enter", codexNewline: "Shift+Enter", - codexSelectAll: "Ctrl+A" + codexNewlineAlternate: "", + codexSelectAll: "Ctrl+A", + codexCopy: "", + codexCut: "", + codexClear: "", + claudeSubmit: "Meta+Enter", + claudeNewline: "Enter", + claudeNewlineAlternate: "Shift+Enter", + claudeSelectAll: "Meta+A", + claudeCopy: "Meta+C", + claudeCut: "Meta+X", + claudeClear: "Backspace" }; -export function keyboardPresetShortcuts(preset: Exclude): ShortcutBindings { +/** The owned Codex frontend reads its editor keys this way on a macOS host only; elsewhere they stay as they were. */ +const MACOS_CODEX_EDITOR = { + codexSubmit: "Meta+Enter", codexSubmitAlternate: "", codexSubmitSuper: "", + codexNewline: "Enter", codexNewlineAlternate: "Shift+Enter", codexSelectAll: "Meta+A", + codexCopy: "Meta+C", codexCut: "Meta+X", codexClear: "Backspace" +} as const; + +/** Keys for a selected Codex draft: they clash with the Codex editor's keys, not with the terminal's Copy. */ +export const CODEX_DRAFT_SHORTCUTS: readonly ShortcutAction[] = ["codexCopy", "codexCut", "codexClear"]; + +export function keyboardPresetShortcuts( + preset: Exclude, + macHost: boolean = preset === "macos" +): ShortcutBindings { return { ...DEFAULT_SHORTCUTS, toggleFullscreen: preset === "macos" ? "Meta+F" : "F11", @@ -226,15 +265,26 @@ export function keyboardPresetShortcuts(preset: Exclude action.startsWith("terminal") || action.startsWith("codex"); - return left === "toggleDetail" || right === "toggleDetail" || terminal(left) === terminal(right); + if (CODEX_DRAFT_SHORTCUTS.includes(left) || CODEX_DRAFT_SHORTCUTS.includes(right)) { + return left === "toggleDetail" || right === "toggleDetail" || (left.startsWith("codex") && right.startsWith("codex")); + } + const context = (action: ShortcutAction) => action.startsWith("claude") ? "claude" + : action.startsWith("terminal") || action.startsWith("codex") ? "terminal" : "canvas"; + return left === "toggleDetail" || right === "toggleDetail" || context(left) === context(right); } +/** Editor actions that always keep a key: without them the prompt cannot be sent, broken or selected. */ +export const REQUIRED_SHORTCUTS: readonly ShortcutAction[] = [ + "codexSubmit", "codexNewline", "codexNewlineAlternate", "codexSelectAll", "claudeSubmit", "claudeNewline", "claudeNewlineAlternate", "claudeSelectAll" +]; + export const INITIAL_TERMINAL_COLS = 80; export const INITIAL_TERMINAL_ROWS = 24; @@ -248,6 +298,9 @@ export interface Size { height: number; } +/** Whole-draft operations CanvasTTY performs for Claude Code on macOS (Command+A/C/X, replace-on-type). */ +export type ClaudeDraftAction = "copy" | "cut" | "clear"; + export interface SessionBounds { position: Point; size: Size; @@ -493,6 +546,8 @@ export interface AppSettings { agentLifecycleHooksEnabled: boolean; /** Base protection: deny-only hard rules for agents' tool calls (writes outside the folder, sudo, …). */ baseProtectionEnabled: boolean; + /** macOS Claude cards: Command+A selects the whole prompt draft for copy, cut and delete (Claude's Ctrl+G round trip). */ + claudeDraftKeysEnabled: boolean; uiScale: number; canvasColor: CanvasColorId; canvasBackground: CanvasBackgroundId; @@ -670,7 +725,10 @@ export interface SessionMetadata { revision: number; provider: ProviderId; /** Bindings actually consumed by this separately launched Codex editor. */ - nativeEditor?: { submit: string; submitAlternate: string; submitSuper: string; newline: string; selectAll: string }; + nativeEditor?: { submit: string; newline: string; selectAll: string } + & ({ newlineAlternate: string; copy: string; cut: string; clear: string } | { submitAlternate: string; submitSuper: string }); + /** macOS Claude launched with CanvasTTY's draft helper: Command+A selects the whole draft. */ + claudeDraft?: boolean; /** Provider conversation id, when the session is attached to one. */ threadId?: string; profile: LaunchProfileId; @@ -2060,6 +2118,11 @@ export interface CanvasTTYApi { /** `resume` continues the card's own conversation instead of starting a new one. */ restart(id: string, options?: { resume?: boolean }): Promise; input(id: string, data: string): void; + /** + * Copies, cuts or clears a macOS Claude card's whole draft, then types followUp, or pastes the clipboard as it is + * then (bracketed when Claude turned bracketed paste on); false when nothing ran. + */ + draftAction(id: string, action: ClaudeDraftAction, followUp?: string, paste?: "plain" | "bracketed"): Promise; resize(id: string, cols: number, rows: number): void; setBounds(id: string, bounds: SessionBounds): void; rename(id: string, title: string): Promise; @@ -2256,6 +2319,7 @@ export const IPC = { agentChatHistoryResume: "agent-chat-history:resume", terminalRestart: "terminal:restart", terminalInput: "terminal:input", + terminalDraftAction: "terminal:draft-action", terminalResize: "terminal:resize", terminalBounds: "terminal:bounds", terminalRename: "terminal:rename", diff --git a/tests/agent-control-capabilities.test.mjs b/tests/agent-control-capabilities.test.mjs index 265a32563..4d3762dac 100644 --- a/tests/agent-control-capabilities.test.mjs +++ b/tests/agent-control-capabilities.test.mjs @@ -11,7 +11,7 @@ import { isLaunchRole, launchRole } from "../src/main/services/agent-control/controlCapabilities.ts"; -import { TerminalManager, terminalEnvironment } from "../src/main/services/TerminalManager.ts"; +import { TerminalManager, setTerminalSystemLocale, terminalEnvironment } from "../src/main/services/TerminalManager.ts"; import { availableRegistry, fakeSpawner } from "./helpers/terminal.mjs"; const CONNECTION = { connectionPath: "/data/agent-control/connection.json", cliPath: "/app/scripts/canvastty-control.mjs" }; @@ -64,12 +64,41 @@ test("terminalEnvironment strips an inherited control grant like the other reser PATH: "/usr/bin", CANVASTTY_CONTROL_CONNECTION: "/leaked/connection.json", CANVASTTY_CONTROL_CLI: "/leaked/cli.mjs", - CANVASTTY_RUNTIME_CAPTURE_RESULT: "1" + CANVASTTY_RUNTIME_CAPTURE_RESULT: "1", + CANVASTTY_DRAFT_DIR: "/leaked/claude-draft/card", + CANVASTTY_DRAFT_EDITOR: "vi", + VISUAL: "/bin/sh /opt/app/agent-runtime/draft-editor.sh" }); assert.equal(environment.PATH, "/usr/bin"); assert.equal("CANVASTTY_CONTROL_CONNECTION" in environment, false); assert.equal("CANVASTTY_CONTROL_CLI" in environment, false); assert.equal("CANVASTTY_RUNTIME_CAPTURE_RESULT" in environment, false); + for (const name of ["CANVASTTY_DRAFT_DIR", "CANVASTTY_DRAFT_EDITOR", "VISUAL"]) assert.equal(name in environment, false, name); + assert.equal(terminalEnvironment({ VISUAL: "code --wait" }).VISUAL, "code --wait", "a person's own editor is kept"); +}); + +test("terminalEnvironment gives a localeless macOS launch the system's UTF-8 locale and keeps any explicit one", () => { + const installed = new Set(["/usr/share/locale/ru_RU.UTF-8", "/usr/share/locale/en_US.UTF-8"]); + const exists = (path) => installed.has(path); + for (const [system, expected] of [ + ["ru-RU", "ru_RU.UTF-8"], ["ru_RU", "ru_RU.UTF-8"], ["en-RU", "en_US.UTF-8"], ["en", "en_US.UTF-8"], ["", "en_US.UTF-8"] + ]) { + setTerminalSystemLocale(system, exists); + const environment = terminalEnvironment({ PATH: "/usr/bin" }, "darwin"); + assert.equal(environment.LANG, expected, system); + assert.equal("LC_CTYPE" in environment, false, "a full locale name, which ssh can pass to a server"); + } + setTerminalSystemLocale("en-US", exists); + for (const locale of [{ LANG: "C" }, { LC_ALL: "en_US.UTF-8" }, { LC_CTYPE: "ru_RU.KOI8-R" }]) { + const environment = terminalEnvironment({ PATH: "/usr/bin", ...locale }, "darwin"); + assert.deepEqual( + ["LANG", "LC_ALL", "LC_CTYPE"].filter((name) => name in environment), + Object.keys(locale) + ); + } + for (const platform of ["linux", "win32"]) { + assert.equal("LANG" in terminalEnvironment({ PATH: "/usr/bin" }, platform), false); + } }); test("TerminalManager hands the descriptor to orchestrator sessions only, and records the role", async () => { diff --git a/tests/agent-isolation.test.mjs b/tests/agent-isolation.test.mjs index 89b2266aa..de2eb9a91 100644 --- a/tests/agent-isolation.test.mjs +++ b/tests/agent-isolation.test.mjs @@ -51,9 +51,9 @@ function isolation(w, options = {}) { } /** Runs `sh -c script` under the generated profile; returns stdout lines. */ -function run(w, script, { provider = "codex", env = {}, granted } = {}) { +function run(w, script, { provider = "codex", env = {}, granted, ownWritable } = {}) { const wrapped = isolation(w).wrap({ sessionId: "s1", provider, cwd: w.project.normalize("NFC"), command: "/bin/sh", args: ["-c", script], - env: { ...w.env, ...env }, ...(granted ? { grantedPrivate: granted } : {}) }); + env: { ...w.env, ...env }, ...(granted ? { grantedPrivate: granted } : {}), ...(ownWritable ? { ownWritable } : {}) }); try { const result = spawnSync(wrapped.command, wrapped.args, { cwd: w.project, env: wrapped.env, encoding: "utf8", timeout: 20_000 }); return { lines: result.stdout.split("\n").filter(Boolean), stderr: result.stderr, env: wrapped.env }; @@ -66,16 +66,18 @@ test("the isolation decision: delegated and non-manual launches, the person's se const on = new AgentIsolation({ userDataPath: "/u", enabled: () => true, platform: "darwin", exists: () => true }); assert.deepEqual(on.decide({ provider: "codex", profile: "normal", delegated: false }), { apply: false, profile: "normal" }, "manual: the person answers"); assert.deepEqual(on.decide({ provider: "terminal", profile: "normal", delegated: true }), { apply: false, profile: "normal" }); + // The person's own agent runs as their terminal would run it, in every profile; only a contained auto needs the layer. for (const profile of ["auto", "acceptEdits", "plan", "yolo"]) { - assert.deepEqual(on.decide({ provider: "claude", profile, delegated: false }), { apply: true, profile, isolation: { state: "on", layer: "seatbelt" } }, profile); + assert.deepEqual(on.decide({ provider: "claude", profile, delegated: false }), { apply: false, profile }, profile); } + assert.deepEqual(on.decide({ provider: "qwen", profile: "auto", delegated: false }), { apply: true, profile: "auto", isolation: { state: "on", layer: "seatbelt" } }, "contained auto"); assert.equal(on.decide({ provider: "codex", profile: "normal", delegated: true }).apply, true, "a subagent always"); assert.deepEqual(on.decide({ provider: "codex", profile: "auto", delegated: true, environment: { isolated: true, label: "Container" } }), { apply: false, profile: "auto", isolation: { state: "environment", reason: "Runs in Container; the isolation layer of this computer does not apply there." } }); assert.equal(on.decide({ provider: "codex", profile: "auto", delegated: true, environment: { isolated: false, label: "Worktree" } }).apply, true); const off = new AgentIsolation({ userDataPath: "/u", enabled: () => false, platform: "darwin", exists: () => true }); - assert.deepEqual(off.decide({ provider: "claude", profile: "auto", delegated: false }), + assert.deepEqual(off.decide({ provider: "claude", profile: "auto", delegated: true }), { apply: false, profile: "auto", isolation: { state: "off", reason: "agent isolation is off in Settings → Agents." } }); assert.match(off.decide({ provider: "qwen", profile: "auto", delegated: false }).refuse, /qwen has no auto mode of its own; its auto runs only inside/u); // Off is the person's opt-in: a subagent keeps its profile (a contained auto, a bypass, still becomes normal). @@ -105,7 +107,7 @@ test("bubblewrap that cannot create a user namespace (Ubuntu's AppArmor restrict assert.match(sub.isolation.reason, /bubblewrap \(bwrap\) is installed but cannot create its sandbox here \(bwrap: setting up uid map: Permission denied\)/u); assert.match(sub.isolation.reason, /AppArmor\. docs\/installing-and-security\.md#linux-when-bubblewrap-cannot-start says how to allow it\. It runs in normal \(it asks\) instead of auto\./u); const own = linux.decide({ provider: "claude", profile: "acceptEdits", delegated: false }); - assert.deepEqual([own.apply, own.profile, own.isolation.state], [false, "acceptEdits", "unavailable"], "the person's own launch is not refused either"); + assert.deepEqual(own, { apply: false, profile: "acceptEdits" }, "the person's own launch does not need the layer"); assert.equal(linux.containment(), false); assert.throws(() => linux.wrap({ sessionId: "s", provider: "codex", cwd: "/p", command: "codex", args: [], env: {} }), /not available: bubblewrap \(bwrap\) is installed but/u); assert.deepEqual(calls, ["/usr/bin/bwrap"], "checked once while the answer is fresh"); @@ -180,6 +182,18 @@ test("bubblewrap: read-only root, writable project, tmpfs over what may not be r assert.deepEqual(args.slice(-5), ["--chdir", w.project, "--", "/usr/bin/claude", "--x"]); }); +test("the paths: Claude Code may write its fixed scratch folder /tmp/claude-, other CLIs may not", { skip: process.platform === "win32" ? "POSIX /tmp only" : false }, async (t) => { + const w = await world(t); + const input = { cwd: w.project, sessionTemp: join(w.temp, "s"), env: w.env, userDataPath: w.userData, sessionId: "s", uid: 4242 }; + const claude = isolationPaths({ ...input, provider: "claude" }); + assert.ok(claude.writable.includes("/tmp/claude-4242")); + if (process.platform === "darwin") assert.ok(claude.writable.includes("/private/tmp/claude-4242"), "both spellings"); + const codex = isolationPaths({ ...input, provider: "codex" }); + assert.ok(!codex.writable.some((path) => path.endsWith("/claude-4242"))); + const withoutUid = isolationPaths({ ...input, uid: undefined, provider: "claude" }); + assert.ok(!withoutUid.writable.some((path) => path.endsWith("/claude-4242"))); +}); + test("the paths: another CLI's home moved by its own variable is unreadable, never this CLI's own", async (t) => { const w = await world(t); const custom = (name) => join(w.base, "creds", name); @@ -283,20 +297,22 @@ test("the launch: wrapped when the layer applies, refused (never unwrapped) when return { command: "/usr/bin/sandbox-exec", args: ["-f", "/p.sb", launch.command, ...launch.args], env: { ...launch.env, TMPDIR: "/s/" }, cleanup: () => cleaned.push(launch.sessionId) }; } }); - const auto = terminals.create({ provider: "claude", profile: "auto", cwd: w.project, position: at }); - assert.equal(calls.at(-1).command, "/usr/bin/sandbox-exec"); - assert.deepEqual(calls.at(-1).args.slice(0, 3), ["-f", "/p.sb", "/resolved/claude"]); - assert.ok(!calls.at(-1).args.some((arg) => arg.includes("\"sandbox\"")), "no Claude sandbox inside the layer"); - assert.deepEqual(auto.isolation, { state: "on", layer: "seatbelt" }); + // The person's own agent runs as their terminal would run it, in auto as in manual. + const own = terminals.create({ provider: "claude", profile: "auto", cwd: w.project, position: at }); + assert.equal(calls.at(-1).command, "/resolved/claude", "an auto launch by the person is not wrapped"); + assert.equal(own.isolation, undefined); const manual = terminals.create({ provider: "claude", profile: "normal", cwd: w.project, position: at }); assert.equal(calls.at(-1).command, "/resolved/claude", "a manual launch by the person is not wrapped"); assert.equal(manual.isolation, undefined); // A contained auto (no auto of its own) exists only inside the layer. - terminals.create({ provider: "qwen", profile: "auto", cwd: w.project, position: at }); + const auto = terminals.create({ provider: "qwen", profile: "auto", cwd: w.project, position: at }); + assert.equal(calls.at(-1).command, "/usr/bin/sandbox-exec"); + assert.deepEqual(calls.at(-1).args.slice(0, 3), ["-f", "/p.sb", "/resolved/qwen"]); assert.ok(calls.at(-1).args.includes("--yolo")); + assert.deepEqual(auto.isolation, { state: "on", layer: "seatbelt" }); const count = calls.length; failing = true; - const refused = terminals.create({ provider: "codex", profile: "auto", cwd: w.project, position: at }); + const refused = terminals.create({ provider: "qwen", profile: "auto", cwd: w.project, position: at }); assert.equal(calls.length, count, "nothing started"); assert.equal(refused.status, "failed"); assert.match(refused.failureDetails, /^Launch refused: agent isolation could not be set up: disk full\. The agent was not started without it\./u); @@ -358,6 +374,14 @@ test("seatbelt, for real: writes stay in the project, secrets stay unread, nothi assert.notEqual(spawnSync("defaults", ["read", "ctty.isolation.probe"]).status, 0); }); +test("seatbelt, for real: Claude's Bash tool can create its session folder in /tmp/claude-; Codex cannot", onMac, async (t) => { + const w = await world(t); + const probe = `ctty-iso-probe-${process.pid}`; + const script = `d="/private/tmp/claude-$(id -u)/${probe}"; mkdir -p "$d" 2>/dev/null && echo x > "$d/f" && rm -rf "$d" && echo CLAUDE-TMP-ok || echo CLAUDE-TMP-denied`; + assert.deepEqual(run(w, script, { provider: "claude" }).lines, ["CLAUDE-TMP-ok"]); + assert.deepEqual(run(w, script, { provider: "codex" }).lines, ["CLAUDE-TMP-denied"]); +}); + test("seatbelt, for real: the launch writes the account home it was handed, not its permission settings, and no other home", onMac, async (t) => { const w = await world(t); const own = join(w.userData, "account-homes", "a1"); @@ -378,6 +402,45 @@ test("seatbelt, for real: the launch writes the account home it was handed, not assert.equal(await readFile(join(own, "auth.json"), "utf8"), "refreshed\n"); }); +test("the paths: a Claude card's own draft folder is writable and readable again; other cards' are hidden", async (t) => { + const w = await world(t); + const own = join(w.userData, "claude-draft", "s1"); + const paths = isolationPaths({ provider: "claude", cwd: w.project, sessionTemp: join(w.temp, "s"), env: w.env, + userDataPath: w.userData, sessionId: "s1", ownWritable: [own] }); + assert.ok(paths.writable.includes(own) && paths.readableAgain.includes(own)); + assert.ok(paths.unreadable.includes(join(w.userData, "claude-draft"))); + const without = isolationPaths({ provider: "claude", cwd: w.project, sessionTemp: join(w.temp, "s"), env: w.env, userDataPath: w.userData, sessionId: "s1" }); + assert.ok(!without.writable.includes(own) && !without.readableAgain.includes(own)); +}); + +test("seatbelt, for real: Claude's draft helper answers in its own card's folder and cannot reach another card's", onMac, async (t) => { + const w = await world(t); + const drafts = join(w.userData, "claude-draft"); + const own = join(drafts, "s1"); + const other = join(drafts, "s2"); + const helper = new URL("../src/agent-runtime/draft-editor.sh", import.meta.url).pathname; + await mkdir(own, { recursive: true }); + await mkdir(other, { recursive: true }); + const prompt = join(w.project, "claude-prompt-t.md"); + await writeFile(prompt, "черновик"); + await writeFile(join(own, "req.1"), "cut\n"); + await writeFile(join(other, "req.2"), "copy\n"); + await writeFile(join(other, "draft.3"), "другая карточка"); + const { lines } = run(w, [ + `/bin/sh "${helper}" "${prompt}" && echo own`, + // Another card's request is hidden: with none of its own, this Ctrl+G opens the person's editor. + `/bin/sh "${helper}" "${prompt}"`, + `: > "${other}/req.9" 2>/dev/null && echo other-write`, + `cat "${other}/draft.3" 2>/dev/null && echo other-read`, + `ls "${drafts}" 2>/dev/null && echo listed` + ].join("; "), { provider: "claude", ownWritable: [own], env: { CANVASTTY_DRAFT_DIR: own, CANVASTTY_DRAFT_EDITOR: "echo editor" } }); + assert.deepEqual(lines, ["own", `editor ${prompt}`]); + assert.deepEqual((await readdir(own)).sort(), ["done.1", "draft.1"]); + assert.equal(await readFile(join(own, "draft.1"), "utf8"), "черновик"); + assert.equal(await readFile(prompt, "utf8"), "", "cut empties Claude's prompt file"); + assert.deepEqual((await readdir(other)).sort(), ["draft.3", "req.2"]); +}); + test("seatbelt, for real: git init works, but no repository in the project gets a hook or attributes from the agent", onMac, async (t) => { const w = await world(t); const { lines, env } = run(w, [ diff --git a/tests/auto-profile.test.mjs b/tests/auto-profile.test.mjs index 218f57de6..2595b9b70 100644 --- a/tests/auto-profile.test.mjs +++ b/tests/auto-profile.test.mjs @@ -103,7 +103,7 @@ test("auto exists only where the CLI has a native auto mode (OpenCode: a per-run assert.deepEqual(launch("codex", "yolo"), ["--dangerously-bypass-approvals-and-sandbox"]); }); -test("auto: Codex --approve-for-me (its workspace-write sandbox), Claude auto with its sandbox merged into the one --settings", () => { +test("auto: Codex --approve-for-me (its workspace-write sandbox), Claude auto keeps one --settings and its own sandbox choice", () => { assert.deepEqual(launch("codex", "auto"), ["--approve-for-me"]); assert.deepEqual(launch("grok", "auto"), ["--permission-mode", "auto"]); const hooks = JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: "command", command: "/hook" }] }] } }); @@ -112,12 +112,12 @@ test("auto: Codex --approve-for-me (its workspace-write sandbox), Claude auto wi assert.deepEqual(args.slice(0, 2), ["--permission-mode", "auto"]); assert.equal(args.filter((arg) => arg === "--settings").length, 1, "Claude keeps only the last --settings"); const [settings] = settingsOf(args); - assert.deepEqual(settings.sandbox, { enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: false }); + assert.equal(settings.sandbox, undefined, "Claude's sandbox follows the person's own Claude settings"); assert.equal(settings.hooks.Stop[0].hooks[0].command, "/hook", "CanvasTTY's hooks survive"); assert.equal(settings.env.ANTHROPIC_BASE_URL, "http://127.0.0.1:11434"); - // Without other settings the sandbox is its own inline --settings. - assert.deepEqual(settingsOf(launch("claude", "auto")), [{ sandbox: { enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: false } }]); - assert.deepEqual(settingsOf(launch("claude", "auto", [], { platform: "darwin" })), settingsOf(launch("claude", "auto")), "macOS: the same sandbox"); + // Without other settings there is no inline --settings at all, on macOS as on Linux. + assert.deepEqual(launch("claude", "auto"), ["--permission-mode", "auto"]); + assert.deepEqual(launch("claude", "auto", [], { platform: "darwin" }), ["--permission-mode", "auto"]); // Claude Code has no sandbox on Windows: auto there is its auto mode alone. assert.deepEqual(launch("claude", "auto", [], { platform: "win32" }), ["--permission-mode", "auto"]); // Inside CanvasTTY's isolation layer Claude's own sandbox cannot start (macOS refuses a sandbox in a sandbox): left out. @@ -133,11 +133,11 @@ test("auto: Codex --approve-for-me (its workspace-write sandbox), Claude auto wi assert.deepEqual(launch("codex", "auto"), ["--approve-for-me"], "outside the layer Codex keeps its own sandbox"); }); -test("a third-party model turns auto into accept-edits, sandbox kept; other profiles ignore the mark", () => { +test("a third-party model turns auto into accept-edits; other profiles ignore the mark", () => { assert.deepEqual(launch("codex", "auto", [], { thirdPartyModel: true }), ["--sandbox", "workspace-write", "--ask-for-approval", "on-request"]); const claude = launch("claude", "auto", [], { thirdPartyModel: true }); assert.deepEqual(claude.slice(0, 2), ["--permission-mode", "acceptEdits"]); - assert.equal(settingsOf(claude)[0].sandbox.enabled, true); + assert.deepEqual(settingsOf(claude), [], "no sandbox switched on for the person"); assert.deepEqual(launch("grok", "auto", [], { thirdPartyModel: true }), ["--permission-mode", "acceptEdits"]); assert.deepEqual(launch("codex", "normal", [], { thirdPartyModel: true }), []); }); diff --git a/tests/canvas-navigation-override.test.mjs b/tests/canvas-navigation-override.test.mjs index d2985208a..cbd9b95f9 100644 --- a/tests/canvas-navigation-override.test.mjs +++ b/tests/canvas-navigation-override.test.mjs @@ -232,7 +232,7 @@ test("modifier-only Meta full override does not swallow ordinary Command shortcu assert.equal(prevented, false); }); -test("macOS Select All, Copy and Paste reach a focused terminal without capturing other Command shortcuts", () => { +test("macOS Select All, Copy, Cut and Paste reach a focused terminal without capturing other Command shortcuts", () => { const contents = new EventEmitter(); const ignored = []; contents.isDestroyed = () => false; @@ -252,13 +252,15 @@ test("macOS Select All, Copy and Paste reach a focused terminal without capturin contents.emit("before-input-event", event, input("keyUp", "v", { code: "KeyV", meta: true })); contents.emit("before-input-event", event, input("keyDown", "ф", { code: "KeyA", meta: true })); contents.emit("before-input-event", event, input("keyUp", "ф", { code: "KeyA", meta: true })); + contents.emit("before-input-event", event, input("keyDown", "ч", { code: "KeyX", meta: true })); + contents.emit("before-input-event", event, input("keyUp", "ч", { code: "KeyX", meta: true })); contents.emit("before-input-event", event, input("keyDown", "q", { code: "KeyQ", meta: true })); assert.equal(prevented, false); - assert.deepEqual(ignored, [true, false, true, false, true, false]); + assert.deepEqual(ignored, [true, false, true, false, true, false, true, false]); }); -test("modified Command+A and non-macOS menu input keep their existing dispatch", () => { +test("modified Command+A/X and non-macOS menu input keep their existing dispatch", () => { for (const captureMacEditShortcuts of [true, false]) { const contents = new EventEmitter(); const ignored = []; @@ -266,6 +268,7 @@ test("modified Command+A and non-macOS menu input keep their existing dispatch", contents.setIgnoreMenuShortcuts = (active) => ignored.push(active); const controller = new CanvasNavigationInputController({ wheelBinding: null, navigationBinding: null }, () => undefined); controller.attach(contents, { captureMacEditShortcuts }); + controller.setTerminalEditFocus(contents, true); const event = { preventDefault: () => assert.fail("editing input must reach its focused native field") }; const chords = [ { meta: false, control: true }, { meta: true, control: true }, @@ -273,8 +276,10 @@ test("modified Command+A and non-macOS menu input keep their existing dispatch", ]; if (!captureMacEditShortcuts) chords.push({ meta: true }); for (const modifiers of chords) { - contents.emit("before-input-event", event, input("keyDown", "a", { code: "KeyA", ...modifiers })); - contents.emit("before-input-event", event, input("keyUp", "a", { code: "KeyA", ...modifiers })); + for (const key of ["a", "x"]) { + contents.emit("before-input-event", event, input("keyDown", key, { code: `Key${key.toUpperCase()}`, ...modifiers })); + contents.emit("before-input-event", event, input("keyUp", key, { code: `Key${key.toUpperCase()}`, ...modifiers })); + } } assert.deepEqual(ignored, []); } @@ -434,7 +439,7 @@ test("changing a binding resets pressed state instead of activating it retroacti assert.equal(tracker.active, false); }); -test("macOS Command+C/V/A keep the Edit menu in ordinary fields and plugin pages; only a focused terminal captures them", () => { +test("macOS Command+C/V/A/X keep the Edit menu in ordinary fields and plugin pages; only a focused terminal captures them", () => { const top = { name: "top" }; const pluginFrame = { name: "plugin iframe" }; const contents = new EventEmitter(); @@ -446,36 +451,39 @@ test("macOS Command+C/V/A keep the Edit menu in ordinary fields and plugin pages const controller = new CanvasNavigationInputController({ wheelBinding: null, navigationBinding: null }, () => undefined); controller.attach(contents, { captureMacEditShortcuts: true }); const event = { preventDefault: () => assert.fail("editing keys are never cancelled") }; - const pressV = () => { - contents.emit("before-input-event", event, input("keyDown", "v", { code: "KeyV", meta: true })); - contents.emit("before-input-event", event, input("keyUp", "v", { code: "KeyV", meta: true })); + const pressEditKeys = () => { + for (const key of ["a", "c", "v", "x"]) { + contents.emit("before-input-event", event, input("keyDown", key, { code: `Key${key.toUpperCase()}`, meta: true })); + contents.emit("before-input-event", event, input("keyUp", key, { code: `Key${key.toUpperCase()}`, meta: true })); + } }; // An app field (no terminal focus reported): the menu's native Paste must run. - pressV(); - assert.deepEqual(ignored, [], "an ordinary field keeps Edit > Paste"); + pressEditKeys(); + assert.deepEqual(ignored, [], "an ordinary field keeps native editing"); // A plugin page's field: the iframe has focus, even if a terminal had focus before. controller.setTerminalEditFocus(contents, true); contents.focusedFrame = pluginFrame; - pressV(); - assert.deepEqual(ignored, [], "a plugin iframe keeps Edit > Paste"); + pressEditKeys(); + assert.deepEqual(ignored, [], "a plugin iframe keeps native editing"); // Back in the terminal: captured for xterm's own paste. contents.focusedFrame = top; - pressV(); - assert.deepEqual(ignored, [true, false]); + pressEditKeys(); + assert.deepEqual(ignored, [true, false, true, false, true, false, true, false]); + ignored.length = 0; // Focus leaves the terminal while the capture is held: it is released at once. contents.emit("before-input-event", event, input("keyDown", "c", { code: "KeyC", meta: true })); controller.setTerminalEditFocus(contents, false); - assert.deepEqual(ignored, [true, false, true, false]); - pressV(); - assert.deepEqual(ignored, [true, false, true, false]); + assert.deepEqual(ignored, [true, false]); + pressEditKeys(); + assert.deepEqual(ignored, [true, false]); }); -test("focused shortcut recorders receive Command+A/C/V while ordinary fields keep native editing", (t) => { +test("focused shortcut recorders receive Command+A/C/V/X while ordinary fields keep native editing", (t) => { const previousElement = globalThis.Element; class FakeElement { constructor(selector) { this.selector = selector; } @@ -507,7 +515,7 @@ test("focused shortcut recorders receive Command+A/C/V while ordinary fields kee const stop = trackTerminalEditFocus(doc, (focused) => controller.setTerminalEditFocus(contents, focused)); t.after(stop); const pressEditKeys = () => { - for (const key of ["a", "c", "v"]) { + for (const key of ["a", "c", "v", "x"]) { const event = { preventDefault: () => assert.fail("the renderer must receive recorder keyboard events") }; contents.emit("before-input-event", event, input("keyDown", key, { code: `Key${key.toUpperCase()}`, meta: true })); contents.emit("before-input-event", event, input("keyUp", key, { code: `Key${key.toUpperCase()}`, meta: true })); @@ -518,7 +526,7 @@ test("focused shortcut recorders receive Command+A/C/V while ordinary fields kee doc.activeElement = new FakeElement('[data-shortcut-capture="true"]'); listeners.get("focusin")(); pressEditKeys(); - assert.deepEqual(ignored, [true, false, true, false, true, false], "all three chords bypass the menu for the recorder"); + assert.deepEqual(ignored, [true, false, true, false, true, false, true, false], "all four chords bypass the menu for the recorder"); ignored.length = 0; contents.focusedFrame = {}; pressEditKeys(); diff --git a/tests/claude-draft-editor.test.mjs b/tests/claude-draft-editor.test.mjs new file mode 100644 index 000000000..a135c10dd --- /dev/null +++ b/tests/claude-draft-editor.test.mjs @@ -0,0 +1,438 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { ClaudeDraftEditor, isClaudeDraftAction } from "../src/main/services/ClaudeDraftEditor.ts"; +import { TerminalManager } from "../src/main/services/TerminalManager.ts"; +import { availableRegistry, fakeSpawner } from "./helpers/terminal.mjs"; + +const helperPath = new URL("../src/agent-runtime/draft-editor.sh", import.meta.url).pathname; +// The helper is a POSIX shell script for macOS Claude cards; Windows has no /bin/sh to run it. +const POSIX = { skip: process.platform === "win32" ? "the draft helper is a POSIX shell script" : false }; + +// Stands in for Claude Code: Ctrl+G hands the draft to $VISUAL and reloads what it leaves. +function fakeClaude(environment, draft) { + const state = { draft, writes: [], editorRuns: 0 }; + const scratch = mkdtempSync(join(tmpdir(), "claude-draft-test-")); + state.write = (data) => { + state.writes.push(data); + if (data !== "\u0007") return true; + state.editorRuns += 1; + const file = join(scratch, "claude-prompt-test.md"); + writeFileSync(file, state.draft); + execFileSync("/bin/sh", ["-c", `${environment.VISUAL} "$1"`, "claude", file], { + env: { PATH: process.env.PATH, ...environment, CANVASTTY_DRAFT_EDITOR: "true" } + }); + state.draft = readFileSync(file, "utf8"); + return true; + }; + state.cleanup = () => rmSync(scratch, { recursive: true, force: true }); + return state; +} + +// What the helper would do for the oldest waiting request: claim it, save the draft, report done. +function finishRequest(directory, draft = "") { + const id = readdirSync(directory).filter((name) => name.startsWith("req.")).map((name) => Number(name.slice(4))).sort((a, b) => a - b)[0]; + rmSync(join(directory, `req.${id}`)); + writeFileSync(join(directory, `draft.${id}`), draft); + writeFileSync(join(directory, `done.${id}`), ""); +} + +const files = (directory) => (existsSync(directory) ? readdirSync(directory).sort() : []); + +function editorFixture(timeoutMs) { + const root = mkdtempSync(join(tmpdir(), "claude-draft-root-")); + const clipboard = []; + const source = { image: false, text: "" }; + const editor = new ClaudeDraftEditor({ + root, helperPath, writeClipboard: (text) => clipboard.push(text), readClipboard: () => ({ ...source }), timeoutMs + }); + return { root, clipboard, source, editor }; +} + +/** Runs the helper as Claude's $VISUAL on `file`; returns its exit status. */ +function runHelper(file, directory, ownEditor = "false") { + try { + execFileSync("/bin/sh", [helperPath, file], { env: { PATH: process.env.PATH, CANVASTTY_DRAFT_DIR: directory, CANVASTTY_DRAFT_EDITOR: ownEditor } }); + return 0; + } catch (error) { + return error.status; + } +} + +test("copy, cut and clear act on the whole Claude draft through the real helper", POSIX, async () => { + const { root, clipboard, editor } = editorFixture(); + const environment = editor.environment("card-1", { VISUAL: "code --wait" }); + assert.deepEqual(environment, { + VISUAL: `/bin/sh ${helperPath}`, + CANVASTTY_DRAFT_DIR: join(root, "card-1"), + CANVASTTY_DRAFT_EDITOR: "code --wait" + }); + const draft = "Привет 👋\nвторая строка\n[вставка из 40 строк]"; + const claude = fakeClaude(environment, draft); + try { + assert.equal(await editor.run("card-1", "copy", "", claude.write), true); + assert.equal(claude.draft, draft, "copying leaves the draft alone"); + assert.equal(await editor.run("card-1", "cut", "", claude.write), true); + assert.equal(claude.draft, ""); + assert.deepEqual(clipboard, [draft, draft]); + claude.draft = "старое"; + assert.equal(await editor.run("card-1", "clear", "ж", claude.write), true); + assert.equal(claude.draft, ""); + assert.deepEqual(claude.writes.slice(-2), ["\u0007", "ж"], "the replacing key follows the round trip"); + assert.equal(clipboard.length, 2, "clearing never touches the clipboard"); + assert.deepEqual(files(join(root, "card-1")), [], "no request or draft copy outlives its action"); + } finally { + claude.cleanup(); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a session's actions run one after another, and input typed meanwhile keeps its place", async () => { + const { root, clipboard, editor } = editorFixture(); + editor.environment("card-2", {}); + const directory = join(root, "card-2"); + const writes = []; + const write = (data) => { writes.push(data); return true; }; + const tick = () => new Promise((resolve) => setTimeout(resolve, 30)); + const copying = editor.run("card-2", "copy", "", write); + assert.equal(editor.hold("card-2", "b"), true); + const clearing = editor.run("card-2", "clear", "ж", write); + assert.equal(editor.hold("card-2", "c"), true); + assert.equal(editor.hold("other-card", "x"), false, "other cards are never held"); + await tick(); + assert.deepEqual(writes, ["\u0007"], "the second action waits for the first"); + finishRequest(directory, "весь черновик"); + assert.equal(await copying, true); + await tick(); + assert.deepEqual(writes, ["\u0007", "b", "\u0007"]); + finishRequest(directory); + assert.equal(await clearing, true); + await tick(); + assert.deepEqual(writes, ["\u0007", "b", "\u0007", "ж", "c"]); + assert.deepEqual(clipboard, ["весь черновик"]); + assert.equal(editor.hold("card-2", "d"), false); + rmSync(root, { recursive: true, force: true }); +}); + +test("a Ctrl+G Claude picks up late opens no editor and changes nothing, even after a newer action", POSIX, async () => { + const { root, clipboard, editor } = editorFixture(60); + const environment = editor.environment("card-3", {}); + const claude = fakeClaude(environment, "черновик"); + const late = []; + const writes = []; + const delayed = (data) => { writes.push(data); if (data === "\u0007") late.push(() => claude.write(data)); return true; }; + try { + assert.equal(await editor.run("card-3", "cut", "ж", delayed), false, "the deadline passes"); + assert.deepEqual(writes, ["\u0007", "ж"], "what was typed still arrives"); + assert.deepEqual(files(join(root, "card-3")), ["cancel.1"]); + late.shift()(); + assert.equal(claude.draft, "черновик", "the late Ctrl+G is a no-op, not the person's editor"); + assert.deepEqual(files(join(root, "card-3")), []); + assert.deepEqual(clipboard, []); + + assert.equal(await editor.run("card-3", "copy", "", delayed), false); + const running = editor.run("card-3", "clear", "", claude.write); + assert.equal(await running, true, "the newer action is done by its own Ctrl+G"); + late.shift()(); + assert.equal(claude.draft, ""); + assert.deepEqual(clipboard, []); + assert.deepEqual(files(join(root, "card-3")), []); + } finally { + claude.cleanup(); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a Ctrl+G Claude never handles costs one later Ctrl+G, never the following actions", POSIX, async () => { + const { root, clipboard, editor } = editorFixture(40); + const environment = editor.environment("card-4", {}); + const claude = fakeClaude(environment, "черновик"); + try { + // A dialog swallowed this Ctrl+G: it will never reach the helper. + assert.equal(await editor.run("card-4", "cut", "", () => true), false); + for (let i = 0; i < 3; i += 1) assert.equal(await editor.run("card-4", "copy", "", claude.write), true); + assert.deepEqual(clipboard, ["черновик", "черновик", "черновик"]); + assert.deepEqual(files(join(root, "card-4")), ["cancel.1"]); + claude.write("\u0007"); + assert.deepEqual(files(join(root, "card-4")), [], "the next manual Ctrl+G uses it up"); + assert.equal(claude.draft, "черновик"); + editor.environment("card-4", {}); + assert.equal(existsSync(join(root, "card-4")), false, "a new Claude launch starts clean"); + assert.equal(await editor.run("card-4", "cut", "", () => false), false, "an unsent Ctrl+G is not queued"); + assert.deepEqual(files(join(root, "card-4")), []); + } finally { + claude.cleanup(); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a request is either claimed by the helper or cancelled, never both", async () => { + const { root, clipboard, editor } = editorFixture(40); + editor.environment("card-5", {}); + const directory = join(root, "card-5"); + let claim; + const write = () => { + // The helper claims the request just before the deadline and finishes just after it. + claim = setTimeout(() => { + rmSync(join(directory, "req.1")); + setTimeout(() => { + writeFileSync(join(directory, "draft.1"), "вырезано"); + writeFileSync(join(directory, "done.1"), ""); + }, 40); + }, 30); + return true; + }; + assert.equal(await editor.run("card-5", "cut", "", write), true, "a claimed request is waited for, not cancelled"); + clearTimeout(claim); + assert.deepEqual(clipboard, ["вырезано"], "cut text reaches the clipboard"); + assert.deepEqual(files(directory), []); + rmSync(root, { recursive: true, force: true }); +}); + +test("the helper leaves the draft alone when it cannot save a copy, and ignores unknown requests", POSIX, () => { + const scratch = mkdtempSync(join(tmpdir(), "claude-draft-helper-")); + const directory = join(scratch, "card"); + mkdirSync(directory); + const file = join(scratch, "claude-prompt-test.md"); + writeFileSync(file, "draft"); + const run = () => runHelper(file, directory); + writeFileSync(join(directory, "req.1"), "rm\n"); + assert.equal(run(), 0); + assert.equal(readFileSync(file, "utf8"), "draft"); + writeFileSync(join(directory, "req.2"), "cut\n"); + chmodSync(file, 0o200); + assert.notEqual(run(), 0); + chmodSync(file, 0o600); + assert.equal(readFileSync(file, "utf8"), "draft", "no copy, no cut"); + assert.equal(existsSync(join(directory, "done.2")), false); + rmSync(scratch, { recursive: true, force: true }); +}); + +test("only Claude's own prompt file is acted on: a program Claude runs gets the person's editor", POSIX, () => { + const scratch = mkdtempSync(join(tmpdir(), "claude-draft-other-file-")); + const directory = join(scratch, "card"); + mkdirSync(directory); + const commitMessage = join(scratch, "COMMIT_EDITMSG"); + writeFileSync(commitMessage, "fix: keep me"); + writeFileSync(join(directory, "req.1"), "cut\n"); + writeFileSync(join(directory, "cancel.2"), ""); + const ownEditor = join(scratch, "own-editor.sh"); + writeFileSync(ownEditor, 'printf "%s" "$1" > "$(dirname "$0")/opened"\n'); + assert.equal(runHelper(commitMessage, directory, `/bin/sh ${ownEditor}`), 0); + assert.equal(readFileSync(join(scratch, "opened"), "utf8"), commitMessage, "git's editor is the person's"); + assert.equal(readFileSync(commitMessage, "utf8"), "fix: keep me"); + assert.deepEqual(files(directory), ["cancel.2", "req.1"], "the card's request and cancel stay for Claude's Ctrl+G"); + rmSync(scratch, { recursive: true, force: true }); +}); + +test("a background session shown by another card answers that card's request; its own come first", POSIX, () => { + const scratch = mkdtempSync(join(tmpdir(), "claude-draft-cards-")); + const started = join(scratch, "card-a"); + const showing = join(scratch, "card-b"); + mkdirSync(started); + mkdirSync(showing); + const file = join(scratch, "claude-prompt-test.md"); + writeFileSync(file, "черновик"); + // card-b sent the Ctrl+G; the session's helper names card-a's folder, where it was started. + writeFileSync(join(showing, "req.7"), "copy\n"); + assert.equal(runHelper(file, started), 0); + assert.deepEqual(files(showing), ["done.7", "draft.7"]); + assert.equal(readFileSync(join(showing, "draft.7"), "utf8"), "черновик"); + rmSync(join(showing, "done.7")); + rmSync(join(showing, "draft.7")); + writeFileSync(join(showing, "req.3"), "cut\n"); + writeFileSync(join(started, "req.9"), "copy\n"); + assert.equal(runHelper(file, started), 0); + assert.deepEqual(files(started), ["done.9", "draft.9"], "its own card's request first"); + assert.deepEqual(files(showing), ["req.3"]); + assert.equal(readFileSync(file, "utf8"), "черновик"); + rmSync(join(showing, "req.3")); + writeFileSync(join(showing, "cancel.4"), ""); + assert.equal(runHelper(file, started), 1, "another card's cancel does not cost this Ctrl+G: the editor opens"); + assert.deepEqual(files(showing), ["cancel.4"]); + rmSync(scratch, { recursive: true, force: true }); +}); + +test("a cancel the helper cannot remove is not used up: that Ctrl+G opens the editor", { skip: POSIX.skip || (process.getuid?.() === 0 && "root ignores permissions") }, () => { + const scratch = mkdtempSync(join(tmpdir(), "claude-draft-locked-")); + const directory = join(scratch, "card"); + mkdirSync(directory); + const file = join(scratch, "claude-prompt-test.md"); + writeFileSync(file, "draft"); + writeFileSync(join(directory, "cancel.1"), ""); + chmodSync(directory, 0o500); + try { + const ownEditor = join(scratch, "own-editor.sh"); + writeFileSync(ownEditor, ': > "$(dirname "$0")/opened"\n'); + assert.equal(runHelper(file, directory, `/bin/sh ${ownEditor}`), 0); + assert.equal(existsSync(join(scratch, "opened")), true); + assert.deepEqual(files(directory), ["cancel.1"]); + } finally { + chmodSync(directory, 0o700); + rmSync(scratch, { recursive: true, force: true }); + } +}); + +test("a paste that replaces the draft reads the clipboard in its turn, so later keys stay after it", async () => { + const { root, source, editor } = editorFixture(); + editor.environment("card-p", {}); + const directory = join(root, "card-p"); + const writes = []; + const write = (data) => { writes.push(data); return true; }; + const tick = () => new Promise((resolve) => setTimeout(resolve, 30)); + source.text = "старый буфер"; + const pasting = editor.run("card-p", "clear", "", write, "bracketed"); + assert.equal(editor.hold("card-p", "x"), true); + await tick(); + source.text = "строка 1\nстрока 2"; + finishRequest(directory); + assert.equal(await pasting, true); + await tick(); + assert.deepEqual(writes, ["\u0007", "\u001b[200~строка 1\rстрока 2\u001b[201~", "x"]); + source.image = true; + const image = editor.run("card-p", "clear", "", write, "plain"); + await tick(); + finishRequest(directory); + await image; + assert.equal(writes.at(-1), "\u0016", "an image is left for Claude to read itself"); + source.image = false; + source.text = "a\r\nb"; + const plain = editor.run("card-p", "clear", "", write, "plain"); + await tick(); + finishRequest(directory); + await plain; + assert.equal(writes.at(-1), "a\rb"); + rmSync(root, { recursive: true, force: true }); +}); + +test("leftovers of an earlier CanvasTTY run are removed before any card launches", () => { + const { root, editor } = editorFixture(); + mkdirSync(join(root, "old-card")); + writeFileSync(join(root, "old-card", "cancel.4"), ""); + editor.removeLeftovers(); + assert.equal(existsSync(root), false); + assert.equal(editor.environment("card", {}).CANVASTTY_DRAFT_DIR, join(root, "card")); +}); + +test("without a request the helper opens the person's own editor, arguments included", POSIX, () => { + const scratch = mkdtempSync(join(tmpdir(), "claude-draft-own-")); + const file = join(scratch, "claude-prompt-test.md"); + writeFileSync(file, "draft"); + const ownEditor = join(scratch, "own-editor.sh"); + writeFileSync(ownEditor, 'printf "%s|" "$@" > "$(dirname "$0")/opened"\n'); + execFileSync("/bin/sh", [helperPath, file], { + env: { PATH: process.env.PATH, CANVASTTY_DRAFT_DIR: join(scratch, "none"), CANVASTTY_DRAFT_EDITOR: `/bin/sh ${ownEditor} --wait` } + }); + assert.equal(readFileSync(join(scratch, "opened"), "utf8"), `--wait|${file}|`); + assert.equal(readFileSync(file, "utf8"), "draft"); + rmSync(scratch, { recursive: true, force: true }); +}); + +test("the helper is only offered when it can be named safely, and actions are validated", async () => { + const root = mkdtempSync(join(tmpdir(), "claude-draft-names-")); + for (const unsafe of ["/Applications/My App/draft-editor.sh", "/opt/a$b/draft-editor.sh", "/x/'q'/draft-editor.sh"]) { + const editor = new ClaudeDraftEditor({ root, helperPath: unsafe, writeClipboard() {} }); + assert.deepEqual(editor.environment("card", {}), {}, unsafe); + assert.equal(editor.isGranted("card"), false); + assert.equal(await editor.run("card", "clear", "", () => assert.fail("no Ctrl+G without the helper")), false); + } + const cyrillic = new ClaudeDraftEditor({ root, helperPath: "/opt/Программы/draft-editor.sh", writeClipboard() {} }); + assert.equal(cyrillic.environment("card", {}).VISUAL, "/bin/sh /opt/Программы/draft-editor.sh"); + const safe = new ClaudeDraftEditor({ root, helperPath, writeClipboard() {} }); + assert.deepEqual(safe.environment("../escape", {}), {}); + assert.equal(safe.environment("card", { EDITOR: "nano" }).CANVASTTY_DRAFT_EDITOR, "nano"); + assert.equal(safe.isGranted("card"), true); + safe.forget("card"); + assert.equal(safe.isGranted("card"), false); + assert.equal(isClaudeDraftAction("cut"), true); + assert.equal(isClaudeDraftAction("rm"), false); + rmSync(root, { recursive: true, force: true }); +}); + +test("TerminalManager gives local macOS Claude cards the helper and holds their input during an action", { + skip: process.platform !== "darwin" && "the draft helper is macOS-only" +}, async () => { + const { root, clipboard, editor } = editorFixture(); + const calls = []; + const writes = []; + const terminals = new TerminalManager(() => undefined, availableRegistry(), undefined, undefined, true, + fakeSpawner(calls, { onWrite: (data, options) => { + writes.push(data); + if (data === "\u0007") finishRequest(options.env.CANVASTTY_DRAFT_DIR, "весь черновик"); + } })); + terminals.configureDraftEditor(editor); + try { + const base = { profile: "yolo", cwd: process.cwd(), position: { x: 0, y: 0 } }; + const claude = terminals.create({ ...base, provider: "claude" }); + const claudeEnv = calls.at(-1).options.env; + assert.equal(claudeEnv.VISUAL, `/bin/sh ${helperPath}`); + assert.equal(claudeEnv.CANVASTTY_DRAFT_DIR, join(root, claude.id)); + assert.equal(terminals.listMetadata().find((s) => s.id === claude.id).claudeDraft, true); + // A background session (/bg, /resume) gets Claude's --settings, not this environment. + const args = calls.at(-1).args; + const inline = args.filter((_, index) => args[index - 1] === "--settings").map((value) => JSON.parse(value)); + assert.equal(inline.length, 1, "one merged --settings, so the hooks are kept"); + assert.equal(inline[0].env.VISUAL, claudeEnv.VISUAL); + assert.equal(inline[0].env.CANVASTTY_DRAFT_DIR, claudeEnv.CANVASTTY_DRAFT_DIR); + assert.equal(inline[0].env.CANVASTTY_DRAFT_EDITOR, claudeEnv.CANVASTTY_DRAFT_EDITOR); + for (const key of ["LANG", "LC_ALL", "LC_CTYPE"]) assert.equal(inline[0].env[key], claudeEnv[key], key); + // A plugin's own editor (even only in its --settings env) and its own locale are kept. + const plugin = (env, args) => ({ ok: true, env, secretEnv: {}, args, files: [], envSources: Object.fromEntries(Object.keys(env).map((key) => [key, "Plugin p"])) }); + terminals.spawnProcess("plugin-editor", "claude", "yolo", process.cwd(), 80, 24, null, false, "agent", undefined, + plugin({}, ["--settings", JSON.stringify({ env: { VISUAL: "plugin-editor" } })])); + assert.equal("CANVASTTY_DRAFT_DIR" in calls.at(-1).options.env, false, "a plugin's --settings editor keeps Ctrl+G"); + terminals.spawnProcess("plugin-locale", "claude", "yolo", process.cwd(), 80, 24, null, false, "agent", undefined, plugin({ LC_ALL: "C" }, [])); + const localeArgs = calls.at(-1).args; + const localeSettings = localeArgs.filter((_, index) => localeArgs[index - 1] === "--settings").map((value) => JSON.parse(value)); + assert.equal(localeSettings[0].env.CANVASTTY_DRAFT_DIR, join(root, "plugin-locale")); + assert.equal("LC_ALL" in localeSettings[0].env, false, "the plugin's locale is not replaced in background sessions"); + const codex = terminals.create({ ...base, provider: "codex" }); + assert.equal("CANVASTTY_DRAFT_DIR" in calls.at(-1).options.env, false, "only Claude cards get the helper"); + assert.equal(terminals.listMetadata().find((s) => s.id === codex.id).claudeDraft, undefined); + assert.equal(await terminals.draftAction(codex.id, "copy", ""), false); + + const running = terminals.draftAction(claude.id, "cut", ""); + terminals.input(claude.id, "после"); + assert.equal(await running, true); + assert.deepEqual(writes, ["\u0007", "после"], "typing during the round trip arrives after it"); + assert.deepEqual(clipboard, ["весь черновик"]); + } finally { + for (const session of terminals.list()) terminals.dispose(session.id); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("with the Claude draft keys turned off a new Claude keeps the person's editor and actions do nothing", { + skip: process.platform !== "darwin" && "the draft helper is macOS-only" +}, async () => { + const { root, editor } = editorFixture(); + const calls = []; + const writes = []; + let enabled = false; + const terminals = new TerminalManager(() => undefined, availableRegistry(), undefined, undefined, true, + fakeSpawner(calls, { onWrite: (data) => writes.push(data) })); + terminals.configureDraftEditor(editor); + terminals.configureDraftKeys(() => enabled); + try { + const base = { profile: "yolo", cwd: process.cwd(), position: { x: 0, y: 0 } }; + const off = terminals.create({ ...base, provider: "claude" }); + const env = calls.at(-1).options.env; + assert.equal("CANVASTTY_DRAFT_DIR" in env, false); + assert.notEqual(env.VISUAL, `/bin/sh ${helperPath}`); + assert.equal(terminals.listMetadata().find((s) => s.id === off.id).claudeDraft, undefined); + assert.equal(await terminals.draftAction(off.id, "clear", ""), false); + // Turned on again: a new Claude gets the helper; while it is off, a running one's actions do nothing. + enabled = true; + const on = terminals.create({ ...base, provider: "claude" }); + assert.equal(terminals.listMetadata().find((s) => s.id === on.id).claudeDraft, true); + enabled = false; + assert.equal(await terminals.draftAction(on.id, "clear", ""), false); + assert.deepEqual(writes, [], "no Ctrl+G was sent"); + } finally { + for (const session of terminals.list()) terminals.dispose(session.id); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/claude-editor-keys-settings.test.mjs b/tests/claude-editor-keys-settings.test.mjs new file mode 100644 index 000000000..7b40566c5 --- /dev/null +++ b/tests/claude-editor-keys-settings.test.mjs @@ -0,0 +1,53 @@ +/** + * The Claude editor keys (Settings → Keyboard → Claude editor): their own context, so the terminal's Command+C/V/A + * do not count as conflicts; submit, line break and select always keep a key; old settings get the defaults. + */ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; +import { normalizeSettings, SettingsStore } from "../src/main/services/SettingsStore.ts"; +import { DEFAULT_SHORTCUTS, keyboardPresetShortcuts, shortcutsShareContext } from "../src/shared/contracts.ts"; + +const settingsPanelPath = new URL("../src/renderer/src/features/settings/SettingsPanel.tsx", import.meta.url); +const CLAUDE_DEFAULTS = { claudeSubmit: "Meta+Enter", claudeNewline: "Enter", claudeNewlineAlternate: "Shift+Enter", claudeSelectAll: "Meta+A", + claudeCopy: "Meta+C", claudeCut: "Meta+X", claudeClear: "Backspace" }; +const claudeKeys = (shortcuts) => Object.fromEntries(Object.keys(CLAUDE_DEFAULTS).map((action) => [action, shortcuts[action]])); + +test("Claude editor defaults are the same in every preset and in older settings without them", () => { + for (const preset of ["macos", "windows", "linux"]) assert.deepEqual(claudeKeys(keyboardPresetShortcuts(preset)), CLAUDE_DEFAULTS); + const defaults = new SettingsStore("unused-settings-test-path", "en").get(); + const { claudeSubmit, claudeNewline, claudeNewlineAlternate, claudeSelectAll, claudeCopy, claudeCut, claudeClear, ...older } = keyboardPresetShortcuts("macos"); + const restored = normalizeSettings({ keyboardPreset: "custom", shortcuts: older }, defaults, "macos"); + assert.deepEqual(claudeKeys(restored.shortcuts), CLAUDE_DEFAULTS); + assert.equal(restored.shortcuts.terminalCopy, "Meta+C", "the terminal keeps its own Command+C"); +}); + +test("Claude editor keys conflict only with each other (and the detail toggle every context shares)", () => { + assert.equal(shortcutsShareContext("claudeCopy", "terminalCopy"), false); + assert.equal(shortcutsShareContext("claudeSelectAll", "codexSelectAll"), false); + assert.equal(shortcutsShareContext("claudeNewline", "codexSubmit"), false); + assert.equal(shortcutsShareContext("claudeSubmit", "commandPalette"), false); + assert.equal(shortcutsShareContext("claudeCopy", "claudeCut"), true); + assert.equal(shortcutsShareContext("claudeClear", "toggleDetail"), true); + const defaults = new SettingsStore("unused-settings-test-path", "en").get(); + const rebound = normalizeSettings({ shortcuts: { ...DEFAULT_SHORTCUTS, claudeCopy: "Meta+K", claudeSubmit: "Ctrl+Enter" } }, defaults, "macos"); + assert.equal(rebound.shortcuts.claudeCopy, "Meta+K"); + assert.equal(rebound.shortcuts.claudeSubmit, "Ctrl+Enter"); + const clash = normalizeSettings({ shortcuts: { ...DEFAULT_SHORTCUTS, claudeCut: "Meta+C", claudeCopy: "Meta+C" } }, defaults, "macos"); + assert.deepEqual(clash.shortcuts, defaults.shortcuts, "a saved clash inside the Claude editor falls back as a whole"); +}); + +test("submit, both line breaks and select keep a key; copy, cut and delete can be switched off", () => { + const defaults = new SettingsStore("unused-settings-test-path", "en").get(); + const off = Object.fromEntries(Object.keys(CLAUDE_DEFAULTS).map((action) => [action, ""])); + const normalized = normalizeSettings({ shortcuts: { ...DEFAULT_SHORTCUTS, ...off } }, defaults, "macos"); + assert.deepEqual(claudeKeys(normalized.shortcuts), { ...CLAUDE_DEFAULTS, claudeCopy: "", claudeCut: "", claudeClear: "" }); +}); + +test("the Claude editor group sits in Keyboard on macOS only, with the draft-keys switch at its top", async () => { + const source = await readFile(settingsPanelPath, "utf8"); + assert.match(source, /\["keyboardClaude", \["claudeSubmit", "claudeNewline", "claudeNewlineAlternate", "claudeSelectAll", "claudeCopy", "claudeCut", "claudeClear"\]\]/); + assert.match(source, /group !== "keyboardClaude" \|\| window\.canvasTTY\.window\.isMacOS/); + assert.equal(source.match(/claudeDraftKeysEnabled: value === "on"/g)?.length, 1, "one switch, in the Claude editor group"); + assert.match(source, /onDisable=\{REQUIRED_SHORTCUTS\.includes\(action\)/); +}); diff --git a/tests/claude-launch-settings.test.mjs b/tests/claude-launch-settings.test.mjs index ec2a49bc9..759b7765c 100644 --- a/tests/claude-launch-settings.test.mjs +++ b/tests/claude-launch-settings.test.mjs @@ -13,8 +13,6 @@ import { LaunchPipeline } from "../src/main/services/LaunchPipeline.ts"; import { TerminalManager } from "../src/main/services/TerminalManager.ts"; import { coreOwnedLaunchArgument, mergeClaudeInlineSettings } from "../src/main/services/terminalLaunch.ts"; -const CLAUDE_HAS_SANDBOX = process.platform === "darwin" || process.platform === "linux"; - const cwd = process.cwd(); const at = { x: 0, y: 0 }; const HOOKS = { showStatusInTerminalTab: true, hooks: { Stop: [{ hooks: [{ type: "command", command: "/core/hook stop" }] }] } }; @@ -112,7 +110,7 @@ async function launchClaude(t, profile, answer) { return { args: calls[0]?.args ?? null, card: current() }; } -test("Normal and Auto: one effective --settings keeps CanvasTTY's hooks (and Auto's sandbox) with the plugin's allowed keys", async (t) => { +test("Normal and Auto: one effective --settings keeps CanvasTTY's hooks with the plugin's allowed keys", async (t) => { for (const profile of ["normal", "auto"]) { for (const answer of [ { args: [`--settings=${JSON.stringify(ROUTE)}`] }, @@ -124,9 +122,8 @@ test("Normal and Auto: one effective --settings keeps CanvasTTY's hooks (and Aut const [settings] = settingsOf(args); assert.deepEqual(settings.hooks, HOOKS.hooks, `${profile}: CanvasTTY's hooks stay`); assert.deepEqual(settings.env, ROUTE.env); - // Auto adds Claude Code's own sandbox where Claude has one (macOS, Linux); this launch runs on the test's host. - if (profile === "auto" && CLAUDE_HAS_SANDBOX) assert.deepEqual(settings.sandbox, { enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: false }); - else assert.equal(settings.sandbox, undefined); + // Claude Code's own sandbox follows the person's Claude settings: CanvasTTY adds none. + assert.equal(settings.sandbox, undefined); } for (const answer of [ { args: [`--settings=${JSON.stringify({ disableAllHooks: true })}`] }, diff --git a/tests/codex-editor-keys-settings.test.mjs b/tests/codex-editor-keys-settings.test.mjs new file mode 100644 index 000000000..a8b5c7145 --- /dev/null +++ b/tests/codex-editor-keys-settings.test.mjs @@ -0,0 +1,113 @@ +/** + * The Codex editor keys (Settings → Keyboard → Codex editor) the owned Codex frontend reads from + * CANVASTTY_CODEX_KEYBOARD: submit, line break, alternate line break and select, all always bound. + */ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; +import { normalizeSettings, SettingsStore } from "../src/main/services/SettingsStore.ts"; +import { resolveTerminalLaunch } from "../src/main/services/terminalLaunch.ts"; +import { DEFAULT_SHORTCUTS, keyboardPresetShortcuts, shortcutsShareContext } from "../src/shared/contracts.ts"; + +const settingsPanelPath = new URL("../src/renderer/src/features/settings/SettingsPanel.tsx", import.meta.url); +const NEW_DEFAULTS = { codexSubmit: "Meta+Enter", codexSubmitAlternate: "", codexSubmitSuper: "", codexNewline: "Enter", + codexNewlineAlternate: "Shift+Enter", codexCopy: "Meta+C", codexCut: "Meta+X", codexClear: "Backspace" }; +const OTHER_SYSTEMS = { codexSubmit: "Enter", codexSubmitAlternate: "Ctrl+Enter", codexSubmitSuper: "Meta+Enter", + codexNewline: "Shift+Enter", codexNewlineAlternate: "", codexSelectAll: "Ctrl+A", codexCopy: "", codexCut: "", codexClear: "" }; +const OLD_DEFAULTS = { codexSubmit: "Enter", codexSubmitAlternate: "Ctrl+Enter", codexSubmitSuper: "Meta+Enter", codexNewline: "Shift+Enter" }; +const codexKeys = (shortcuts) => Object.fromEntries(Object.keys(shortcuts).filter((action) => action.startsWith("codex")) + .map((action) => [action, shortcuts[action]])); +const withoutCodex = Object.fromEntries(Object.entries(keyboardPresetShortcuts("macos")).filter(([action]) => !action.startsWith("codex"))); +// The store's defaults follow the host; these tests need a macOS host's on any CI runner. +const macDefaults = () => ({ ...new SettingsStore("unused-settings-test-path", "en").get(), keyboardPreset: "macos", + shortcuts: keyboardPresetShortcuts("macos", true) }); + +test("Codex editor defaults: Command+Enter submits, Enter and Shift+Enter break the line, Command+A selects on macOS", () => { + assert.deepEqual(codexKeys(keyboardPresetShortcuts("macos")), { ...NEW_DEFAULTS, codexSelectAll: "Meta+A" }); + assert.deepEqual(codexKeys(keyboardPresetShortcuts("linux", true)), { ...NEW_DEFAULTS, codexSelectAll: "Meta+A" }, + "a macOS host keeps them under any preset"); + // Linux and Windows keep the keys they had. + for (const shortcuts of [DEFAULT_SHORTCUTS, keyboardPresetShortcuts("linux"), keyboardPresetShortcuts("windows"), + keyboardPresetShortcuts("macos", false)]) { + assert.deepEqual(codexKeys(shortcuts), { ...OTHER_SYSTEMS, codexSelectAll: shortcuts.codexSelectAll }); + } +}); + +test("settings still at the old Codex defaults take the new ones; the extra submit keys are gone", () => { + const defaults = macDefaults(); + const saved = { keyboardPreset: "custom", shortcuts: { ...withoutCodex, ...OLD_DEFAULTS } }; + const migrated = normalizeSettings(saved, defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(migrated), { ...NEW_DEFAULTS, codexSelectAll: "Meta+A" }); + assert.equal(migrated.terminalCopy, "Meta+C", "other keys are untouched"); + const again = normalizeSettings({ ...saved, shortcuts: migrated }, defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(again), codexKeys(migrated), "saved after the migration, nothing moves"); +}); + +test("Linux and Windows settings are not migrated", () => { + const linux = normalizeSettings({}, new SettingsStore("unused-settings-test-path", "en").get(), "linux"); + const defaults = { ...linux, shortcuts: keyboardPresetShortcuts("linux") }; + const custom = { ...OTHER_SYSTEMS, codexSubmit: "Ctrl+Enter", codexSubmitAlternate: "Alt+Enter" }; + delete custom.codexNewlineAlternate; + const kept = normalizeSettings({ shortcuts: { ...keyboardPresetShortcuts("linux"), ...custom } }, defaults, "linux").shortcuts; + assert.deepEqual(codexKeys(kept), { ...custom, codexNewlineAlternate: "" }); +}); + +test("customized Codex submit and line-break keys are kept through the migration", () => { + const defaults = macDefaults(); + const custom = normalizeSettings({ shortcuts: { ...withoutCodex, ...OLD_DEFAULTS, codexSubmit: "Ctrl+Enter", codexSubmitAlternate: "" } }, + defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(custom), { ...NEW_DEFAULTS, codexSubmit: "Ctrl+Enter", codexNewline: "Shift+Enter", + codexNewlineAlternate: "Enter", codexSelectAll: "Meta+A" }, "Shift+Enter is taken, so the alternate line break gets Enter"); + const other = normalizeSettings({ shortcuts: { ...withoutCodex, ...OLD_DEFAULTS, codexNewline: "Alt+Enter" } }, defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(other), { ...NEW_DEFAULTS, codexSubmit: "Enter", codexNewline: "Alt+Enter", codexSelectAll: "Meta+A" }); + const both = normalizeSettings({ shortcuts: { ...withoutCodex, ...OLD_DEFAULTS, codexSubmitAlternate: "" } }, defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(both), { ...NEW_DEFAULTS, codexSubmit: "Enter", codexNewline: "Shift+Enter", + codexNewlineAlternate: "Alt+Enter", codexSelectAll: "Meta+A" }, "Enter and Shift+Enter both taken"); + // Settings saved after the migration keep their keys. + const current = normalizeSettings({ shortcuts: { ...withoutCodex, ...NEW_DEFAULTS, codexSubmit: "Ctrl+Enter", + codexNewline: "Shift+Enter", codexNewlineAlternate: "Alt+Enter", codexSelectAll: "Ctrl+L" } }, defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(current), { ...NEW_DEFAULTS, codexSubmit: "Ctrl+Enter", codexNewline: "Shift+Enter", + codexNewlineAlternate: "Alt+Enter", codexSelectAll: "Ctrl+L" }); +}); + +test("no Codex editor key can be switched off", () => { + const defaults = macDefaults(); + const off = { codexSubmit: "", codexNewline: "", codexNewlineAlternate: "", codexSelectAll: "", codexSubmitAlternate: "", + codexSubmitSuper: "", codexCopy: "", codexCut: "", codexClear: "" }; + const normalized = normalizeSettings({ shortcuts: { ...keyboardPresetShortcuts("macos"), ...off } }, defaults, "macos").shortcuts; + assert.deepEqual(codexKeys(normalized), { ...codexKeys(defaults.shortcuts), codexCopy: "", codexCut: "", codexClear: "" }, + "copy, cut and delete can be switched off"); +}); + +test("Codex draft copy, cut and delete clash with the Codex editor's keys, not with the terminal's Copy", () => { + assert.equal(shortcutsShareContext("codexCopy", "terminalCopy"), false); + assert.equal(shortcutsShareContext("codexCut", "terminalPaste"), false); + assert.equal(shortcutsShareContext("codexClear", "codexNewline"), true); + assert.equal(shortcutsShareContext("codexCopy", "toggleDetail"), true); + assert.equal(shortcutsShareContext("codexSubmit", "terminalCopy"), true, "the other Codex keys keep their context"); + const defaults = macDefaults(); + const { codexCopy, codexCut, codexClear, ...older } = keyboardPresetShortcuts("macos"); + const custom = normalizeSettings({ shortcuts: { ...older, codexNewline: "Backspace", codexNewlineAlternate: "Enter" } }, + defaults, "macos").shortcuts; + assert.deepEqual([custom.codexNewline, custom.codexCopy, custom.codexCut, custom.codexClear], ["Backspace", "Meta+C", "Meta+X", ""], + "a new default that clashes with a kept key starts off"); +}); + +test("the Codex editor group lists the four keys, and the frontend gets them in CANVASTTY_CODEX_KEYBOARD", async () => { + const source = await readFile(settingsPanelPath, "utf8"); + assert.match(source, /\["codexSubmit", "codexNewline", "codexNewlineAlternate", "codexSelectAll", "codexCopy", "codexCut", "codexClear"\] as ShortcutAction\[\]\s+: \["codexSubmit", "codexSubmitAlternate", "codexSubmitSuper", "codexNewline", "codexSelectAll"\]/); + const providerCli = { state: "available", provider: "codex", executable: "/official/codex", launcher: "native", + environment: {}, checked: [] }; + const launch = resolveTerminalLaunch("codex", "normal", [], { platform: "darwin", providerCli, fileExists: () => true, + environment: { CANVASTTY_CODEX_TUI_QA: "/qa/codex-tui", CANVASTTY_CODEX_TUI_LAUNCHER_QA: "/qa/launch.mjs" }, + shortcuts: { ...keyboardPresetShortcuts("macos"), codexNewlineAlternate: "Alt+Enter" } }); + assert.deepEqual(JSON.parse(launch.environment.CANVASTTY_CODEX_KEYBOARD), + { submit: "Meta+Enter", newline: "Enter", newlineAlternate: "Alt+Enter", selectAll: "Meta+A", copy: "Meta+C", cut: "Meta+X", + clear: "Backspace" }); + const linux = resolveTerminalLaunch("codex", "normal", [], { platform: "linux", providerCli, fileExists: () => true, + environment: { CANVASTTY_CODEX_TUI_QA: "/qa/codex-tui", CANVASTTY_CODEX_TUI_LAUNCHER_QA: "/qa/launch.mjs" }, + shortcuts: keyboardPresetShortcuts("linux") }); + assert.deepEqual(JSON.parse(linux.environment.CANVASTTY_CODEX_KEYBOARD), + { submit: "Enter", submitAlternate: "Ctrl+Enter", submitSuper: "Meta+Enter", newline: "Shift+Enter", selectAll: "Ctrl+A" }, + "Linux gets what it got before"); +}); diff --git a/tests/environment-keeps.test.mjs b/tests/environment-keeps.test.mjs index 7f951662b..9b16286d0 100644 --- a/tests/environment-keeps.test.mjs +++ b/tests/environment-keeps.test.mjs @@ -46,7 +46,7 @@ function setup(t, keeps, project) { decide: (input) => new AgentIsolation({ userDataPath: "/u", enabled: () => true, platform: "darwin", exists: () => true }).decide(input), wrap: (launch) => ({ command: "/usr/bin/sandbox-exec", args: ["-f", "/p.sb", launch.command, ...launch.args], env: launch.env, cleanup() {} }) }); - const create = (profile) => terminals.create({ provider: "codex", profile, cwd: project, position: at, environment: { pluginId: PLUGIN, kind: "box" } }); + const create = (profile, provider = "codex") => terminals.create({ provider, profile, cwd: project, position: at, environment: { pluginId: PLUGIN, kind: "box" } }); const card = (id) => terminals.list().find((session) => session.id === id); return { terminals, calls, create, card }; } @@ -81,10 +81,12 @@ test("an isolated environment (container, remote) is not wrapped again; a local const inside = container.create("auto"); await waitFor(() => container.calls.length === 1); assert.equal(container.calls[0].command, WRAPPER, "no second sandbox around a container"); - assert.equal(container.card(inside.id).isolation.state, "environment"); + // The person's own auto needs no layer, so the card has nothing to say about it. + assert.equal(container.card(inside.id).isolation, undefined); // No shell guard is claimed for a wrapped launch (OpenCode would otherwise run commands without asking). const local = setup(t, { launch: true }, project); - const worktree = local.create("auto"); + // The person's own auto runs as their terminal would; a contained auto (a bypass) runs only inside the layer. + const worktree = local.create("auto", "qwen"); await waitFor(() => local.calls.length === 1); assert.equal(local.calls[0].command, "/usr/bin/sandbox-exec", "the local environment's command runs inside the layer"); assert.deepEqual(local.calls[0].args.slice(0, 3), ["-f", "/p.sb", WRAPPER]); diff --git a/tests/git-audit.test.mjs b/tests/git-audit.test.mjs index 22d99ae77..83633b43d 100644 --- a/tests/git-audit.test.mjs +++ b/tests/git-audit.test.mjs @@ -214,7 +214,7 @@ test("an isolated session that ends with a dangerous git setting shows it on its const project = join(base, "p"); await mkdir(project); const { terminals, calls } = await isolatedManager(t, project); - const card = terminals.create({ provider: "codex", profile: "auto", cwd: project, position: at }); + const card = terminals.create({ provider: "qwen", profile: "auto", cwd: project, position: at }); assert.equal(card.isolation?.state, "on"); await plant(project); calls.at(-1).process.emitExit(0); @@ -233,11 +233,11 @@ test("a closed isolated card's git settings are reported to the app; keep leaves await mkdir(project); const events = []; const { terminals } = await isolatedManager(t, project, events); - const clean = terminals.create({ provider: "codex", profile: "auto", cwd: project, position: at }); + const clean = terminals.create({ provider: "qwen", profile: "auto", cwd: project, position: at }); terminals.dispose(clean.id); await new Promise((resolve) => setTimeout(resolve, 200)); assert.deepEqual(events.filter((event) => event.channel === IPC.terminalGitRisk), []); - const card = terminals.create({ provider: "codex", profile: "auto", cwd: project, position: at, title: "worker" }); + const card = terminals.create({ provider: "qwen", profile: "auto", cwd: project, position: at, title: "worker" }); await plant(project); terminals.dispose(card.id); const reported = await until(() => events.find((event) => event.channel === IPC.terminalGitRisk)?.payload); @@ -255,7 +255,7 @@ test("a card restored after the app quit mid-session is audited on restore", asy await mkdir(project); await mkdir(storeDirectory); const first = await isolatedManager(t, project, [], new TerminalSessionStore(storeDirectory)); - const card = first.terminals.create({ provider: "codex", profile: "auto", cwd: project, position: at }); + const card = first.terminals.create({ provider: "qwen", profile: "auto", cwd: project, position: at }); await plant(project); await first.terminals.shutdown(); const saved = JSON.parse(await readFile(join(storeDirectory, "terminal-sessions.json"), "utf8")).sessions; diff --git a/tests/terminal-lifecycle.test.mjs b/tests/terminal-lifecycle.test.mjs index 8ca7f9c16..807aedeb1 100644 --- a/tests/terminal-lifecycle.test.mjs +++ b/tests/terminal-lifecycle.test.mjs @@ -1,9 +1,13 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; +import { stripTypeScriptTypes } from "node:module"; import test from "node:test"; import * as terminalShortcuts from "../src/renderer/src/features/terminal/terminalShortcuts.ts"; import { keyboardPresetShortcuts } from "../src/shared/contracts.ts"; import { matchesShortcut } from "../src/renderer/src/lib/shortcuts.ts"; +import { TerminalManager } from "../src/main/services/TerminalManager.ts"; +import { availableRegistry, fakeSpawner } from "./helpers/terminal.mjs"; +import { fileURLToPath } from "node:url"; const terminalCardPath = new URL( "../src/renderer/src/features/terminal/TerminalCard.tsx", @@ -13,17 +17,44 @@ const appStylesPath = new URL("../src/renderer/src/styles/app.css", import.meta. const terminalManagerPath = new URL("../src/main/services/TerminalManager.ts", import.meta.url); const contractsPath = new URL("../src/shared/contracts.ts", import.meta.url); -function terminalKeyHandler(body, scope) { +// Runs the card's actual keyboard setup (paste and Claude draft helpers plus the xterm key handler) against fakes. +// scope.screen, when given, is the fake .xterm-screen the Claude draft highlight layer is added to. +function terminalKeyHandler(source, scope) { + const setup = source.match(/^ const pasteClipboard[\s\S]*?^ terminal\.attachCustomKeyEventHandler\(\(event\) => \{[\s\S]*?^ \}\);/m)?.[0]; + assert.ok(setup, "the terminal's actual keyboard handler must be located"); + let handler; + const listeners = { write: [] }; + // The fake is extended in place: tests compare it with terminalRef.current. + const terminal = Object.assign(scope.terminal ?? {}, { + hasSelection: scope.terminal?.hasSelection ?? (() => false), + attachCustomKeyEventHandler: (attached) => { handler = attached; }, + onWriteParsed: (listener) => { listeners.write.push(listener); return { dispose() {} }; }, + onResize: () => ({ dispose() {} }), + element: { + addEventListener: (type, listener) => { if (type === "mousedown") scope.onMouseDown?.(listener); }, + removeEventListener() {} + } + }); const values = { ...terminalShortcuts, matchesShortcut, nativeEditorRef: { current: null }, shortcutsRef: { current: keyboardPresetShortcuts("macos") }, sessionExited: { current: false }, + sessionStartedAt: { current: 1 }, + terminalRef: { current: terminal }, terminalHost: { current: null }, - terminal: { hasSelection: () => false }, - ...scope + claudeDraftSelected: { current: false }, + claudeDraftRef: { current: scope.session?.claudeDraft === true }, + claudeKeysRef: { current: true }, + document: { createElement: () => ({ className: "", hidden: false, style: {}, parentElement: null }) }, + screen: undefined, + ...scope, + terminal }; - return new Function(...Object.keys(values), `return (event) => {${body}}`)(...Object.values(values)); + delete values.onMouseDown; + new Function(...Object.keys(values), stripTypeScriptTypes(setup))(...Object.values(values)); + scope.repaint = () => listeners.write.forEach((listener) => listener()); + return handler; } test("actual Codex handler preserves Enter modifiers before xterm can collapse them", async () => { @@ -35,7 +66,7 @@ test("actual Codex handler preserves Enter modifiers before xterm can collapse t window: { isMacOS: true }, terminal: { input: (id, sequence) => writes.push([id, sequence]) } } }; - const handler = terminalKeyHandler(body, { window, session: { id: "draft", provider: "codex" } }); + const handler = terminalKeyHandler(source, { window, session: { id: "draft", provider: "codex" } }); for (const code of ["Enter", "NumpadEnter"]) { for (const [modifiers, sequence] of [ [{}, "\r"], [{ shiftKey: true }, "\u001b[13;2u"], [{ metaKey: true }, "\u001b[13;9u"], @@ -74,12 +105,13 @@ test("Command+A dispatches native Codex selection and leaves other providers and preventDefault: () => calls.push("prevent"), stopPropagation: () => calls.push("stop") }; - const codex = terminalKeyHandler(body, { window, session: { id: "codex-qa", provider: "codex" }, terminal }); + const codex = terminalKeyHandler(source, { window, session: { id: "codex-qa", provider: "codex" }, terminal }); assert.equal(codex(event), false); assert.deepEqual(calls, ["prevent", "stop", "clear", ["codex-qa", "\u001b[97;9u"]]); calls.length = 0; - for (const provider of ["terminal", "claude", "gemini"]) { - const handler = terminalKeyHandler(body, { window, session: { id: provider, provider }, terminal }); + // Claude's Command+A is CanvasTTY's own draft selection (its own test below). + for (const provider of ["terminal", "gemini"]) { + const handler = terminalKeyHandler(source, { window, session: { id: provider, provider }, terminal }); assert.equal(handler(event), true); } for (const change of [ @@ -90,6 +122,300 @@ test("Command+A dispatches native Codex selection and leaves other providers and assert.deepEqual(calls, []); }); +test("a locally launched Codex card forwards its actual Cut binding after create, restart and restore", { + skip: process.platform !== "darwin" +}, async () => { + const source = await readFile(terminalCardPath, "utf8"); + const calls = []; + const events = []; + const runtime = { + prepareLaunch: () => ({ args: [], environment: { + CANVASTTY_CODEX_TUI_QA: fileURLToPath(import.meta.url), + CANVASTTY_CODEX_TUI_LAUNCHER_QA: fileURLToPath(import.meta.url) + }, cleanup() {} }), + currentStatus: () => null + }; + const manager = new TerminalManager((_, event) => events.push(event), availableRegistry(), undefined, + runtime, true, fakeSpawner(calls)); + let shortcuts = keyboardPresetShortcuts("macos"); + manager.setKeyboardShortcuts(shortcuts); + const verify = (session, letter) => { + assert.deepEqual(session.nativeEditor, JSON.parse(calls.at(-1).options.env.CANVASTTY_CODEX_KEYBOARD)); + assert.deepEqual(events.at(-1).session.nativeEditor, session.nativeEditor); + const writes = []; + const handler = terminalKeyHandler(source, { session, nativeEditorRef: { current: session.nativeEditor }, + window: { canvasTTY: { window: { isMacOS: true }, terminal: { input: (...args) => writes.push(args) } } } }); + assert.equal(handler({ type: "keydown", key: letter, code: `Key${letter.toUpperCase()}`, metaKey: true, + ctrlKey: false, altKey: false, shiftKey: false, preventDefault() {}, stopPropagation() {} }), false); + assert.deepEqual(writes, [[session.id, `\u001b[${letter.charCodeAt(0)};9u`]]); + }; + try { + const session = manager.create({ provider: "codex", profile: "normal", cwd: process.cwd(), position: { x: 0, y: 0 } }); + verify(session, "x"); + shortcuts = { ...shortcuts, codexCut: "Meta+K" }; + manager.setKeyboardShortcuts(shortcuts); + calls.at(-1).process.emitExit(0); + verify(manager.restart(session.id), "k"); + const descriptor = { ...session, id: "restored-codex", lastState: "running", restore: true }; + delete descriptor.nativeEditor; + manager.configureSessionPersistence({ load: async () => [descriptor], replace: async () => {} }, "continue"); + await manager.restorePersistedSessions(); + verify(manager.list().find(card => card.id === descriptor.id), "k"); + } finally { + manager.disposeAll(); + } +}); + +test("the Codex draft keys reach Codex; selected output keeps the terminal's Copy; a plain delete key passes as it is", async () => { + const source = await readFile(terminalCardPath, "utf8"); + const calls = []; + let selected = false; + const terminal = { clearSelection: () => calls.push("clear"), hasSelection: () => selected, getSelection: () => "вывод" }; + const window = { canvasTTY: { + window: { isMacOS: true }, + clipboard: { writeText: (text) => calls.push(["clipboard", text]) }, + terminal: { input: (id, sequence) => calls.push([id, sequence]) } + } }; + const nativeEditor = { submit: "Meta+Enter", newline: "Enter", newlineAlternate: "Shift+Enter", selectAll: "Meta+A", + copy: "Meta+C", cut: "Meta+X", clear: "Backspace" }; + const handler = terminalKeyHandler(source, { window, session: { id: "codex", provider: "codex" }, terminal, + nativeEditorRef: { current: nativeEditor } }); + const key = (code, key, metaKey = true) => ({ type: "keydown", key, code, metaKey, ctrlKey: false, shiftKey: false, + altKey: false, preventDefault: () => {}, stopPropagation: () => {} }); + assert.equal(handler(key("KeyX", "x")), false); + assert.equal(handler(key("KeyX", "ч")), false, "Cut uses the physical key on a Russian layout"); + assert.equal(handler(key("KeyC", "c")), false); + selected = true; + assert.equal(handler(key("KeyC", "c")), false); + assert.equal(handler(key("Backspace", "Backspace", false)), true, "Codex gets its usual Backspace byte"); + assert.deepEqual(calls, [["codex", "\u001b[120;9u"], ["codex", "\u001b[120;9u"], ["codex", "\u001b[99;9u"], ["clipboard", "вывод"]]); +}); + +// A fake xterm whose screen shows `rows()`: Claude's prompt box is the part between the last two rules. +const screenTerminal = (rows) => ({ + get rows() { return rows().length; }, + buffer: { active: { viewportY: 0, getLine: (index) => ({ translateToString: () => rows()[index] ?? "" }) } }, + hasSelection: () => false +}); + +test("macOS Claude editor: Enter breaks the line and Command+Enter submits only while the prompt box is on screen", async () => { + const source = await readFile(terminalCardPath, "utf8"); + const writes = []; + const window = { canvasTTY: { + window: { isMacOS: true }, + terminal: { input: (id, sequence) => writes.push([id, sequence]) } + } }; + const rule = "─".repeat(40); + let rows = ["history", rule, "❯ draft", rule, " footer"]; + const key = (handler, modifiers, code = "Enter") => handler({ type: "keydown", key: "Enter", code, ctrlKey: false, + altKey: false, shiftKey: false, metaKey: false, ...modifiers, preventDefault() {}, stopPropagation() {} }); + const claudeKeysRef = { current: true }; + const shortcutsRef = { current: keyboardPresetShortcuts("macos") }; + const claude = terminalKeyHandler(source, { window, session: { id: "claude", provider: "claude" }, + terminal: screenTerminal(() => rows), claudeKeysRef, shortcutsRef }); + assert.equal(key(claude, {}), false); + assert.equal(key(claude, {}, "NumpadEnter"), false); + assert.equal(key(claude, { metaKey: true }), false); + assert.equal(key(claude, { shiftKey: true }), false, "Shift+Enter stays a line break"); + assert.equal(key(claude, { metaKey: true, isComposing: true }), true); + assert.equal(key(claude, { type: "keyup" }), true); + assert.deepEqual(writes.splice(0), [["claude", "\u001b[13;2u"], ["claude", "\u001b[13;2u"], ["claude", "\r"], + ["claude", "\u001b[13;2u"]]); + + // A dialog in place of the prompt box keeps Enter: it answers the dialog. + rows = ["Do you want to proceed?", "❯ 1. Yes", " 2. No"]; + assert.equal(key(claude, {}), true, "plain Enter stays xterm's carriage return"); + assert.equal(key(claude, { metaKey: true }), true); + assert.deepEqual(writes.splice(0), []); + + // Rebinding applies at once, in the open card. + rows = ["history", rule, "❯ draft", rule]; + shortcutsRef.current = { ...shortcutsRef.current, claudeSubmit: "Ctrl+Enter", claudeNewline: "Alt+Enter", + claudeNewlineAlternate: "Shift+Meta+Enter" }; + assert.equal(key(claude, {}), true, "an unbound plain Enter is Claude's own submit"); + assert.equal(key(claude, { ctrlKey: true }), false); + assert.equal(key(claude, { altKey: true }), false); + assert.equal(key(claude, { metaKey: true, shiftKey: true }), false, "the alternate line break"); + assert.deepEqual(writes.splice(0), [["claude", "\r"], ["claude", "\u001b[13;2u"], ["claude", "\u001b[13;2u"]]); + shortcutsRef.current = keyboardPresetShortcuts("macos"); + + // Switched off: no Claude editor keys at all; the generic Shift+Enter line break stays. + claudeKeysRef.current = false; + assert.equal(key(claude, {}), true); + assert.equal(key(claude, { metaKey: true }), true); + assert.equal(key(claude, { shiftKey: true }), false); + assert.deepEqual(writes.splice(0), [["claude", "\u001b[13;2u"]]); + claudeKeysRef.current = true; + + const linux = terminalKeyHandler(source, { window: { canvasTTY: { ...window.canvasTTY, window: { isMacOS: false } } }, + session: { id: "claude", provider: "claude" }, terminal: screenTerminal(() => rows) }); + assert.equal(key(linux, {}), true, "other platforms keep their own Enter"); + assert.equal(key(linux, { metaKey: true }), true); + const shell = terminalKeyHandler(source, { window, session: { id: "shell", provider: "terminal" }, + terminal: screenTerminal(() => rows) }); + assert.equal(key(shell, {}), true); + assert.equal(key(shell, { metaKey: true }), true); + assert.deepEqual(writes, []); +}); + +test("Command+A selects a macOS Claude draft that copy, cut, typing, paste and deletion act on as a whole", async () => { + const source = await readFile(terminalCardPath, "utf8"); + const calls = []; + const rule = "─".repeat(40); + let rows = ["history", rule, "❯ first line", " second line", rule, " footer"]; + const terminal = { + rows: rows.length, + buffer: { active: { viewportY: 10, getLine: (index) => ({ translateToString: () => rows[index - 10] ?? "" }) } }, + selectLines: () => calls.push("xterm selection"), + clearSelection: () => calls.push("xterm clear"), + paste: (text) => calls.push(["paste", text]), + modes: { bracketedPasteMode: true } + }; + const screen = { clientHeight: 120, append(child) { child.parentElement = screen; screen.layer = child; } }; + let mouseDown; + const window = { canvasTTY: { + window: { isMacOS: true }, + clipboard: { hasImage: async () => false, readText: async () => "из буфера" }, + terminal: { + input: (id, data) => calls.push(["input", data]), + draftAction: async (id, action, followUp, paste) => { calls.push(["draft", action, followUp ?? "", ...(paste ? [paste] : [])]); return true; } + } + } }; + const scope = { window, terminal, screen, sessionStartedAt: { current: 1 }, + session: { id: "claude-card", provider: "claude", claudeDraft: true }, + onMouseDown: (listener) => { mouseDown = listener; } }; + const handler = terminalKeyHandler(source, scope); + const key = (key, code, modifiers = {}) => handler({ type: "keydown", key, code, ctrlKey: false, shiftKey: false, + altKey: false, metaKey: false, repeat: false, ...modifiers, preventDefault() {}, stopPropagation() {} }); + const tick = () => new Promise((resolve) => setImmediate(resolve)); + const highlight = () => screen.layer.hidden ? null : [screen.layer.style.top, screen.layer.style.height]; + + assert.equal(screen.layer.className, "terminal-card__draft-highlight"); + assert.equal(highlight(), null); + assert.equal(key("ч", "KeyX", { metaKey: true }), false, "Command+X without a selection does nothing"); + assert.equal(key("ф", "KeyA", { metaKey: true }), false); + assert.deepEqual(highlight(), ["40px", "40px"], "the visible prompt rows show the selection"); + rows = ["history", "more", rule, "❯ first line", " second line", rule]; + scope.repaint(); + assert.deepEqual(highlight(), ["60px", "40px"], "the layer follows Claude's repaint"); + assert.equal(key("Shift", "ShiftLeft", { shiftKey: true }), true, "a modifier alone keeps the selection"); + assert.equal(key("с", "KeyC", { metaKey: true }), false); + assert.equal(key("с", "KeyC", { metaKey: true }), false, "copying keeps the selection"); + assert.equal(key("с", "KeyC", { metaKey: true, repeat: true }), false, "a held shortcut acts once"); + assert.notEqual(highlight(), null); + assert.equal(key("ж", "Semicolon"), false); + await tick(); + assert.deepEqual(calls.splice(0), [["draft", "copy", ""], ["draft", "copy", ""], ["draft", "clear", "ж"]], + "xterm's own selection is never used"); + assert.equal(highlight(), null); + assert.equal(key("я", "KeyZ"), true, "typing after the replacement is ordinary input"); + + for (const [press, expected] of [ + [() => key("ч", "KeyX", { metaKey: true }), [["draft", "cut", ""]]], + [() => key("Backspace", "Backspace"), [["draft", "clear", ""]]], + [() => key("Delete", "Delete"), [["draft", "clear", ""]]], + // The main process types the clipboard right after the clear, in order with later keys. + [() => key("м", "KeyV", { metaKey: true }), [["draft", "clear", "", "bracketed"]]] + ]) { + key("a", "KeyA", { metaKey: true }); + calls.length = 0; + assert.equal(press(), false); + for (let i = 0; i < 4; i += 1) await tick(); + assert.deepEqual(calls, expected); + calls.length = 0; + } + + key("a", "KeyA", { metaKey: true }); + assert.equal(key("a", "KeyA", { metaKey: true, repeat: true }), false); + assert.equal(key("ч", "KeyX", { metaKey: true, repeat: true }), false, "holding Command+X cannot cut"); + assert.deepEqual(calls.splice(0), []); + assert.equal(key("ArrowLeft", "ArrowLeft"), true, "other keys drop the selection and reach Claude"); + assert.equal(highlight(), null); + key("a", "KeyA", { metaKey: true }); + assert.equal(key("Enter", "Enter", { metaKey: true }), false); + assert.deepEqual(calls.splice(0), [["input", "\r"]], "Command+Enter drops the selection, then submits"); + assert.equal(highlight(), null); + key("a", "KeyA", { metaKey: true }); + mouseDown(); + assert.equal(highlight(), null); + assert.equal(key("ж", "Semicolon"), true, "a click replaces the draft selection"); + assert.deepEqual(calls, []); + + key("a", "KeyA", { metaKey: true }); + scope.sessionStartedAt.current = 2; + assert.equal(key("ж", "Semicolon"), true, "a restarted Claude has a new draft: no selection carries over"); + key("a", "KeyA", { metaKey: true }); + rows = ["Do you want to proceed?", "❯ 1. Yes", " 2. No"]; + scope.repaint(); + assert.equal(highlight(), null); + assert.equal(key("Backspace", "Backspace"), true, "with a dialog in place of the prompt the key is the dialog's"); + assert.equal(key("a", "KeyA", { metaKey: true }), false); + assert.equal(key("Backspace", "Backspace"), true, "Command+A selects nothing without a prompt on screen"); + rows = ["history", rule, "❯ draft", rule]; + scope.repaint(); + key("a", "KeyA", { metaKey: true }); + rows = ["Do you want to proceed?", "❯ 1. Yes", " 2. No"]; + key("a", "KeyA", { metaKey: true }); + rows = ["history", rule, "❯ draft", rule]; + scope.repaint(); + assert.equal(highlight(), null, "Command+A over a dialog drops an earlier selection instead of keeping it hidden"); + assert.equal(key("Backspace", "Backspace"), true); + assert.deepEqual(calls, []); +}); + +test("a Claude card launched without the draft helper keeps xterm's own Command+A and clipboard keys", async () => { + const source = await readFile(terminalCardPath, "utf8"); + const calls = []; + const window = { canvasTTY: { + window: { isMacOS: true }, + terminal: { input: (id, data) => calls.push(data), draftAction: async () => calls.push("draft") } + } }; + const handler = terminalKeyHandler(source, { window, session: { id: "plugin-claude", provider: "claude" } }); + const key = (key, code, modifiers = {}) => handler({ type: "keydown", key, code, ctrlKey: false, shiftKey: false, + altKey: false, metaKey: false, repeat: false, ...modifiers, preventDefault() {}, stopPropagation() {} }); + assert.equal(key("a", "KeyA", { metaKey: true }), true); + assert.equal(key("Backspace", "Backspace"), true); + assert.equal(key("x", "KeyX", { metaKey: true }), true); + assert.deepEqual(calls, [], "no Ctrl+G, so Claude never opens the person's editor"); +}); + +test("Claude prompt rows are found between the last two rules, and nothing is guessed without them", () => { + const rule = "─".repeat(30); + assert.deepEqual(terminalShortcuts.claudePromptRows(["a", rule, "❯ x", rule, "footer"]), { first: 2, last: 2 }); + assert.deepEqual(terminalShortcuts.claudePromptRows([rule, "old", rule, "❯ x", " y", " " + rule, ""]), { first: 3, last: 4 }); + assert.equal(terminalShortcuts.claudePromptRows(["❯ x", rule]), null); + assert.equal(terminalShortcuts.claudePromptRows([rule, rule]), null); + const commandA = { type: "keydown", key: "a", code: "KeyA", metaKey: true, ctrlKey: false, shiftKey: false, altKey: false }; + const mac = keyboardPresetShortcuts("macos"); + for (const provider of ["codex", "terminal"]) { + assert.equal(terminalShortcuts.claudeDraftKeyIntent(commandA, true, provider, false, mac), null); + } + assert.equal(terminalShortcuts.claudeDraftKeyIntent(commandA, false, "claude", false, mac), null, "macOS only"); + assert.equal(terminalShortcuts.claudeDraftKeyIntent({ ...commandA, isComposing: true }, true, "claude", false, mac), null); +}); + +test("Claude draft keys follow their bindings; an empty binding is switched off", () => { + const press = (key, code, modifiers = {}) => ({ type: "keydown", key, code, metaKey: false, ctrlKey: false, + shiftKey: false, altKey: false, ...modifiers }); + const intent = (event, selected, bindings) => terminalShortcuts.claudeDraftKeyIntent(event, true, "claude", selected, bindings); + const mac = keyboardPresetShortcuts("macos"); + assert.equal(intent(press("ф", "KeyA", { metaKey: true }), false, mac), "select", "the physical key, any layout"); + assert.equal(intent(press("Backspace", "Backspace"), true, mac), "clear"); + assert.equal(intent(press("Delete", "Delete"), true, mac), "clear", "forward delete goes with the Mac delete key"); + assert.equal(intent(press("Backspace", "Backspace"), false, mac), null, "without a selection deletion is Claude's"); + const custom = { ...mac, claudeSelectAll: "Shift+Meta+A", claudeCopy: "", claudeCut: "Ctrl+X", claudeClear: "Delete" }; + assert.equal(intent(press("a", "KeyA", { metaKey: true }), false, custom), null, "the old key is free again"); + assert.equal(intent(press("A", "KeyA", { metaKey: true, shiftKey: true }), false, custom), "select"); + assert.equal(intent(press("c", "KeyC", { metaKey: true }), true, custom), "deselect", "copy switched off"); + assert.equal(intent(press("x", "KeyX", { ctrlKey: true }), true, custom), "cut"); + assert.equal(intent(press("x", "KeyX", { metaKey: true }), true, custom), "deselect"); + assert.equal(intent(press("Delete", "Delete"), true, custom), "clear"); + assert.equal(intent(press("Backspace", "Backspace"), true, custom), "deselect", "Backspace edits as usual"); + assert.equal(intent(press("v", "KeyV", { metaKey: true }), true, { ...mac, terminalPaste: "Ctrl+Shift+V" }), "deselect", + "paste follows the terminal Paste key"); + assert.equal(intent(press("V", "KeyV", { ctrlKey: true, shiftKey: true }), true, { ...mac, terminalPaste: "Ctrl+Shift+V" }), "paste"); +}); + test("clipboard replies cannot paste into a restarted or exited session while normal text and image paste stay intact", async () => { const source = await readFile(terminalCardPath, "utf8"); const body = source.match(/terminal\.attachCustomKeyEventHandler\(\(event\) => \{([\s\S]*?)^ \}\);/m)?.[1]; @@ -122,7 +448,7 @@ test("clipboard replies cannot paste into a restarted or exited session while no }, terminal: { input: (id, sequence) => calls.push([id, sequence]) } } }; - const handler = terminalKeyHandler(body, { window, session: { id: "same-card", provider: "codex" }, terminal, + const handler = terminalKeyHandler(source, { window, session: { id: "same-card", provider: "codex" }, terminal, terminalRef, sessionExited, sessionStartedAt }); return { handler, image, text, calls, reads, terminalRef, sessionExited, sessionStartedAt }; };