Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(agents): Cursor Agent CLI as a builtin agent (#1128)
Dev Goswami295f9ed7d033
diff --git a/README.md b/README.mdindex 566d14932..b0f56e28f 100644--- a/README.md+++ b/README.md@@ -123,7 +123,7 @@ never leaves the machine.### Node kinds🖥 **Terminal** (xterm + tmux, AI naming) · 🤖 **Agent** (Claude Code / Codex / Antigravity /-Gemini / GitHub Copilot / opencode / Grok / custom) · 📝 **Sticky note** (link to an agent as context) · 🗂 **Group**+Gemini / GitHub Copilot / opencode / Grok / Cursor / custom) · 📝 **Sticky note** (link to an agent as context) · 🗂 **Group**(bind to a **git worktree** for agent-per-branch) · ✏️ **Editor** (Monaco, ⌘S) ·🔀 **Diff** · 🌐 **Web / Video**diff --git a/docs/cursor-agent.md b/docs/cursor-agent.mdnew file mode 100644index 000000000..dbe8e3f1f--- /dev/null+++ b/docs/cursor-agent.md@@ -0,0 +1,571 @@+# Cursor Agent CLI (`cursor-agent`) as a nodeterm agent++Builtin id `cursor` (`AGENT_CONFIG.cursor`, launch `cursor-agent`, prompt behind the `agent`+subcommand). Sections 1 to 8 cover the status-hook leaf: `cursor` is a member of+`AGENT_HOOK_TARGETS`, so a Cursor node gets the RUNNING badge, the unread dot, the completion+notification, `--after` dependencies and trigger targets. The later sections cover every capability+it joined since (model and permission flags, chat, meter, session continuity, NEEDS YOU,+orchestration). Sibling write-ups:+`docs/antigravity-agent.md` (closest precedent), `docs/grok-agent.md`.++**Where the facts come from.** Measured on `cursor-agent` 2026.09.28-64d2043 (macOS): five headless+(`-p`) runs on a paid account, two zero-cost interactive TUI launches, and the shipped JS bundle+(`~/.local/share/cursor-agent/versions/*/`). The installed CLI auto-updated from 2026.09.23 during+the work. Fixture: `src/shared/agents/__fixtures__/cursor/hook-payloads.json`.++## 1. The recorded id (for the resume work)++Every hook payload carries **`conversation_id`** and a duplicate **`session_id`** (equal in every+capture). `normalizeCursor` records `conversation_id` (falling back to `session_id`) as the event's+`sessionId`, which is how every agent's id reaches `agentStatus`. **Verified with zero cost:**+`cursor-agent --resume <conversation_id>` opens that chat with its history. `cursor-agent+create-chat` prints a new empty chat id. The transcript path is+`~/.cursor/projects/<workspace path with non-alphanumerics as "-">/agent-transcripts/<id>/<id>.jsonl`+(JSONL; the last line is `{"type":"turn_ended","status":"success"|"error"}`), and the payload's+`transcript_path` names it once the first turn is written (null before).++## 2. Hook config++- Files read: `~/.cursor/hooks.json`, `<workspace>/.cursor/hooks.json`, enterprise/team files, and+ **`~/.claude/settings.json` (+ project `.claude/settings*.json`)** as Claude compat.+- Shape: `{"version":1,"hooks":{"<camelCaseEvent>":[{"command":"...","timeout":5}]}}`, flat entries.+- 21 events exist. We subscribe six (`CURSOR_HOOK_EVENTS`): `beforeSubmitPrompt`, `preToolUse`,+ `postToolUse`, `postToolUseFailure`, `stop`, `sessionEnd` (see "Session continuity").+- Payload envelope (all events): `conversation_id`, `session_id`, `generation_id`, `model`,+ `hook_event_name`, `cursor_version`, `workspace_roots[]`, `user_email`, `transcript_path`. Tool+ events add `tool_name` (`Shell`, ...), `tool_input`, `tool_use_id`, `cwd` (was `""`), and+ `postToolUse` adds `tool_output`, `duration`. Hook env carries `CURSOR_PROJECT_DIR`,+ `CURSOR_VERSION`, `CURSOR_TRANSCRIPT_PATH`, `CLAUDE_PROJECT_DIR`, and the parent's env+ (so `NODETERM_NODE_ID` reaches our script).+- `sessionStart` fires once at startup, **not on `--resume`** (measured in the TUI and in the bundle).+ Re-measured on 2026.10.01 (private tmux, project-level logger, no prompt): a plain `cursor-agent`+ fires it within seconds, before any prompt, with `conversation_id` (== `generation_id`); a+ `cursor-agent --resume <fresh uuid>` (how nodeterm launches EVERY node, minted id included) fired+ nothing until `/quit` (`sessionEnd`), two runs. So it is not subscribed: it would not give a fresh+ nodeterm node a status before its first turn (no DROPPED chip if it is killed before one).++## 3. Is the hook a gate? Yes, for some events; silence is the safe default++From the bundle (`executeCommandHook`) and confirmed by runs:++| hook result | effect |+|---|---|+| empty stdout, exit 0 | no-op; the tool ran (measured on `preToolUse`) |+| exit 2 | DENY on gating events (`preToolUse`, `beforeShellExecution`, `beforeMCPExecution`, `beforeReadFile`, `subagentStart`) |+| any other non-zero exit, timeout | logged as failed, fail-open unless the entry sets `failClosed` |+| stdout that is not valid JSON | DENY on gating events ("blocked for safety") |++So the installed command is `sh <script> >/dev/null 2>&1 || :` (`buildManagedHookCommand`+`silent`): a broken script can never print garbage or exit 2. Our script prints nothing anyway.++Traps found:+- Cursor strips `//...` from hooks.json as JSONC comments **ignoring quotes**, before parsing. A+ command containing `//` corrupts the whole file for every tool. The installer refuses to write one.+- **A headless run subscribed to 18 events (incl. `afterAgentResponse`, `afterAgentThought`,+ shell/MCP/file events) plus a claude-format project file lost its agent stream after the first+ reply three times ("Connection lost... WritableIterable is closed"); the same run with the five+ events plus sessionStart/sessionEnd finished clean.** Which difference broke it is unknown, so the+ extra events are not subscribed. Device item 3.+- Server tells the client which steps have hooks (`hooksConfig.configuredSteps`) and calls only those.++## 4. State mapping (`normalizeCursor`, pure, closed set of exact names)++| event | result |+|---|---|+| `beforeSubmitPrompt` | `working`, `newTurn` |+| `preToolUse` / `postToolUse` / `postToolUseFailure` | `working`; null for a subagent's call (`isCursorChildToolEvent`); the parent's `Task` preToolUse is `subagent-start` (see "Orchestration parity") |+| `stop` | `done`; `interrupted` if `status==="aborted"`, `errored` if `"error"` |+| `sessionEnd` | session phase `end` (skipped when `is_background_agent`) |+| anything else | null |++The phone's activity line comes from the raw listener (`applyCursorRaw`): a parent `preToolUse` is+recorded as claude's `PreToolUse` (tool name and input, so `Shell` reads "Running ..."), `stop` /+`sessionEnd` as `Stop`; a child's tool event is skipped.++**No NEEDS YOU from the normalizer.** Measured: the `AskQuestion` tool fires no tool hook (headless+and TUI); Cursor's own approval prompt has no hook either. Guessing one from events would strobe+(rule 7). The approval prompt and the AskQuestion box are detected from the pane instead: see+"NEEDS YOU, SSH hooks and lost stop" below.++## 5. Cross-fire with nodeterm's claude hook (measured)++With a matcher-bearing claude-format settings file, Cursor ran the claude hook command on its own+`sessionStart`/`preToolUse`/`postToolUse` (payload keys unchanged, `hook_event_name` camelCase).+A file with only matcher-less entries is NOT treated as claude-format (Cursor's `isClaudeFormat`+needs one `matcher`), but this machine's `~/.claude/settings.json` has other tools' matcher entries,+so nodeterm's `claude.sh` fires in every Cursor node here. **Inert:** `normalizeClaude` compares exact+PascalCase names and returns null for every captured cursor payload (pinned in+`normalize.cursor.test.ts`), and the claude raw listener returns before any association or tail write+for a payload that `isCursorPayload` recognises (`cursor_version` or `conversation_id`; no Claude+payload has either). It used to record `nodeContextSession.set(node, session_id)`, often a CHILD's+id, so `pty:destroy` released the wrong session and the parent's cursor tail leaked (pinned in+`src/server/agent-status.test.ts`). Cost: two POSTs per event. Do not canonicalise claude's+event-name compare.++## 6. Installer (`core/agents/hooks/cursor.ts`)++Merges into the SHARED `~/.cursor/hooks.json` (the real one holds another tool's `sessionStart`+entry) through `updateSettingsFile` (symlink-safe, locked, mode kept, ENOENT-only creation): our+entries are appended to the five events, ours are swept from any other event, every other+entry/key survives, an unparseable or mis-shaped file is left byte-for-byte, a second run writes+nothing. Only where `cursor-agent` is found (PATH, then `~/.local/bin`); one boot pass (no+login-shell re-probe like agy). Removal deletes only our entries and never creates the file. Ours =+command containing `.nodeterm/agent-hooks/cursor.sh`. Tests use a temp dir, never the real home.++Consent (issue #744, `core/agent-integrations.ts`): the installer runs only for a `cursor` choice of+`enabled`, like every other agent. `declined` runs `removeCursorHooks`, deletes `cursor.sh` and our+two skills from `~/.cursor/skills` (exact-content receipts; a file the user edited is kept). Never+asked = nothing written, nothing removed.++## 7. Surfaces and what is not done++- Desktop and Server Edition: both via the consent lifecycle (`installManagedAgentHooks`); state comes from the normalizer,+ and both raw listeners call the one shared `applyCursorRaw` (meter, subagents, activity line).+ Mobile: status mirror is agent-agnostic.+- SSH: `RemoteHooks.installCursorRemote` (see "NEEDS YOU, SSH hooks and lost stop" below).+- Windows: `installCursorHooks` writes nothing (`'refused'`). The command is POSIX sh, Windows+ hook execution is unmeasured, and a non-JSON byte on `preToolUse` denies the tool in every+ cursor session on the machine. The remote installer only targets POSIX hosts.+- Joined since this section was first written: resume, mint, session end and the model list+ ("Session continuity"), chat/transfer/context link and the meter, canvas control, rename and+ subagents ("Orchestration parity"), plan usage in the usage pill (see "Context meter"). Not joined:+ recurring (`/loop`), branch (claude-only).++## 8. Device checklist (unverified)++1. Answered: the interactive TUI fires `beforeSubmitPrompt` and `stop` (see "NEEDS YOU").+2. `stop` payload: `completed` captured (interactive subagent run); `aborted|error` still assumed, and whether Esc fires it.+3. Bisect the 18-event stream failure (add events back one at a time in a headless run).+4. ~~Subagent behaviour~~ measured on 2026.10.01, see "Orchestration parity".+5. Answered: `/quit` fires `sessionEnd`; cursor is in `SESSION_END_CAPABLE` ("Session continuity").+6. Answered: no hook for either (measured in the TUI); both the approval prompt and the AskQuestion box are read from the pane.+7. Hook latency inside a node (script backgrounds the POST; expected small).+8. Linux and Windows: hooks.json location, `cursor-agent` install dir.++## Model and permission flags++Measured on `cursor-agent` 2026.09.28-64d2043 (macOS). Cursor is in `MODEL_SWITCH_CAPABLE` and+`PERMISSION_MODE_CAPABLE`; the translation lives in `src/shared/agents/approval-mode.ts`+(`CURSOR_MODES`) and `withAgentModel` in `model-gateway.ts`.++### Where the flags go++The composed line is `cursor-agent [flags] agent '<prompt>'`, flags BEFORE `agent`. `agent` is a+commander subcommand with no options of its own; its action reads the root program's options+(`Ie()` is `root.opts()` in the bundle), and root parses `--model`, `--force`, `--mode` wherever they+sit. Measured in the TUI (no prompt, so no model cost) both `cursor-agent --model X agent` and+`cursor-agent agent --model X` show model X; the same for `--force` ("Run Everything"), `--mode plan`+and `--auto-review`. Both composers (`assembleLaunchCommand`, `core/agent-launch.ts`) are pinned by+tests.++### Mode table++| nodeterm mode | emitted | why |+|---|---|---|+| Ask each time (`manual`) | nothing | cursor's default is `approvalMode: allowlist`; a shell command off the allowlist stops at "Run this command? Not in allowlist" (measured) |+| Auto (`auto`, the default) | `--auto-review` | Cursor's Smart Auto: a classifier auto-runs safe calls and prompts for the rest, the same shape as claude's `auto`. Measured on 2026.10.01: `touch` ran unprompted, footer "Auto-review". Cursor ships in this change, so no existing node widens. |+| Accept edits | nothing | no flag means "auto-approve edits, prompt for shell" |+| Plan | `--mode plan` | measured: a "create a file" prompt produced a written plan ("Ready to build?"), no file |+| Bypass all | `--force` | measured: the shell command ran with no prompt, footer "Run Everything" |++Only `acceptEdits` shows in `unsupportedModesNote`. `--sandbox` is a separate axis and is not+touched (cursor's sandbox is off by default, so the Bypass caveat does not claim one). `--mode ask`+has no nodeterm mode.++### Models++`--model <id>`, quoted by `withAgentModel`. The catalogue is `cursor-agent models` (about 250+account-scoped ids, `<id> - <label>` lines, some with zero-width spaces at the end). Cursor is in+`OWN_MODEL_CATALOGUE` with grok: it never receives the gateway's models (`modelsForAgent` returns+none, transfer targets stay flat, the gateway default model is not applied).++### Model and permission: not verified / not built++1. Superseded: cursor is resumable now and the restart menu's "Switch model" lists+ `cursor-agent models` (see "Session continuity", Models). The transfer menu stays flat.+2. `--auto-review` measured on one safe command only (`touch` auto-ran); which calls its classifier still prompts for is Cursor's server-side policy and was not mapped.+3. What cursor does with an unknown `--model` id is unmeasured.+4. `--model` in the TUI adds the id to `modelParameters` / `modelSelectionHistory` in+ `~/.cursor/cli-config.json` (seen on the real config); it did not change the saved default model.+5. A model can be rate-limited per account ("You've hit your usage limit" for `gpt-5.4-nano-none`);+ that error comes from the backend and proves the flag reached it.++## Transcript, chat view and context link++Leaf: `src/core/cursor-chat.ts`. Measured on `cursor-agent` 2026.09.23 and 2026.09.28 (macOS), against+real chats (a `-p` run with a shell turn and a write/read/grep turn, plus an older subagent chat).++**Storage.** `<config>/chats/<md5(physical cwd)>/<chatId>/store.db`, where `<config>` is+`$CURSOR_CONFIG_DIR`, else `$XDG_CONFIG_HOME/cursor`, else `~/.cursor` (the CLI's own rule).+`<chatId>` is a UUID: the `--resume` id and the stream-json `session_id` (stable across resume).+2026.09.28 also writes a `meta.json` sidecar. `--resume <id>` of an unknown id creates `store.db` at+once (meta key `0` = hex JSON with `latestRootBlobId: ""`); only a fresh TUI quit before any turn+leaves `meta.json` alone, with no `store.db`.+The store is SQLite (WAL): `meta` key `0` = hex(JSON) with `latestRootBlobId` and `name`; `blobs` is+content addressed (sha256). The root blob is protobuf (`ConversationStateStructure`): field 1 lists the+ordered ids of the model-context messages, each an AI-SDK-shaped JSON blob (system / user / assistant+parts `text`, `reasoning`, `redacted-reasoning`, `tool-call` / tool `tool-result`). The typed prompt is+`<user_query>` inside a user text part; everything else in user messages is injected context. The+root's field 5 holds `used / window` context tokens, which the meter reads ("Context meter"; verified+18335 / 200000 = the TUI footer's 9.2%).+Not used: `~/.cursor/projects/<slug>/agent-transcripts/<id>/<id>.jsonl`. Its text reads `[REDACTED]`, it+has no tool results and lost the user line of a failed turn.++**Reading.** Built-in `node:sqlite`, read-only (Electron 42 = Node 24.19; `engines` floor has it). No new+dependency. Found strictly by the whole-UUID id; the cwd only orders the bucket search. There is no cwd+fallback, so another chat is never shown. One page, `olderCursor: null`. Newest 16 MiB of messages+are read. Compaction replaces the model context, so pre-compaction turns are not shown.++| Capability | Desktop | Server Edition | Mobile | SSH-remote node |+|---|---|---|---|---|+| ⌘M chat (`CHAT_CAPABLE`) | yes | yes (core handler) | yes, via relay `chat.page` | refused: "not supported yet" (`CHAT_LOCAL_ONLY`), never the local disk |+| Context link, both directions (`CONTEXT_LINK_CAPABLE`) | yes | yes | N/A | no transcript for a remote node ("no conversation transcript yet") |+| Transfer source (`TRANSFER_SOURCE_CAPABLE`) | yes | N/A (handoff is desktop main) | N/A | refused with its own sentence |+| Session name read (`TITLE_READ_CAPABLE`) | yes | sweep to the mirror only (the IPC read is stubbed there for every agent) | via mirror | none (node keeps its title) |++`get-linked-context` discovery: cursor-agent lists `~/.claude/skills/get-linked-context` in its own+`<agent_skills>` (measured). Since the consent change (#744) each agent gets the skills in its own+dir, so cursor's copy goes to `~/.cursor/skills` (below, "Canvas control"). The composer's model label, effort, plan/question+cards and `at` timestamps are not supported. `/rename` joined `RENAME_CAPABLE` later ("Orchestration parity").++## Device checklist (not verified)++1. ⌘M on a live interactive node after hooks supply the chat id (this leaf assumes the node's session id is it).+2. A chat with a very long history (compaction) and one over 16 MiB.+3. Title chip after cursor auto-names an interactive chat (print mode leaves `New Agent`).+4. Server Edition on Linux and Windows path hashing of the cwd bucket (only the id scan is relied on).++## Context meter (`USAGE_CAPABLE`)++Source: the agent's OWN numbers (CLAUDE.md rule 6), not the `stop` payload's `input_tokens` /+`cache_read_tokens` (no window there). The store's root protobuf field 5 is `token_details` {1+used_tokens, 2 max_tokens}; it matches the TUI's `/context`, and `max` varies per session (200000 /+256000 / 300000 / 1000000), so it is read, never inferred. No `max`, no meter. Read by the one store+reader (`readCursorStore` returns `tokens`; `rootMessageIds` and `rootTokenDetails` share one protobuf+walker in `core/cursor-chat.ts`). No second SQLite reader.++**Tail choice.** `createContextTail` gained one option, `readSource(path, lastKey)`, replacing the+byte read for a source that is not a text file. Cursor's is `readCursorContextSource`: stat of+`store.db` + `store.db-wal` as the change key (WAL leaves the db file untouched between checkpoints),+then the store read for the numbers only, handed to `cursorContextParse` as one JSON line. The shared+1 Hz poll does the re-reading; cursor hook events (`trackCursorContext`) only locate and track the+store, strictly by `conversation_id` (`locateCursorChat`, chats root only, whole-UUID). note: a+poll, not a hook-triggered reader; upgrade if the stat gate ever shows up in a profile.++**Jail.** No payload path is consumed: `transcript_path` names the redacted agent-transcripts jsonl and+is ignored, so there is nothing to widen in `safeTranscriptPath`; the only path is the one the locator+builds under `cursorConfigDir()` (honours `CURSOR_CONFIG_DIR` / `XDG_CONFIG_HOME`).++**Gates.** `hasUsage` also gates `context.ensure` (now a `cursor` case: `locateCursorChat(id)`, no cwd)+and the find-bar index and cold-resume stay on `readsClaudeTranscript`, which is false for cursor (pinned).++| Surface | Status |+|---|---|+| Desktop | yes: raw listener `agentId === 'cursor'` in `src/main/index.ts`; ensure routes to `cursorContextTail` |+| Server Edition | yes: same branch in `src/server/agent-status.ts` (parity), `tailFor` in `src/server/index.ts` |+| Mobile | meter rides the shared context mirror (agent-agnostic); not device-verified |+| SSH node | "not yet": raw branch returns for a remote node, `ensureRemote` is terminal `unresolved`, never this machine's disk |++Plan usage is read separately, in the bottom usage pill (`src/core/usage/cursor-usage.ts`, provider+`cursor`, shown by default, Settings -> Usage toggle). Measured on cursor-agent 2026.10.01-e373342:+the CLI's own `/usage` calls `aiserver.v1.DashboardService/GetCurrentPeriodUsage` (Connect, plain+JSON POST `{}`) on `https://api2.cursor.sh` with the login's bearer token. Fields used:+`planUsage.totalPercentUsed` (else `includedSpend / limit`, the CLI's fallback), `autoPercentUsed`,+`apiPercentUsed`, and `billingCycleEnd` / `billingCycleStart` (epoch ms as strings) for the reset and+window. The credential is the CLI's: macOS login Keychain (account `cursor-user`, service+`cursor-access-token`, created by `/usr/bin/security`, so reading it with the same binary raises no+prompt), else `auth.json` (`~/.cursor/` with `AGENT_CLI_CREDENTIAL_STORE=file`, `$XDG_CONFIG_HOME/cursor/`+on Linux, `%APPDATA%/Cursor/` on Windows). Read only, never refreshed; the token stays in process+(only the service name is on argv). Not signed in, an expired token (401/403) or a reply over 256 KB+(read stops there, never parsed) = no row; network or+5xx = error status keeping the last good numbers of the same login for up to an hour. Not shown:+dollar spend, bonus credit, on-demand (spend limit) usage, the plan name, and enterprise accounts with+no `planUsage`. SSH hosts: local login only, no remote leg. Model is not shown in the context meter+(the store root states none cheaply; the popover omits it).+Verified live on the dev app: the header showed 90% left against the TUI footer's 10.1% used.+Unverified: a real store read in this branch's tests (fixtures are synthesized), Mobile on device.++## Session continuity (resume, mint, session end, restart, models)++Measured on `cursor-agent` 2026.09.28 (macOS, tmux TUI, project-level hooks logger). One paid run+(composer-2.5), the rest zero cost.++**Grammar.** `--resume [chatId]` is a ROOT option with an OPTIONAL value: the id must directly follow+it, then `agent '<prompt>'` may follow. Resume is `cursor-agent --resume <id> [--mode/--force] [--model X]`+(no prompt); flags may sit either side of the id. Both composers (`resumeCommandWith` ->+`assembleResumeCommand`, and `core/agent-launch.ts` argv) emit it; pinned in `cursor-launch.test.ts`+and `agent-launch.test.ts`.++**Dead id is safe.** `--resume <unknown uuid>` opens an empty chat that ADOPTS that id (exit 0, no+error; a `chats/<bucket>/<id>/` dir appears). So a wrong id costs the history, never the launch.++**Minting (`SESSION_ID_CAPABLE`, unconditional like copilot).** Because an unknown id is adopted, a+fresh UUID on first launch IS minting, with no model call: `cursor-agent --resume <uuid> [flags] agent+'<prompt>'`. Paid run: that exact line answered "pong" and `stop` carried `conversation_id` == the uuid.+`create-chat` (1.5 s, network) is NOT used: it returns a cursor-chosen id, and nodeterm needs the id+before launch. No help probe: the flag is the one resume already needs, and the adopt behavior is not a+flag a probe could see. An id that already exists just resumes (never grok's "taken id" launch error).+If an older CLI ignored the unknown id, the node degrades to the hook-learned id.++**Session end (`SESSION_END_CAPABLE`).** `/quit` + Enter fires `sessionEnd` (also with a resumed+chat). `normalizeCursor` maps it to `sessionPhase: 'end'` (skipped when `is_background_agent`), AND+`sessionEnd` is added to `CURSOR_HOOK_EVENTS`: the list is inert, and every quit would read as a+DROPPED crash, without the subscription. Existing installs gain it on the next installer pass.++**In-place restart.** `EXIT_SEQUENCES.cursor = '/quit'` (bare). Enter is a SEPARATE write (150 ms+split, as opencode): text+Enter in one write is not submitted. Ctrl-U (`KILL_LINE`) clears a half-typed+draft in the cursor TUI (measured). The `/quit` also waits `EXIT_KEY_GAP_MS` (150 ms) after the+Ctrl-U: measured on 2026.10.01 in a private tmux, Ctrl-U+`/quit` in one burst then Enter 150 ms later+left the CLI running 10 of 10 (the `/quit` was dropped, composer empty); Ctrl-U, 150 ms, `/quit`,+150 ms, Enter returned to the shell 10 of 10. Applies to every `submitsSeparately` agent. The restart rejects `working` and+`blocked` (the approval watch reports Cursor's approval prompt as `blocked`, see "NEEDS YOU").++**Relaunch clears the exit.** Our own `/quit` fires `sessionEnd`, which records `sessionEnded`, and+`--resume` fires no `sessionStart`. So once nodeterm delivers its own resume line (in-place restart,+Pause/Eco wake, and the cold-restore relaunch a model switch recycles into), the node withdraws+`sessionEnded` itself (`performResumePhase`'s `onResumed`, and the cold-restore delivery in+`TerminalNode.tsx`). Without it the chat composer and the phone refused the running CLI as+"exited" until its next turn.++**Models.** `cursorModelsFrom` parses `cursor-agent models` (`<id> - <label>`, zero-width spaces+stripped; 246 of 246 lines matched, header and Tip ignored) into `{id, name}`. Probe: `core/cursor-cli.ts`+(`registerCursorCliIpc`, in BOTH shells), memoized, a failed/empty probe is retried, fails open to [].+Channel mirrors grok's: `IPC.cursorCliCaps`, `window.nodeTerminal.cursor.cliCaps()` (preload, ws-bridge,+stub), renderer memo `ensureCursorCliCaps`/`cursorCliCapsNow` warmed at boot, and `modelsForAgent(...,+cursorModels)` fed by Canvas. This lights the restart menu's "Switch model" for cursor.++**Cold-resume presence: not built.** `transcriptExists`/`shouldProbeTranscript` is claude-only and has+no agent argument on its channel; the store locator (`locateCursorChat`, strictly by id) could answer,+but the dead-id behavior makes it unnecessary: a missing chat resumes into an empty chat under the same+id instead of failing like claude. The only loss is the "lost session" notice.++| Capability | Desktop | Server Edition | Mobile | SSH-remote node |+|---|---|---|---|---|+| Resume / cold restore / restart / mint | yes | yes (core + shared composer) | N/A | hooks via `installCursorRemote` give the id; mint also gives one; remote run unverified |+| Session end (DROPPED chip) | yes | yes (normalizer is shared) | status mirror | hooks via `installCursorRemote`; remote `sessionEnd` unverified |+| Model catalogue | yes (IPC) | yes (WS-RPC handler) | N/A | lists THIS machine's account |++### Not verified (device checklist)++1. `sessionEnd` on Ctrl-C twice, SIGTERM, and a closed terminal (only `/quit` measured).+2. Mint on an older cursor-agent that may not adopt an unknown id.+3. `sessionEnd` of a subagent chat (`is_background_agent` only guards the flag, never seen true).+4. `--resume <id>` after the real chat has history inside a restart, including the Switch model path.+5. Windows `cursor-agent` argv for resume (composer pinned, never run).+6. Models list under an account switch (memoized per process) and offline.++## NEEDS YOU, SSH hooks and lost stop++Measured on `cursor-agent` 2026.09.28-64d2043, interactive TUI in a private tmux, project-level+hooks logger, 4 model runs (composer-2.5).++### NEEDS YOU (`core/agents/cursor-approval.ts`)++| case | hook events | pane |+|---|---|---|+| shell off allowlist | `preToolUse` (Shell), `beforeShellExecution`, then silence | `Run this command?` / `Not in allowlist: touch` / `→ Run (once) (y)` ... `Skip & tell the agent what to do instead (esc or n)`; tool row `$ touch x Waiting for approval...` |+| MCP tool | `preToolUse` (`MCP:ping`), `beforeMCPExecution`, then silence | `Run this MCP tool?` / `→ Run (once) (y)` ... `Skip (esc or n)` |+| approve (y) or skip (n) | `postToolUse` for the same `tool_use_id` (skip too), then `stop` | dialog gone |+| file write (default mode) | no dialog: auto-approved | n/a |+| AskQuestion (measured again 2026-10-04, 6 runs) | NO tool hook on show, on answer (Enter) or on skip (Esc): after `beforeSubmitPrompt` only `afterAgentThought` (not subscribed) until the turn's `stop`, which came 20 to 55 s after the answer, status `error` in every run (the pane printed `WritableIterable is closed`) | bordered box at the bottom of the pane: a title (the model's own, e.g. `Color preference`, or the default `Clarifying Questions`) / `Question 1 of N` / `1. <question>` / `› [ ] Red` ... `[ ] Other: (type to answer)` / footer `↑/↓ option · ←/→ question · Space select · Enter next/submit · Esc to skip` (wraps onto two rows at 60 columns). Answered or skipped, it stays as a summary (`AskQuestion <title> (1)` and `[x]`/`[ ]` rows) with no footer |++Rule: a cursor `preToolUse` whose `tool_use_id` has no `postToolUse`/`postToolUseFailure` after+1.5 s gets a pane read (`ptyManager.captureSession`, bounded by `probeWithin`), retried at 4 s and+10 s (`CURSOR_APPROVAL_READS_MS`) because the dev app's first read once ran before the dialog drew. If the last 30+non-blank lines hold an exact heading from the bundle's `decision-logic.ts` (`Run this command?`,+`Run this command outside the sandbox?`, `Run this MCP tool?`, `Delete this file?`, `Write to this+file?`, `Read this file?`, `Allow this web search?`, `Allow this web fetch?`) followed by an option+ending in `(y)`, the hook server emits `blocked` on the same listener as every hook event. The next+event (`postToolUse` on y/n, `stop` on Esc) replaces it. No pending tool = no timer, no read; at most three reads+per call and one `blocked` per dialog (a second pending call reading the same dialog emits nothing), so a+long approved command never strobes. `stop`/`beforeSubmitPrompt`/`sessionEnd` drop the node's pending calls,+and closing or recycling the node releases them (`hookServer.releaseCursorNode`, both shells), so a read+still in flight cannot bring a deleted node back as `blocked`. A node has at most ONE capture in flight,+across turns, release and a replacement session: a read due while one is outstanding is skipped (never+handed that read's snapshot, which may be another turn's) and its next slot reads fresh. An empty or+timed-out read stops the node's reads until the next turn edge: retrying an unreadable pane stacks ssh+children (`pane-probe.ts`). Only a parent event names the node's session: any event with+`generation_id === conversation_id` is a child's and never lends its id to a synthetic event.+No subagent `sessionEnd` was seen in any capture (three subagent runs plus the reviewers'); the+parent's own `sessionEnd` also has `generation_id === conversation_id`, so the two could not be told+apart by that field if a child one ever appeared (unverified).++**Subagent calls** (`isCursorChildToolEvent`: `generation_id === conversation_id`) are watched too.+Measured on 2026.10.01 (private tmux, a Task/explore child running `find . -name '*.txt' | sed … |+sort`): the child's `preToolUse` Shell drew `Run this command?` / `Not in allowlist: find, sed, sort` /+`→ Run (once) (y)` on the PARENT pane while the parent turn was still working. The watch emits `blocked`+1.5 s later with the PARENT's chat id (remembered from the node's parent events; omitted if none was+seen yet), never the child's, which would replace the node's resume id. normalizeCursor drops child+events, so the child's `postToolUse` (measured for `y`, and for `n` + an empty "tell the agent" line)+makes the watch emit `working` itself. The parent's `Task` call is not watched: it never gets a+`postToolUse`, and watched it caught the child's dialog first and emitted a duplicate `blocked`+(measured before the fix).++**Plan mode.** Measured (`--mode plan`): the turn ends with `stop` status `completed`, then the pane+shows `Ready to build?` / `→ 1. Yes, build locally (b)` / `2. Yes, build in cloud (c)` / `3. No, propose+changes (p or Esc)`. A parent `stop` with status `completed` therefore arms the same three reads, and+`Ready to build?` followed only by option rows ending in a `(key)` hint and the box border (it must be+the bottom of the pane) emits `blocked`, as claude's ExitPlanMode is. Strict on purpose: the answered+box stays in the transcript, and the build's own `stop` read it 30 lines up (measured). `b` fires no+`beforeSubmitPrompt`; the build's first parent `preToolUse` ends the block (a `Task` normalizes to+`subagent-start`, not `working`, so the watch emits `working` itself) and cancels the reads. Cost:+up to three pane reads after every completed turn, plan mode or not.++**AskQuestion.** The box has no hook (table above), so the watch hangs the same bounded reads on a+quiet stretch of a working turn: `beforeSubmitPrompt` and every tool post (a child's too, since the+parent's `Task` never posts and the parent may ask once its child is done) arm them, a `preToolUse`+cancels them (a tool is running), `stop`/`sessionEnd`/release drop them. `cursorQuestionIn` matches+the box by structure, not by title (the title is the model's): the footer ending `Esc to skip` must be+the last row above the bottom border, with a `Question N of M` row and an option row (`› [ ] ...`,+`[x] ...`) above it, so the answered summary left in the transcript never matches (measured: the next+turn's first read saw it and did not). A match emits `waiting`, what Claude's AskUserQuestion+normalizes to (NEEDS YOU, a question card on the phone, chat send and agent messaging refused). The+next parent tool event replaces it (`working`; the watch emits it itself before a `Task`) and so does+`stop` (`done`, `errored` for the measured `error` status). Live replay (real hook log, real tmux+pane, `createCursorApprovalWatch`): the 1.5 s read missed the box both times and the 4 s read caught+it. Cost: up to three pane reads per quiet stretch of 1.5 s or more, on any turn.++| Surface | Desktop | Server Edition | Mobile | SSH-remote node |+|---|---|---|---|---|+| NEEDS YOU on approval and on the AskQuestion box | yes (`hookServer.setPaneReader` in main) | yes (same call in server) | yes (mirror is agent-agnostic) | yes: `captureSession` reads the remote tmux over the ControlMaster (one ssh child per read) |+| Kanban card, chips, card modal | `cardBadge` / `chatSendRefusal` read `blocked` for every agent | same | N/A | same |+| Chat send / agent messaging refuse while blocked | `chatSendRefusal` = `dialog`; `decideDelivery` = `targetBusy` | same | same | same |++Limits: an AskQuestion box first drawn more than 10 s after the last hook event (the last read of+the stretch) keeps the node on RUNNING; after the answer the node stays NEEDS YOU until the turn's+next hook, measured 20 to 55 s later (`stop`), because nothing marks the answer itself. The+headings other than shell and MCP are bundle-read, not seen in a pane. Unmeasured: `p`/Esc on the plan+prompt (no hook expected; the node stays NEEDS YOU until the next prompt's `beforeSubmitPrompt`).++### SSH hook installer (`RemoteHooks.installCursorRemote`)++`cursor` left `LOCAL_ONLY_HOOK_AGENTS`, so `--after` accepts a cursor node on an SSH project. On+connect, only where the host has `cursor-agent` (`command -v`, or `~/.local/bin/cursor-agent`, which a+non-login ssh shell often lacks): write `~/.nodeterm/agent-hooks/cursor.sh` (stdin), then merge into+the host's `~/.cursor/hooks.json` with the local installer's pure `applyCursorHooks` through+`updateRemoteSettingsFile` (content over stdin, lock dir, other tools' entries kept, an unparseable+file left byte-for-byte, a second run writes nothing). A command holding `//` is refused before+anything runs. Tested under a real `/bin/sh` against a fake host tree+(`remote-cursor-hooks.test.ts`). It runs only when the host's consent plan installs `cursor`; a plan+that removes it strips our entries from the host's `~/.cursor/hooks.json` (`stripRemoteSettingsFile`,+never creating the file) and deletes `cursor.sh`. Its skills go to `~/.agents/skills`, a root the+bundle loads (unverified on a host).++### Lost stop++A mid-turn network reconnect dropped `stop` (measured, wave 1). No new timer: the mirror's+`sweepStaleWorking` (core) and the renderer's `sweepStaleWorking` both match `state === 'working'` for+any agent, so a cursor node with a lost `stop` turns `done` after `WORKING_STALE_MS` (20 min) of+silence (pinned in `cursor-approval.test.ts`). `blocked` is not swept, by design (a person may take+long); its clearing event is the `postToolUse`/`stop` of the same turn.++### Device checklist (not verified)++1. A cursor node on the real canvas: NEEDS YOU badge, chime and phone card on the shell dialog;+ back to RUNNING on y.+2. Linux host over SSH: install lands, hooks fire through the tunnel, the remote pane read matches.+3. `Run this command outside the sandbox?` (sandbox on) and the Write/Delete/Read/web dialogs:+ heading text and a `(y)` option as rendered.+4. A very long command preview pushing the heading above the 30-line window (would degrade to RUNNING).+5. Two parallel tool calls with one approval: the other call's `postToolUse` returns the badge to+ RUNNING while the dialog is still up (no re-read).+6. A cursor node on the real canvas: NEEDS YOU and a question card on the phone for the AskQuestion+ box; DONE after Esc or after the answer's `stop`.++## Orchestration parity (canvas control, subagents, rename, loop)++Measured on `cursor-agent` 2026.10.01-e373342 (it auto-updated from 2026.09.28 during the work),+macOS, in the INTERACTIVE TUI inside a private tmux server, scratch workspace with a project+`.cursor/hooks.json` logger for ten events (incl. `subagentStart`/`subagentStop`). Five model turns+(composer-2.5). Fixture: `src/shared/agents/__fixtures__/cursor/subagent-payloads.json`.++### Canvas control (`CANVAS_CONTROL_CAPABLE`)++Membership is the whole wiring, like grok: it sets `NODETERM_CANVAS_CONTROL` (`buildPtyEnv`,+`remoteHookEnvArgs`) and lets `controlRouting`/the Server factory accept a cursor source. Discovery:+asked to list its skills, cursor named `~/.claude/skills/manage-nodeterm-canvas/SKILL.md` and+`get-linked-context`. The bundle loads skill roots in this order: `~/.cursor/skills-cursor` (built-in),+`~/.cursor/skills`, `~/.claude/skills`, `~/.codex/skills`, `~/.agents/skills`, plugins; the three+third-party roots are gated by `thirdPartyExtensibility` (CLI default on; a team setting could turn+it off). Trap: cursor TRUNCATES a long skill list ("52 additional skills were omitted" here), from+the tail. `~/.claude/skills` sits third, so it survived; a user with hundreds of `~/.cursor/skills`+could push it out. Since #744 the skills are written into `~/.cursor/skills` under cursor's own+consent (`skillRootsFor`), which also keeps canvas control working when claude is declined. That+copy is not measured in a live session yet; the `~/.claude/skills` copy (when claude is enabled) is.++### Subagents (`SUBAGENT_CAPABLE`)++Three runs (two built-in `explore`, one custom `.cursor/agents` subagent), all the same:++| fact | measured |+|---|---|+| `subagentStart` / `subagentStop` | never fired, although subscribed |+| parent `Task` tool | `preToolUse` (with `tool_input.subagent_type`, `description`, `prompt`) and NO `postToolUse` |+| child tool events | `conversation_id` = `generation_id` = the CHILD's chat id; no `parent_tool_call_id`; `transcript_path` null on its first preToolUse, its own JSONL after |+| ordering | synchronous: every child event landed before the parent's `stop` |+| correlating key | none in any hook payload. The child's `store.db` meta has `subagentInfo {parentAgentId, rootParentAgentId, toolCallId, typeName}`; `toolCallId` == the parent `Task`'s `tool_use_id` |+| child transcript | `<config>/projects/<slug>/agent-transcripts/<childId>/<childId>.jsonl`, append-only, ends `{"type":"turn_ended","status":"success"}`; assistant text often `[REDACTED]` |++So: `normalizeCursor` turns the parent `Task` preToolUse into `subagent-start` (key `tool_use_id`),+and returns null for a child's tool event (`isCursorChildToolEvent`: `generation_id ===+conversation_id`). That rule also fixed a real bug: child events used to drive the parent badge AND+replace the node's recorded session id (the resume id) with the child's. The END and the live tail+live in ONE core helper both shells call (`core/cursor-subagents.ts`, `createCursorSubagentTracker`):+the parent's `stop` emits `subagent-end` for every Task opened in that turn, and a child is tailed+(`subagentTail.trackFile` + `createCursorSubagentFormatter` over its JSONL, path jailed under+`<config>/projects/`) when exactly one of the node's open Tasks is unclaimed.++Trade-offs, stated: a HEADLESS (`-p`) run has `generation_id === conversation_id` on its own tool+events (2026.09.28 capture), so they now read as a child's and drive nothing; headless runs fire no+`beforeSubmitPrompt`/`stop` either, so those events only ever lit a RUNNING badge nothing cleared.+Parallel Tasks get cards but no tail (note: read the child meta's `toolCallId` to claim them). A+lost `stop` (network reconnect) leaves the cards to the shared `WORKING_STALE_MS` decay. A node+closed or recycled mid-Task releases its entry and child tails (`tracker.release`, called from both+shells' `releaseNodeTails`). Not+subscribed: `subagentStart`/`subagentStop` (never fired; `subagentStart` is a GATING event, so a+subscription is only risk).++### Rename (`RENAME_CAPABLE`)++`/rename <name>` is a local TUI command (`agentStore.setMetadata("name")`, no model call, no hook)+and lands in the store meta `name` the read leg (`TITLE_READ_CAPABLE`) already reads, so read ⊇+write holds. MEASURED: nodeterm's one-shot `sendText` (bracketed paste and Enter in ONE tmux+invocation) left `/rename x` sitting unsubmitted in the composer; the same paste followed by a bare+Enter as a SECOND invocation renamed the chat (meta `name` changed). Hence `SEPARATE_SUBMIT_AGENTS`+(`submitsSeparately`): `PtyManager.sendText` pastes, then sends a bare Enter only after the paste+succeeded, one transaction at a time per node. Agent `send`/`reply` envelopes split the same way. The+agent comes from `create()` or, before the node mounts after a restart, the workspace records when every+placement agrees. An approval, AskQuestion or plan prompt already on screen gets nothing written (an+envelope answers `targetBusy`/`blocked`, retryable); one that opens after the paste gets no Enter (the text+stays composed: `pasted-not-submitted`, an envelope reports `stalled`). An empty capture is not a dialog.+Known limit: before mount the split trusts the records' `agentId`, so a shared project file naming+`cursor` for a pane that is not Cursor gets the split. `pushSessionRename` sends one ordinary line. The built-in `rename-chat` skill is model-driven+(`cursor-app-control.rename_chat`, not in the CLI) and is not used.++### Loop (`RECURRING_CAPABLE`): not joined++`/loop 2m <task>` read `~/.cursor/skills-cursor/loop/SKILL.md` (a `preToolUse Read`) and proposed a+Shell `while true; do sleep 120; echo 'AGENT_LOOP_TICK_<purpose> {...}'; done` (a `preToolUse+Shell`), which stopped at the allowlist prompt and was declined. So the SETUP has a signal (the+sentinel `AGENT_LOOP_TICK_` / `AGENT_LOOP_WAKE_` in a Shell command), but a tick, its turn shape+and the loop's end were never measured. A card counting turns it never saw would be a guess.++| Capability | Desktop | Server Edition | Mobile | SSH-remote node |+|---|---|---|---|---|+| Canvas control | yes | yes when its canvas control is enabled | N/A | same skill on the host via `installCanvasControl`; unverified for cursor |+| Subagent cards + tail | yes | yes (same tracker, `src/server/agent-status.ts`) | N/A (cards are renderer-only) | cards from `installCursorRemote` hooks; no live tail (child store is on the host) |+| Rename push | yes | yes (same renderer path, `sendText` over the bridge) | N/A | `sendText` over the ControlMaster; title READ is local only, so the chip will not confirm |++### Device checklist (not verified)++1. Does the FIRST turn of a node launched as `cursor-agent agent '<prompt>'` carry `generation_id+ !== conversation_id`? If it equals (like `sessionStart`), that turn's tool events and a `Task`+ in it are dropped (badge still from `beforeSubmitPrompt`/`stop`).+2. A backgrounded subagent (`SubagentRunState.backgrounded` exists in the bundle): its card ends at+ the parent's `stop` while it still runs.+3. Parallel Tasks in one turn (cards expected, no tail).+4. Rename while a turn runs, and rename when the composer still holds text: in this capture the+ composer KEPT a long prompt typed with `send-keys -l` after it was submitted, and the next typed+ line was appended to it. Whether nodeterm's paste path leaves the composer empty is unmeasured+ (the rename test cleared it first).+5. Canvas control end to end in a real cursor node (`nodeterm.sh list` from the agent).diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.mdindex 68d39c2c7..bcd361a5a 100644--- a/docs/mobile-chat-view.md+++ b/docs/mobile-chat-view.md@@ -103,7 +103,7 @@ as `hostBridge.chat` in `main/index.ts`, forwarded by both phone hosts).| verb | params | reply | does ||---|---|---|---|-| `chat.page` | `{nodeId, before?, maxBytes?}` | `{page: ChatPage}` | Only for agents with a chat view — `canChat(capabilityAgentId(agent))` (claude, grok, gemini, codex, copilot, opencode, and custom agents whose base harness is one of them; codex is read by its own reader, `src/core/codex-chat.ts`, locally and on an SSH host — fixtures and the record rules in `src/shared/chat-fixtures/codex/`); anything else is refused before any read. `readChatTranscript` with the ⌘M panel's own deps (paged ALWAYS — an absent page is the default 256 KB tail; grok unpaged) + `model`/`effort`, `version: 1`. Session id: the RENDERER's agent-status id first (what ⌘M reads — after a desktop restart a hook-fed id lives only there), then the mirror's, then the node's minted id; the fallbacks apply only when the renderer does not answer within 3 s or knows none. **Remote (SSH-project) nodes are read REMOTE-ONLY** (`remoteOnly`): over the live pty's ControlMaster, else the node's PROJECT's master (an idle tab / any node after a restart has no pty), and never from this machine's disk — a remote node with no reachable master, or a host that did not answer, is `Could not read the transcript.`, not an empty page. The host-side locate is TRI-STATE (`locateRemoteTranscriptRef`, `src/main/remote-transcript-page.ts`): a CLEAN MISS (the host looked and has no such file, or there is no session id to look for) is `found:false`, and only a failure to ask (no master, no resolved home, a failed ssh, a path outside the jail, a failed ranged read) is the error. For REMOTE nodes the desktop ⌘M panel follows the same remote-only rule and the same absent-vs-unreadable split (same deps): its IPC handler decides remoteness from the shell's own records (`isRemoteNode` — live remote pty or `workspaceStore.sshProjectIdForNode`, never a renderer flag) and applies `remoteOnly` to the paged read, the legacy unpaged read, the find-bar index and the presence probe (`unknown`); it shows `unreadable` as "Couldn't read the transcript." (a remote grok node is read on its host too — `core/remote-grok-chat.ts`, whole-file and unpaged, with the same absent-vs-unreadable split; a remote node of an agent with no remote reader — `CHAT_LOCAL_ONLY` — as "not supported yet"). LOCAL nodes on ⌘M are unchanged — the renderer still sends the cwd, so claude's cwd fallback still applies there; the cwd-only-when-remote rule below is the phone path's. The cwd rides ONLY for a remote node with a known id (the host-side locate needs it); locally a known-but-dead id must not fall back to the cwd's newest transcript (another node's), and with no id at all ⇒ `found:false`. `found:false` therefore always means "looked, and there is no transcript". The reply's `page.sessionId` is exactly the id that read used (absent when none was resolved); the phone should PREFER it over the mirror's `sessionId` as the page's thread identity — the mirror lags — every 4 s on SSH, up to ~30 s on relay (`projects.list` off-LAN) — so right after `/clear` or a resume it still names the old session while the page already comes from the new transcript, and merging by byte `key` across the two would splice threads. `sessionId` is present on a `found:false` page too (an id was resolved, its transcript is missing — e.g. a fresh session that has not written yet): a new id on such a page alone is NOT a confirmed thread switch, so the phone must not clear the thread on it. Additive field: `version` stays 1, and an older desktop simply omits it (fall back to the mirror). |+| `chat.page` | `{nodeId, before?, maxBytes?}` | `{page: ChatPage}` | Only for agents with a chat view — `canChat(capabilityAgentId(agent))` (claude, grok, gemini, codex, copilot, opencode, cursor (its SQLite chat store, `src/core/cursor-chat.ts`; local only), and custom agents whose base harness is one of them; codex is read by its own reader, `src/core/codex-chat.ts`, locally and on an SSH host — fixtures and the record rules in `src/shared/chat-fixtures/codex/`); anything else is refused before any read. `readChatTranscript` with the ⌘M panel's own deps (paged ALWAYS — an absent page is the default 256 KB tail; grok unpaged) + `model`/`effort`, `version: 1`. Session id: the RENDERER's agent-status id first (what ⌘M reads — after a desktop restart a hook-fed id lives only there), then the mirror's, then the node's minted id; the fallbacks apply only when the renderer does not answer within 3 s or knows none. **Remote (SSH-project) nodes are read REMOTE-ONLY** (`remoteOnly`): over the live pty's ControlMaster, else the node's PROJECT's master (an idle tab / any node after a restart has no pty), and never from this machine's disk — a remote node with no reachable master, or a host that did not answer, is `Could not read the transcript.`, not an empty page. The host-side locate is TRI-STATE (`locateRemoteTranscriptRef`, `src/main/remote-transcript-page.ts`): a CLEAN MISS (the host looked and has no such file, or there is no session id to look for) is `found:false`, and only a failure to ask (no master, no resolved home, a failed ssh, a path outside the jail, a failed ranged read) is the error. For REMOTE nodes the desktop ⌘M panel follows the same remote-only rule and the same absent-vs-unreadable split (same deps): its IPC handler decides remoteness from the shell's own records (`isRemoteNode` — live remote pty or `workspaceStore.sshProjectIdForNode`, never a renderer flag) and applies `remoteOnly` to the paged read, the legacy unpaged read, the find-bar index and the presence probe (`unknown`); it shows `unreadable` as "Couldn't read the transcript." (a remote grok node is read on its host too — `core/remote-grok-chat.ts`, whole-file and unpaged, with the same absent-vs-unreadable split; a remote node of an agent with no remote reader — `CHAT_LOCAL_ONLY` — as "not supported yet"). LOCAL nodes on ⌘M are unchanged — the renderer still sends the cwd, so claude's cwd fallback still applies there; the cwd-only-when-remote rule below is the phone path's. The cwd rides ONLY for a remote node with a known id (the host-side locate needs it); locally a known-but-dead id must not fall back to the cwd's newest transcript (another node's), and with no id at all ⇒ `found:false`. `found:false` therefore always means "looked, and there is no transcript". The reply's `page.sessionId` is exactly the id that read used (absent when none was resolved); the phone should PREFER it over the mirror's `sessionId` as the page's thread identity — the mirror lags — every 4 s on SSH, up to ~30 s on relay (`projects.list` off-LAN) — so right after `/clear` or a resume it still names the old session while the page already comes from the new transcript, and merging by byte `key` across the two would splice threads. `sessionId` is present on a `found:false` page too (an id was resolved, its transcript is missing — e.g. a fresh session that has not written yet): a new id on such a page alone is NOT a confirmed thread switch, so the phone must not clear the thread on it. Additive field: `version` stays 1, and an older desktop simply omits it (fall back to the mirror). || `chat.status` | `{nodeId}` | `{status: ChatStatus}` | the renderer's agent-status entry (`state` null = unknown, `held`, hibernated/paused/dropped/sessionEnded) + `structuredAnswers` = the held ticket is in main's structured-ticket ledger (script revision ≥ 5) + the host mirror's `hostRefuses`/`refusal` + `version: 1`. With `{nodeId, catalog: true}` (a literal `true`; opt-in, so an older phone sees the old shape) the status also carries `catalog: ChatCatalog` (`src/shared/chat-catalog.ts`) — the composer's `/` list for the node: measured built-ins, custom commands and skills, read on the node's host for an SSH node. Absent when the host could not build it (never an error on the status). Names pass `catalogName`, descriptions are one sanitized line; render them as text. `partial: true` = a root could not be read. The host waits at most 4 s for it (an SSH node's catalog is an ssh round trip) and then answers WITHOUT it — so a client asks with `catalog: true` ONCE per composer open (and again only when the user opens the menu after a while), never on every status poll. An entry with `interactive: true` is a built-in that opens a dialog in the agent's TUI: a client that cannot show the terminal after sending it must not offer it (the dialog would be invisible and the next send would answer it). Adopting it in nodeterm mobile is an iOS follow-up. || `chat.send` | `{nodeId, text}` | `ChatSendOutcome` = `{result, reason?}` | text capped at 64000 UTF-16 units RAW, then ESC + C0/C1 stripped (`\n`, `\t` kept; `sanitizeChatText`); refused FIRST (`reason` `working`/`dialog`) when the host's mirror says the agent is working / waiting / blocked or holds a question or approval ticket (renderer state is transient after a reload); refused `busy` while another send to the same node is still in flight (held until that send SETTLES, capped at 30 s); then the renderer runs the ⌘M composer's gate at send time (`chatSendRefusal` = `agentProcessInPane` + state ∈ {done, unknown} → its own kind as `reason`) plus "no held request" (`dialog`), then `pty.sendText`. `'sent'` only for `sendText === true`; a paste the pane refused is `refused`/`failed`. || `agent.answer` | `{nodeId, pendingId, answer}` | `{ok: boolean}` | `answerHeldPermission` with the node's own I/O (local fs, or the SSH project's ControlMaster — the same `heldPermissionIoFor` the desktop answer path uses): validated against the pending request file, structured-ticket gated, no `setMode auto`. The `pendingId` must belong to THIS node — one of the mirror's approval tickets for it, or the renderer's `held.pendingId` (plans / questions) — else `{ok:false}` with no I/O and no answered event. Success emits the same optimistic "answered" event. |diff --git a/src/core/agent-integrations.test.ts b/src/core/agent-integrations.test.tsindex 4f901d754..735a12c58 100644--- a/src/core/agent-integrations.test.ts+++ b/src/core/agent-integrations.test.ts@@ -4,7 +4,7 @@// did not enable, a decline removes exactly what nodeterm wrote (a file they edited is kept and// reported), and every agent that has canvas control / context link still discovers them.import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'import os from 'os'import path from 'path'import { initPlatform, resetPlatformForTests } from './platform'@@ -242,6 +242,37 @@ describe('decline: remove exactly what we wrote', () => {expect(existsSync(path.join(home, '.codex', 'skills', CANVAS_SKILL, 'SKILL.md'))).toBe(true)})+ // cursor-agent loads `~/.cursor/skills` ahead of `~/.claude/skills`, so its skills follow ITS consent,+ // not claude's. Its hooks.json is shared with the Cursor IDE: a decline strips only our entries.+ it.skipIf(process.platform === 'win32')('cursor: hook and skills in ~/.cursor under its own consent; a decline removes only ours', () => {+ const bin = path.join(home, '.local', 'bin', 'cursor-agent')+ put(bin, '#!/bin/sh\n')+ chmodSync(bin, 0o755)+ let settings = withAgents({ cursor: 'enabled' })+ const { lc } = lifecycle(() => settings, { realHooks: true })+ lc.reconcile()+ const hooksJson = path.join(home, '.cursor', 'hooks.json')+ const skills = path.join(home, '.cursor', 'skills')+ expect(read(hooksJson)).toContain('agent-hooks/cursor.sh')+ expect(read(path.join(skills, CANVAS_SKILL, 'SKILL.md'))).toBe(buildCanvasSkillBody(SHIMS().canvas))+ expect(read(path.join(skills, CONTEXT_SKILL, 'SKILL.md'))).toBe(buildContextLinkSkillBody(SHIMS().context))+ expect(existsSync(path.join(home, '.nodeterm', 'agent-hooks', 'cursor.sh'))).toBe(true)+ expect(existsSync(path.join(home, '.claude'))).toBe(false)+ // The IDE (or another tool) adds its own hook beside ours.+ const cfg = JSON.parse(read(hooksJson)) as { hooks: Record<string, { command: string }[]> }+ cfg.hooks.stop.push({ command: 'ide-hook' })+ writeFileSync(hooksJson, JSON.stringify(cfg))++ settings = withAgents({ cursor: 'declined' })+ lc.onSettingsChanged(settings)+ const after = read(hooksJson)+ expect(after).not.toContain('agent-hooks/cursor.sh')+ expect(after).toContain('ide-hook')+ expect(existsSync(path.join(skills, CANVAS_SKILL))).toBe(false)+ expect(existsSync(path.join(skills, CONTEXT_SKILL))).toBe(false)+ expect(existsSync(path.join(home, '.nodeterm', 'agent-hooks', 'cursor.sh'))).toBe(false)+ })+it('never overwrites a skill the user edited while still enabled', () => {const { lc } = lifecycle(() => withAgents({ gemini: 'enabled' }))lc.reconcile()diff --git a/src/core/agent-integrations.ts b/src/core/agent-integrations.tsindex a0b3aaf7e..057463371 100644--- a/src/core/agent-integrations.ts+++ b/src/core/agent-integrations.ts@@ -197,6 +197,11 @@ export function skillRootsFor(return [path.join(copilotHomeDir(), 'skills')]case 'opencode':return [path.join(opencodeConfigDir(), 'skills')]+ // cursor-agent's bundle loads `~/.cursor/skills` before `~/.claude/skills` (docs/cursor-agent.md),+ // so its own dir keeps canvas control working when claude is declined, and ahead of the tail+ // its long-skill-list truncation drops.+ case 'cursor':+ return [path.join(home, '.cursor', 'skills')]default:return []}@@ -245,7 +250,8 @@ const HOOK_SCRIPTS: Partial<Record<IntegrationAgentId, string[]>> = {gemini: ['gemini.sh', 'gemini-hook.cmd'],grok: ['grok.sh', 'grok-hook.cmd'],copilot: ['copilot.sh', 'copilot-hook.cmd'],- antigravity: ['antigravity.sh', 'antigravity-hook.cmd']+ antigravity: ['antigravity.sh', 'antigravity-hook.cmd'],+ cursor: ['cursor.sh']}export interface IntegrationLifecycle {diff --git a/src/core/agent-launch.test.ts b/src/core/agent-launch.test.tsindex 0afecc234..565b23027 100644--- a/src/core/agent-launch.test.ts+++ b/src/core/agent-launch.test.ts@@ -155,6 +155,53 @@ describe("prepareAgentLaunch logical argv", () => {});});+ it("puts Cursor's flags before its `agent` subcommand, not after the prompt", async () => {+ await expect(+ prepareAgentLaunch(+ start("cursor", { prompt: "hi", permissionMode: "bypassPermissions" }),+ "posix",+ builtinContext("cursor"),+ ),+ ).resolves.toEqual({ command: "'cursor-agent' '--force' 'agent' 'hi'" });+ await expect(+ prepareAgentLaunch(+ start("cursor", { prompt: "hi", permissionMode: "plan" }),+ "posix",+ builtinContext("cursor"),+ ),+ ).resolves.toEqual({ command: "'cursor-agent' '--mode' 'plan' 'agent' 'hi'" });+ // The default mode emits nothing, so an untouched node's line is byte-identical to before.+ await expect(+ prepareAgentLaunch(+ start("cursor", { prompt: "hi", permissionMode: "auto" }),+ "posix",+ builtinContext("cursor"),+ ),+ ).resolves.toEqual({ command: "'cursor-agent' '--auto-review' 'agent' 'hi'" });+ });++ it("resumes and mints Cursor with `--resume <id>` before the `agent` subcommand", async () => {+ const id = "550e8400-e29b-41d4-a716-446655440000";+ await expect(+ prepareAgentLaunch(+ resume("cursor", id, { permissionMode: "plan" }),+ "posix",+ builtinContext("cursor"),+ ),+ ).resolves.toEqual({+ command: `'cursor-agent' '--resume' '${id}' '--mode' 'plan'`,+ });+ await expect(+ prepareAgentLaunch(+ start("cursor", { prompt: "hi", newSessionId: id }),+ "posix",+ builtinContext("cursor"),+ ),+ ).resolves.toEqual({+ command: `'cursor-agent' '--resume' '${id}' 'agent' 'hi'`,+ });+ });+it("uses flag-prompt for OpenCode and preserves a trailing slash", async () => {await expect(prepareAgentLaunch(diff --git a/src/core/agent-launch.ts b/src/core/agent-launch.tsindex c24685959..19b63b6bd 100644--- a/src/core/agent-launch.ts+++ b/src/core/agent-launch.ts@@ -399,9 +399,12 @@ function logicalLaunch(const sessionArgs: string[] = [];if (intent.newSessionId !== undefined) {if (!mintsSessionId(config.id)) fail("invalid-intent");- // `withSessionId`'s grammar: copilot's verified contract is `--session-id=<uuid>` (1.0.80).+ // `withSessionId`'s grammar: copilot's verified contract is `--session-id=<uuid>` (1.0.80);+ // cursor mints by resuming an id that does not exist yet (see withSessionId in shared/agents/launch).if (config.id === "copilot")sessionArgs.push(`--session-id=${intent.newSessionId}`);+ else if (config.id === "cursor")+ sessionArgs.push("--resume", intent.newSessionId);else sessionArgs.push("--session-id", intent.newSessionId);}diff --git a/src/core/agent-session-name.test.ts b/src/core/agent-session-name.test.tsindex 35805b5be..b75380e9f 100644--- a/src/core/agent-session-name.test.ts+++ b/src/core/agent-session-name.test.ts@@ -6,6 +6,7 @@ import { tmpdir } from 'os'import path from 'path'import { readAgentSessionName } from './agent-session-name'import { rememberGrokSessionDir, forgetGrokSession } from './grok-session'+import { setCustomAgentBaseResolver } from '../shared/agents/config'const root = mkdtempSync(path.join(tmpdir(), 'agent-session-name-'))afterAll(() => rmSync(root, { recursive: true, force: true }))@@ -86,6 +87,33 @@ describe('readAgentSessionName', () => {delete process.env.CODEX_HOME})+ it("routes cursor to its chat store's reader: null for an unknown id, never claude's scan", async () => {+ process.env.CURSOR_CONFIG_DIR = path.join(root, 'no-such-cursor-dir')+ expect(await readAgentSessionName('66666666-e4c7-4f28-9d99-027f84c10837', undefined, 'cursor')).toBeNull()+ delete process.env.CURSOR_CONFIG_DIR+ })++ it('routes a custom agent built on cursor to the cursor store, not claude\'s reader', async () => {+ const { DatabaseSync } = await import('node:sqlite')+ const cfg = path.join(root, 'cursor-cfg')+ const id = '77777777-e4c7-4f28-9d99-027f84c10837'+ const d = path.join(cfg, 'chats', 'b', id)+ mkdirSync(d, { recursive: true })+ const db = new DatabaseSync(path.join(d, 'store.db'))+ db.exec('CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB); CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT);')+ db.prepare("INSERT INTO meta (key, value) VALUES ('0', ?)").run(Buffer.from(JSON.stringify({ name: 'Cursor named it' })).toString('hex'))+ db.close()+ process.env.CURSOR_CONFIG_DIR = cfg+ setCustomAgentBaseResolver((a) => (a === 'my-cursor' ? 'cursor' : undefined))+ try {+ expect(await readAgentSessionName(id, undefined, 'cursor')).toBe('Cursor named it')+ expect(await readAgentSessionName(id, undefined, 'my-cursor')).toBe('Cursor named it')+ } finally {+ setCustomAgentBaseResolver(null)+ delete process.env.CURSOR_CONFIG_DIR+ }+ })+it('answers null for an empty session id without asking either reader', async () => {expect(await readAgentSessionName('', undefined, 'grok')).toBeNull()expect(await readAgentSessionName('')).toBeNull()diff --git a/src/core/agent-session-name.ts b/src/core/agent-session-name.tsindex 3d9264655..862c2419e 100644--- a/src/core/agent-session-name.ts+++ b/src/core/agent-session-name.ts@@ -14,12 +14,15 @@// codex → `Thread.name`, read over the shared app-server's own socket (core/codex-session-name.ts).// There is no file to read: with the shared server the name lives in the server, and the// node's session id IS the thread id.+// cursor → `name` in the chat's `store.db`, located by the id (core/cursor-chat.ts)// Anything else has no readable session name; the claude reader answers null for it, which is what// every pre-grok caller already got.import { readSessionName, readSmallTail, TITLE_TAIL_BYTES } from './transcript-reader'import { readGrokSessionName, type GrokRemoteSummaryReader } from './grok-session'import { pickGeminiTitle } from './gemini-session'import { readCodexSessionName } from './codex-session-name'+import { readCursorSessionName } from './cursor-chat'+import { capabilityAgentId } from '../shared/agents/config'/*** Per-agent associations this router cannot own itself, injected by the shell.@@ -81,10 +84,14 @@ export function readAgentSessionName(deps?: AgentSessionNameDeps): Promise<string | null> {if (!sessionId) return Promise.resolve(null)- if (agentId === 'grok') return readGrokSessionName(sessionId, deps?.grokRemoteSummary)- if (agentId === 'gemini') return readGeminiSessionName(sessionId, deps?.geminiPathFor)+ // Routed by the BASE harness, so a custom agent built on cursor reads cursor's store, not claude's.+ const base = agentId ? capabilityAgentId(agentId) : undefined+ if (base === 'grok') return readGrokSessionName(sessionId, deps?.grokRemoteSummary)+ if (base === 'gemini') return readGeminiSessionName(sessionId, deps?.geminiPathFor)// Never falls through to claude's reader: that one SCANS ~/.claude/projects on a cache miss, so// an unrouted codex node would pay that scan once a minute for a guaranteed null.- if (agentId === 'codex') return readCodexSessionName(sessionId)+ if (base === 'codex') return readCodexSessionName(sessionId)+ // cursor → the `name` in its chat store (core/cursor-chat.ts), found by id; never claude's scan.+ if (base === 'cursor') return readCursorSessionName(sessionId)return readSessionName(sessionId, accountId)}diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex 570ba3bb5..1f95fb652 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -921,7 +921,8 @@ export function toolActivity(toolName: string, toolInput: Record<string, unknowncase 'Read':out = `Reading ${basename(str(ti.file_path) || str(ti.notebook_path)) || 'file'}`break- case 'Bash': {+ case 'Bash':+ case 'Shell': { // cursor's shell tool, same `command` key (measured hook payload)const cmd = str(ti.command).replace(/\s+/g, ' ').trim()out = `Running ${cmd ? clip(cmd, 60) : 'command'}`breakdiff --git a/src/core/agents/agent-message.test.ts b/src/core/agents/agent-message.test.tsindex 0cd3e0d0d..505ab2b4a 100644--- a/src/core/agents/agent-message.test.ts+++ b/src/core/agents/agent-message.test.ts@@ -11,6 +11,7 @@ import {import { CONTROL_CEILING_MS } from './hook-server'import { MANAGED_SCRIPT_REVISION } from './hooks/managed-script'import { frameLineRe } from './agent-message-envelope'+import { RETRYABLE } from './agent-message-decide'import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'import type { MirrorEntry } from '../agent-status-mirror'@@ -253,6 +254,21 @@ describe('deliverAgentMessage — sequencing', () => {expect(traced).toEqual(['targetGone'])})+ it("a write refused by the agent's own dialog is targetBusy/blocked (retryable), not targetGone", async () => {+ const traced: string[] = []+ const r = recorder({+ sendEnvelope: async () => 'dialog',+ trace: async (t) => {+ traced.push(t.outcome)+ return { traceId: 't', traced: 'memory' }+ }+ })+ const out = await deliverAgentMessage(req(), r.deps)+ expect(out).toEqual({ kind: 'targetBusy', state: 'blocked' })+ expect(RETRYABLE[out.kind]).toBe(true)+ expect(traced).toEqual(['targetBusy'])+ })+it('EVERY refusal leaves a trace, including the ones that never reach a pane', async () => {// An agent hammering a target it may not reach is exactly the pattern an audit wants to see,// and tracing only the writes would leave it with no record anywhere.diff --git a/src/core/agents/agent-message.ts b/src/core/agents/agent-message.tsindex d165a950b..942cbad9a 100644--- a/src/core/agents/agent-message.ts+++ b/src/core/agents/agent-message.ts@@ -137,9 +137,10 @@ export interface DeliveryDeps {* must carry no ESC byte of ours, because tmux ≥ 3.7 passes paste-buffer content through vis(3),* which renders an embedded frame as literal `^[` text (issue #453). Resolves false only when* the envelope did not reach the pane; a post-paste submit failure remains eligible for the- * receipt watch's honest `stalled` outcome.+ * receipt watch's honest `stalled` outcome. `'dialog'`: nothing was written because the agent's+ * own dialog owns the keyboard (`PtyManager.sendEnvelope`, Cursor).*/- sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean>+ sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean | 'dialog'>/** The target's status mirror entry — gate 2's whole input. */mirrorEntry(nodeId: string): MirrorEntry | undefined/** `nodeTokenFilePresent(nodeId)`. */@@ -471,6 +472,12 @@ export async function deliverAgentMessage(// demonstrably landed. See `watchForReceipt`: that miss is what makes an LLM send it twice.const watch = watchForReceipt(req.targetNodeId, deps.subscribeEvents)const wrote = await deps.sendEnvelope(req.targetNodeId, payload, owner)+ // A dialog owned the keyboard and nothing was written: the pane waits on a person, which the+ // idle gate already reports as `targetBusy` / `blocked` (retryable, queued when queueing is on).+ if (wrote === 'dialog') {+ watch.cancel()+ return refuse({ kind: 'targetBusy', state: 'blocked' })+ }// The pane went away between the gate and the write. Not a failure of ours and not retryable:// the node is gone. It IS traced: a `sendEnvelope` that fails after a partial write has left// bytes in somebody's pane, and that must not be the one event with no record.diff --git a/src/core/agents/agent-messaging.ts b/src/core/agents/agent-messaging.tsindex 131e683f6..2044ca053 100644--- a/src/core/agents/agent-messaging.ts+++ b/src/core/agents/agent-messaging.ts@@ -143,7 +143,7 @@ export interface AgentMessagingDeps {/** Per-target pane-read budget; see `DeliveryDeps.paneProbeTimeoutMs`. Optional — absent keeps* the 2s default for every target, i.e. exactly the pre-existing behaviour. */paneProbeTimeoutMs?(nodeId: string): number- sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean>+ sendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean | 'dialog'>envelopePasteReady?(nodeId: string): Promise<boolean>/*** Does a session exist for this node at all — attached in this process OR held by a backenddiff --git a/src/core/agents/cursor-approval.test.ts b/src/core/agents/cursor-approval.test.tsnew file mode 100644index 000000000..07331b8f8--- /dev/null+++ b/src/core/agents/cursor-approval.test.ts@@ -0,0 +1,569 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import {+ createCursorApprovalWatch,+ cursorApprovalIn,+ cursorPlanPromptIn,+ cursorQuestionIn,+ CURSOR_APPROVAL_DELAY_MS,+ CURSOR_APPROVAL_READS_MS+} from './cursor-approval'+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'+import { _resetForTest, mirrorEntry, recordAgentEvent, sweepStaleWorking } from '../agent-status-mirror'+import { WORKING_STALE_MS } from '../../shared/agents/stale'+import { decideDelivery } from './agent-message-decide'++// Captured from cursor-agent 2026.09.28-64d2043 in tmux (capture-pane -p), blank lines dropped.+const SHELL = ` Run the shell command: touch approve-me.txt (use the shell tool, nothing else)+ $ touch approve-me.txt Waiting for approval...+────────────────────────────────────────────────────────────+ $ touch approve-me.txt in .+ Run this command?+ Not in allowlist: touch+ → Run (once) (y)+ Add Shell(touch) to allowlist? (tab)+ Run Everything (shift+tab)+ Skip & tell the agent what to do instead (esc or n)+`+const MCP = ` Call the MCP tool ping from the ntc server once. Nothing else.+ Explored available MCP tools ntc · ping+ ntc ping+────────────────────────────────────────────────────────────+ ntc: ping+ Run this MCP tool?+ → Run (once) (y)+ Allowlist MCP Tool (tab)+ Reject & propose changes (p)+ Skip (esc or n)+`+const ASK = ` ┌──────────────────────────────┐+ │ Clarifying Questions │+ │ Question 1 of 1 │+ │ 1. Red or blue? │+ │ › [ ] Red │+ │ ↑/↓ option · ←/→ question · Space select · Enter next/submit · Esc to skip │+ └──────────────────────────────┘+`+const RUNNING = ` Run the shell command: sleep 30+ $ sleep 30 5s+ → Add a follow-up+ Composer 2.5 · 11.5%+`++describe('cursorApprovalIn', () => {+ it('matches the measured shell and MCP dialogs', () => {+ expect(cursorApprovalIn(SHELL)).toBe(true)+ expect(cursorApprovalIn(MCP)).toBe(true)+ })+ it('matches a bordered heading', () => {+ expect(cursorApprovalIn(' │ Delete this file? │\n │ → Delete (y) │\n')).toBe(true)+ })+ it('refuses a running tool, the AskQuestion form, prose, and a heading with no (y) option', () => {+ expect(cursorApprovalIn(RUNNING)).toBe(false)+ expect(cursorApprovalIn(ASK)).toBe(false)+ expect(cursorApprovalIn('the model said: Run this command? (y)')).toBe(false)+ expect(cursorApprovalIn(' Run this command?\n Not in allowlist: touch\n')).toBe(false)+ expect(cursorApprovalIn('')).toBe(false)+ })+ it('ignores a dialog that scrolled out of the bottom window', () => {+ const filler = Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n')+ expect(cursorApprovalIn(`${SHELL}${filler}\n`)).toBe(false)+ })+})++describe('createCursorApprovalWatch', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ const setup = (pane: string | null = SHELL) => {+ const readPane = vi.fn(async () => pane)+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ const post = (hook_event_name: string, extra: Record<string, unknown> = {}) =>+ watch.observe('n1', { hook_event_name, conversation_id: 'c1', ...extra }, true)+ return { readPane, emitted, post }+ }++ it('a pending tool past the delay reads the pane once and goes blocked', async () => {+ const { readPane, emitted, post } = setup()+ post('preToolUse', { tool_use_id: 't1', tool_name: 'Shell' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS - 1)+ expect(readPane).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(readPane).toHaveBeenCalledWith('n1')+ expect(emitted).toEqual([+ { nodeId: 'n1', agentId: 'cursor', sessionId: 'c1', kind: 'state', state: 'blocked', verified: true }+ ])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(1) // never polls+ })++ it('a tool that posts in time gets no approval read; only the quiet stretch after it is read', async () => {+ const { readPane, emitted, post } = setup()+ post('preToolUse', { tool_use_id: 't1' })+ post('postToolUse', { tool_use_id: 't1' })+ post('preToolUse', { tool_use_id: 't2' })+ post('postToolUseFailure', { tool_use_id: 't2' })+ await vi.advanceTimersByTimeAsync(60_000)+ // The question-box reads after the last post; the shell dialog text is not a question box.+ expect(readPane).toHaveBeenCalledTimes(CURSOR_APPROVAL_READS_MS.length)+ expect(emitted).toEqual([])+ })++ it('stop and a new prompt drop every pending call of the node', async () => {+ const { readPane, post } = setup()+ post('preToolUse', { tool_use_id: 't1' })+ post('stop')+ post('preToolUse', { tool_use_id: 't2' })+ post('beforeSubmitPrompt')+ post('stop') // the question-box reads the prompt armed end with the turn+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).not.toHaveBeenCalled()+ })++ it('a long approved command (no dialog on screen) stays quiet after a bounded number of reads', async () => {+ const { readPane, emitted, post } = setup(RUNNING)+ post('preToolUse', { tool_use_id: 't1' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(CURSOR_APPROVAL_READS_MS.length)+ expect(emitted).toEqual([])+ })++ it('a dialog drawn after the first read is caught by a later one, and emitted once', async () => {+ // Measured in the dev app: the first read 1.5 s after preToolUse saw no dialog yet.+ let n = 0+ const readPane = vi.fn(async () => (++n === 1 ? RUNNING : SHELL))+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ watch.observe('n1', { hook_event_name: 'preToolUse', tool_use_id: 't1', conversation_id: 'c1' }, true)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(2)+ expect(emitted.map((e) => e.state)).toEqual(['blocked'])+ })++ it('a post that lands during the read wins', async () => {+ let release: (s: string) => void = () => {}+ const readPane = vi.fn(() => new Promise<string>((r) => (release = r)))+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ watch.observe('n1', { hook_event_name: 'preToolUse', tool_use_id: 't1' }, true)+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ watch.observe('n1', { hook_event_name: 'postToolUse', tool_use_id: 't1' }, true)+ release(SHELL)+ await vi.advanceTimersByTimeAsync(0)+ expect(emitted).toEqual([])+ })++ // A subagent's Shell dialog is drawn on the PARENT's pane (measured 2026.10.01, Task/explore+ // child: conversation_id = generation_id = child id). It goes blocked under the PARENT's id.+ it("a child tool call's dialog goes blocked with the PARENT session id, and its post clears it", async () => {+ const { readPane, emitted, post } = setup()+ post('beforeSubmitPrompt') // the parent's own event: conversation_id c1+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(emitted).toEqual([+ { nodeId: 'n1', agentId: 'cursor', sessionId: 'c1', kind: 'state', state: 'blocked', verified: true }+ ])+ post('postToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ expect(emitted.map((e) => [e.state, e.sessionId])).toEqual([['blocked', 'c1'], ['working', 'c1']])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(emitted).toHaveLength(2) // one blocked per tool id, no strobe+ })++ it("the parent's Task call is not watched; one dialog seen by two calls is ONE blocked", async () => {+ // Measured live (2026.10.01): with the Task call watched, its 4 s read caught the child's+ // dialog and emitted blocked, then the child's own read emitted it again.+ const { readPane, emitted, post } = setup()+ post('beforeSubmitPrompt')+ post('preToolUse', { tool_use_id: 'task1', tool_name: 'Task', generation_id: 'g1' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).not.toHaveBeenCalled() // the Task cancelled the prompt's question-box reads+ post('preToolUse', { tool_use_id: 'p1', tool_name: 'Shell', generation_id: 'g1' })+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted.map((e) => e.state)).toEqual(['blocked'])+ post('postToolUse', { tool_use_id: 'p1', generation_id: 'g1' }) // normalizes to working itself+ post('preToolUse', { tool_use_id: 'p2', tool_name: 'Shell', generation_id: 'g1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted.map((e) => e.state)).toEqual(['blocked', 'blocked']) // a new dialog after working+ })++ it('a child call with no dialog emits nothing, and its post emits nothing either', async () => {+ const { readPane, emitted, post } = setup(RUNNING)+ post('beforeSubmitPrompt')+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(60_000)+ post('postToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ expect(readPane).toHaveBeenCalledTimes(CURSOR_APPROVAL_READS_MS.length)+ expect(emitted).toEqual([])+ })++ it('a child dialog before any parent event omits the session id rather than using the child id', async () => {+ const { emitted, post } = setup()+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted).toHaveLength(1)+ expect('sessionId' in emitted[0]).toBe(false)+ })++ it('an unreadable pane degrades to nothing: one shared read, then the breaker stops the schedule', async () => {+ const { readPane, emitted, post } = setup(null)+ post('preToolUse', { tool_use_id: 't1' })+ post('preToolUse', { tool_use_id: 't2', parent_tool_call_id: 'p' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(emitted).toEqual([])+ // A new turn gets a fresh breaker.+ post('beforeSubmitPrompt')+ post('preToolUse', { tool_use_id: 't3' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(2)+ })++ it('a stalled reader never has more than one capture outstanding for a node', async () => {+ let outstanding = 0+ let most = 0+ const readPane = vi.fn(() => {+ outstanding+++ most = Math.max(most, outstanding)+ return new Promise<string>(() => {}) // an SSH master that never answers+ })+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ const post = (hook_event_name: string, extra: Record<string, unknown> = {}) =>+ watch.observe('n1', { hook_event_name, conversation_id: 'c1', ...extra }, true)+ post('preToolUse', { tool_use_id: 't1' })+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(60_000)+ post('stop', { status: 'completed' }) // a new turn edge while the stalled capture still hangs+ await vi.advanceTimersByTimeAsync(60_000)+ expect(most).toBe(1)+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(emitted).toEqual([])+ })++ it("a new turn's watch never takes the OLD turn's capture: its own fresh read decides", async () => {+ let resolveOld: (s: string) => void = () => {}+ let n = 0+ const readPane = vi.fn(() => (++n === 1 ? new Promise<string>((r) => (resolveOld = r)) : Promise.resolve(RUNNING)))+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e), readsMs: [100, 3000] })+ const post = (hook_event_name: string, extra: Record<string, unknown> = {}) =>+ watch.observe('n1', { hook_event_name, conversation_id: 'c1', generation_id: 'g1', ...extra }, true)+ post('preToolUse', { tool_use_id: 'old', tool_name: 'Shell' })+ await vi.advanceTimersByTimeAsync(100) // the old capture starts (it will hold the old dialog)+ post('beforeSubmitPrompt', { generation_id: 'g2' })+ post('preToolUse', { tool_use_id: 'new', tool_name: 'Shell', generation_id: 'g2' })+ await vi.advanceTimersByTimeAsync(100) // due while the old capture is in flight: skipped+ resolveOld(SHELL)+ await vi.advanceTimersByTimeAsync(5000) // its next slot reads fresh: a running command+ expect(emitted).toEqual([])+ expect(readPane).toHaveBeenCalledTimes(2)+ })++ it('a replacement session after release never starts a second capture beside a stalled one', async () => {+ let outstanding = 0+ let most = 0+ const readPane = vi.fn(() => {+ most = Math.max(most, ++outstanding)+ return new Promise<string>(() => {})+ })+ const watch = createCursorApprovalWatch({ readPane, emit: () => {}, readsMs: [25, 50, 75] })+ watch.observe('n1', { hook_event_name: 'preToolUse', tool_use_id: 'old', conversation_id: 'old-s' }, true)+ await vi.advanceTimersByTimeAsync(40)+ watch.release('n1')+ watch.observe('n1', { hook_event_name: 'preToolUse', tool_use_id: 'new', conversation_id: 'new-s' }, true)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(most).toBe(1)+ })++ it("a child's non-tool event (generation_id === conversation_id) never becomes the node's session", async () => {+ const { emitted, post } = setup()+ post('beforeSubmitPrompt', { generation_id: 'g1' })+ post('beforeShellExecution', { conversation_id: 'child-1', generation_id: 'child-1', command: 'ls' })+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted.map((e) => e.sessionId)).toEqual(['c1'])+ })++ it('release drops the timers and an in-flight read resolving afterwards emits nothing', async () => {+ let release: (s: string) => void = () => {}+ const readPane = vi.fn(() => new Promise<string>((r) => (release = r)))+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ watch.observe('n1', { hook_event_name: 'preToolUse', tool_use_id: 't1', conversation_id: 'c1' }, true)+ watch.observe('n1', { hook_event_name: 'preToolUse', tool_use_id: 't2', conversation_id: 'c1' }, true)+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(readPane).toHaveBeenCalledTimes(1)+ watch.release('n1')+ release(SHELL)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(emitted).toEqual([])+ })++ it("the parent's sessionEnd (generation_id === conversation_id) cancels an armed read", async () => {+ // Real shape (measured 2026.10.01, /quit): the parent's own sessionEnd carries its chat id as+ // generation_id too, so the child predicate must not swallow it.+ const { readPane, emitted, post } = setup()+ post('preToolUse', { tool_use_id: 't1', tool_name: 'Shell', generation_id: 'g1' })+ post('sessionEnd', { generation_id: 'c1', session_id: 'c1', reason: 'completed', is_background_agent: false })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).not.toHaveBeenCalled()+ expect(emitted).toEqual([])+ })++ // Plan mode's hand-off, captured on 2026.10.01-e373342 after a `--mode plan` turn whose `stop`+ // carried status `completed`.+ const PLAN = ` Ready to build?+ → Yes, build locally (b)+ No, propose changes (p or Esc)+`+ // Live capture (tmux, 2026.10.01): the prompt as drawn, and the same box after `b` and a build,+ // which the build's own `stop` used to read as a fresh prompt.+ const PLAN_BOX = ` │ Ready to build? │+ │ │+ │ → 1. Yes, build locally (b) │+ │ 2. Yes, build in cloud (c) │+ │ 3. No, propose changes (p or Esc) │+ │ │+ └─────────────────────────────────────────┘+`+ const AFTER_BUILD = `${PLAN_BOX} ┌─────────────────────────────────────────┐+ │ Building plan... │+ └─────────────────────────────────────────┘+ To-do All done+ ✔ Create hello.txt with content: hi+ Created hello.txt at the workspace root with the single word hi.+ → Add a follow-up+ Composer 2.5 · 11.8% · 1 file edited+`+ it('matches the measured plan prompt, and only it', () => {+ expect(cursorPlanPromptIn(PLAN_BOX)).toBe(true)+ expect(cursorPlanPromptIn(AFTER_BUILD)).toBe(false)+ expect(cursorPlanPromptIn(PLAN)).toBe(true)+ expect(cursorPlanPromptIn(' │ Ready to build? │\n │ → Yes, build locally (b) │\n')).toBe(true)+ expect(cursorPlanPromptIn(' Ready to build?\n No, propose changes (p or Esc)\n')).toBe(false)+ expect(cursorPlanPromptIn(SHELL)).toBe(false)+ expect(cursorApprovalIn(PLAN)).toBe(false)+ })++ it('a completed stop that ends on "Ready to build?" goes blocked once', async () => {+ const { readPane, emitted, post } = setup(PLAN)+ post('stop', { status: 'completed' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(emitted).toEqual([+ { nodeId: 'n1', agentId: 'cursor', sessionId: 'c1', kind: 'state', state: 'blocked', verified: true }+ ])+ })++ it('a plan block answered with a delegated build (parent Task) goes back to working', async () => {+ const { emitted, post } = setup(PLAN)+ post('stop', { status: 'completed', generation_id: 'g1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted.map((e) => e.state)).toEqual(['blocked'])+ // `b`: the build delegates. Task normalizes to subagent-start and its child's events to null.+ post('preToolUse', { tool_use_id: 'task1', tool_name: 'Task', generation_id: 'g2' })+ expect(emitted.map((e) => [e.state, e.sessionId])).toEqual([['blocked', 'c1'], ['working', 'c1']])+ })++ it('no reads without a completed stop, and a new prompt or tool call cancels the plan watch', async () => {+ const { readPane, post } = setup(PLAN)+ post('stop', { status: 'aborted' })+ post('stop', { status: 'error' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).not.toHaveBeenCalled()+ post('stop', { status: 'completed' })+ post('beforeSubmitPrompt')+ post('stop', { status: 'completed' })+ post('preToolUse', { tool_use_id: 't1' })+ post('postToolUse', { tool_use_id: 't1' })+ post('stop', { status: 'aborted' }) // ends the question-box reads the post armed+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).not.toHaveBeenCalled()+ })++ it('a completed stop on an ordinary pane reads a bounded number of times and stays done', async () => {+ const { readPane, emitted, post } = setup(RUNNING)+ post('stop', { status: 'completed' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(CURSOR_APPROVAL_READS_MS.length)+ expect(emitted).toEqual([])+ })+})++// Live captures (cursor-agent 2026.10.01-e373342, tmux capture-pane, 2026-10-04): the AskQuestion box+// as drawn, answered (Enter) and skipped (Esc), plus the hook payloads nodeterm subscribes to.+interface AskFixture {+ panes: Record<string, string[]>+ hooks: Record<string, Record<string, unknown>[]>+}+const ASK_FX = JSON.parse(+ readFileSync(join(__dirname, '../../shared/agents/__fixtures__/cursor/ask-question.json'), 'utf8')+) as AskFixture+const pane = (name: string): string => `${ASK_FX.panes[name].join('\n')}\n`+const SHOWN = pane('shownDefaultTitle')++describe('cursorQuestionIn', () => {+ it('matches the measured boxes: default title, a model title with a wrapped footer, question 2 of 2', () => {+ expect(cursorQuestionIn(SHOWN)).toBe(true)+ expect(cursorQuestionIn(pane('shownWrappedFooter'))).toBe(true)+ expect(cursorQuestionIn(pane('shownSecondOfTwoSelected'))).toBe(true)+ expect(cursorQuestionIn(ASK)).toBe(true)+ })+ it('refuses the box left in the transcript after Enter or Esc', () => {+ expect(cursorQuestionIn(pane('answered'))).toBe(false)+ expect(cursorQuestionIn(pane('answeredReconnecting'))).toBe(false)+ expect(cursorQuestionIn(pane('skipped'))).toBe(false)+ })+ it('refuses the other dialogs, a running tool, and a box that is not the bottom of the pane', () => {+ for (const t of [SHELL, MCP, RUNNING, '']) expect(cursorQuestionIn(t)).toBe(false)+ expect(cursorQuestionIn(`${SHOWN} You chose red.\n → Add a follow-up\n`)).toBe(false)+ // The footer alone, or with no option row under the question line, is not the box.+ expect(cursorQuestionIn(' │ ↑/↓ option · Space select · Enter next/submit · Esc to skip │\n')).toBe(false)+ expect(cursorQuestionIn(' │ Question 1 of 1 │\n │ 1. Red? │\n │ Enter next/submit · Esc to skip │\n')).toBe(false)+ })+ it('the approval and plan tests still refuse the box', () => {+ expect(cursorApprovalIn(SHOWN)).toBe(false)+ expect(cursorPlanPromptIn(SHOWN)).toBe(false)+ })+})++describe('the AskQuestion watch', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ const setup = (read: () => string | null) => {+ const readPane = vi.fn(async () => read())+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ const post = (hook_event_name: string, extra: Record<string, unknown> = {}) =>+ watch.observe('n1', { hook_event_name, conversation_id: 'c1', ...extra }, true)+ return { readPane, emitted, post, watch }+ }+ const WAITING = { nodeId: 'n1', agentId: 'cursor', sessionId: 'c1', kind: 'state', state: 'waiting', verified: true }++ it('the measured Esc run: prompt, box, Esc -> waiting once, and stop ends the reads', async () => {+ const { readPane, emitted, watch } = setup(() => SHOWN)+ const [first, second, stop] = ASK_FX.hooks.skippedEsc+ expect([first, second, stop].map((p) => p.hook_event_name)).toEqual(['beforeSubmitPrompt', 'sessionStart', 'stop'])+ watch.observe('n1', first, true)+ watch.observe('n1', second, true)+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted).toEqual([{ ...WAITING, sessionId: first.conversation_id }])+ watch.observe('n1', stop, true) // normalizes to done (status error): replaces the waiting+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(emitted).toHaveLength(1)+ })++ it('a box drawn after the first read is caught by a later one; an ordinary turn reads a bounded number of times', async () => {+ let n = 0+ const { readPane, emitted, post } = setup(() => (++n === 1 ? RUNNING : SHOWN))+ post('beforeSubmitPrompt')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readPane).toHaveBeenCalledTimes(2)+ expect(emitted).toEqual([WAITING])+ const quiet = setup(() => RUNNING)+ quiet.post('beforeSubmitPrompt')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(quiet.readPane).toHaveBeenCalledTimes(CURSOR_APPROVAL_READS_MS.length)+ expect(quiet.emitted).toEqual([])+ })++ it('the answered box in scrollback never reads as a question', async () => {+ const { emitted, post } = setup(() => pane('answered'))+ post('beforeSubmitPrompt')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(emitted).toEqual([])+ })++ it('a running tool cancels the reads: its own approval reads never take the box for a question', async () => {+ const { emitted, post } = setup(() => SHOWN)+ post('beforeSubmitPrompt')+ post('preToolUse', { tool_use_id: 't1', tool_name: 'Shell' })+ await vi.advanceTimersByTimeAsync(60_000)+ expect(emitted).toEqual([])+ })++ it('a tool after the answer clears the waiting; the quiet stretch after its post can catch a second box', async () => {+ let shown = true+ const { emitted, post } = setup(() => (shown ? SHOWN : RUNNING))+ post('beforeSubmitPrompt')+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ shown = false+ post('preToolUse', { tool_use_id: 't1', tool_name: 'Shell' }) // normalizes to working too+ expect(emitted.map((e) => e.state)).toEqual(['waiting', 'working'])+ post('postToolUse', { tool_use_id: 't1', tool_name: 'Shell' })+ shown = true+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted.map((e) => e.state)).toEqual(['waiting', 'working', 'waiting'])+ })++ it("a child's post re-arms the reads: the parent may ask once its subagent is done", async () => {+ const { emitted, post } = setup(() => SHOWN)+ post('beforeSubmitPrompt', { generation_id: 'g1' })+ post('preToolUse', { tool_use_id: 'task1', tool_name: 'Task', generation_id: 'g1' })+ post('preToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ post('postToolUse', { tool_use_id: 'c1t', conversation_id: 'child-1', generation_id: 'child-1' })+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ expect(emitted).toEqual([WAITING]) // the PARENT's chat id, never the child's+ })++ it('release during the read emits nothing; an unreadable pane stops the reads until the next turn', async () => {+ let resolve: (s: string) => void = () => {}+ const readPane = vi.fn(() => new Promise<string>((r) => (resolve = r)))+ const emitted: NormalizedAgentEvent[] = []+ const watch = createCursorApprovalWatch({ readPane, emit: (e) => emitted.push(e) })+ watch.observe('n1', { hook_event_name: 'beforeSubmitPrompt', conversation_id: 'c1' }, true)+ await vi.advanceTimersByTimeAsync(CURSOR_APPROVAL_DELAY_MS)+ watch.release('n1')+ resolve(SHOWN)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(emitted).toEqual([])+ const dead = setup(() => null)+ dead.post('beforeSubmitPrompt')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(dead.readPane).toHaveBeenCalledTimes(1)+ })+})++describe('a cursor blocked through the mirror and the messaging gate', () => {+ beforeEach(() => _resetForTest())+ afterEach(() => _resetForTest())++ it('holds blocked until the next hook event, and messaging refuses it meanwhile', () => {+ const base = { nodeId: 'n9', agentId: 'cursor', sessionId: 'c1', kind: 'state' as const, verified: true }+ recordAgentEvent({ ...base, state: 'working', newTurn: true })+ recordAgentEvent({ ...base, state: 'working' }) // preToolUse+ const out = recordAgentEvent({ ...base, state: 'blocked' }) // the watch's synthetic event+ expect(out.state).toBe('blocked')+ const entry = mirrorEntry('n9')+ expect(entry?.state).toBe('blocked')+ const o = decideDelivery({ targetLive: true, pane: 'agent', target: entry, tokenFilePresent: true, pasteAware: true })+ expect(o).toEqual({ kind: 'targetBusy', state: 'blocked' })+ recordAgentEvent({ ...base, state: 'working' }) // postToolUse after y / n+ expect(mirrorEntry('n9')?.state).toBe('working')+ })++ it('a question waiting holds until stop, and messaging refuses it meanwhile', () => {+ const base = { nodeId: 'n7', agentId: 'cursor', sessionId: 'c3', kind: 'state' as const, verified: true }+ recordAgentEvent({ ...base, state: 'working', newTurn: true })+ expect(recordAgentEvent({ ...base, state: 'waiting' }).state).toBe('waiting') // the watch's event+ const o = decideDelivery({ targetLive: true, pane: 'agent', target: mirrorEntry('n7'), tokenFilePresent: true, pasteAware: true })+ expect(o).toEqual({ kind: 'targetBusy', state: 'waiting' })+ recordAgentEvent({ ...base, state: 'done', errored: true }) // stop after Esc (measured: status error)+ expect(mirrorEntry('n7')?.state).toBe('done')+ })++ it('a lost stop (network reconnect) is caught by the existing WORKING_STALE_MS sweep', () => {+ recordAgentEvent({ nodeId: 'n8', agentId: 'cursor', sessionId: 'c2', kind: 'state', state: 'working', newTurn: true })+ const at = mirrorEntry('n8')!.updatedAt+ expect(sweepStaleWorking(at + WORKING_STALE_MS)).toEqual([])+ expect(sweepStaleWorking(at + WORKING_STALE_MS + 1)).toEqual(['n8'])+ expect(mirrorEntry('n8')?.state).toBe('done')+ })+})diff --git a/src/core/agents/cursor-approval.ts b/src/core/agents/cursor-approval.tsnew file mode 100644index 000000000..f3a660e34--- /dev/null+++ b/src/core/agents/cursor-approval.ts@@ -0,0 +1,330 @@+/**+ * NEEDS YOU for Cursor (`cursor-agent`), which has NO hook for its approval prompt.+ *+ * Measured on cursor-agent 2026.09.28-64d2043 (interactive TUI, project-level hooks logger): a+ * pending "Run this command?" dialog is preceded by `preToolUse` (+ `beforeShellExecution`) and+ * then silence; an MCP one by `preToolUse` (+ `beforeMCPExecution`). No event, no payload flag.+ * Approve AND skip both end the call with `postToolUse` for the same `tool_use_id`.+ *+ * So: a cursor `preToolUse` whose `tool_use_id` has no `postToolUse`/`postToolUseFailure` gets a+ * pane read at each of CURSOR_APPROVAL_READS_MS (the same `captureSession` the context link uses),+ * stopping at the first that shows Cursor's own approval dialog: the node goes `blocked`. The next+ * hook event (postToolUse on approve or skip, stop on Esc) normalizes to `working`/`done` and+ * replaces it. Nothing polls open-endedly: no pending tool and no quiet turn = no timer and no+ * read; at most CURSOR_APPROVAL_READS_MS.length reads per tool call (and per quiet stretch, below)+ * and `blocked` is emitted once, so a long-running approved command never strobes (rule 7).+ *+ * Why more than one read: MEASURED in the dev app (2026-10-02), a single read 1.5 s after+ * `preToolUse` found no dialog yet and the node sat on RUNNING while the dialog waited ~30 s; the+ * same pane text captured later matched. The dialog's draw time is not ours to know.+ *+ * The dialog test is a closed set (rule 7/14): an exact heading line from the bundle's+ * `decision-logic.ts` (`HR`) plus an option line ending in Cursor's approve hint `(y)`. Anything+ * else degrades to nothing: the node keeps RUNNING, exactly as before this file existed.+ *+ * A SUBAGENT's tool call is watched too: its dialog is drawn on the parent's pane. Its `blocked` (and+ * the `working` that clears it, since normalizeCursor drops child events) carries the PARENT's chat id.+ * A parent `stop` with status `completed` arms the same reads for plan mode's `Ready to build?`.+ *+ * The AskQuestion form fires no tool hook at all (measured: show, answer and Esc; the turn's next+ * hook is its `stop`). So a turn that went quiet (after `beforeSubmitPrompt` or a tool post) arms+ * the same reads for the question box, and a match emits `waiting`, as Claude's AskUserQuestion+ * does. A `preToolUse` cancels them (a tool is running); the next parent tool event or `stop`+ * replaces the `waiting`.+ */+import { isCursorChildToolEvent, type NormalizedAgentEvent } from '../../shared/agents/normalize'+import { probeWithin } from './pane-probe'++/**+ * Every heading `decision-logic.ts` can render. Measured in the TUI: `Run this command?` (shell)+ * and `Run this MCP tool?` (MCP). Read from the bundle only: the rest (a default-mode file write+ * was auto-approved, measured, so `Write to this file?` needs a stricter user config).+ */+export const CURSOR_APPROVAL_HEADINGS: ReadonlySet<string> = new Set([+ 'Run this command?',+ 'Run this command outside the sandbox?',+ 'Run this MCP tool?',+ 'Delete this file?',+ 'Write to this file?',+ 'Read this file?',+ 'Allow this web search?',+ 'Allow this web fetch?'+])++/** Wait this long for the matching postToolUse before the first pane read. An auto-allowed tool+ * posts well inside it; an approval waits on a human. */+export const CURSOR_APPROVAL_DELAY_MS = 1500+/** When (ms after `preToolUse`) a still-pending call reads the pane; the first match wins.+ * note: fixed bounded schedule; a dialog first drawn after the last read stays RUNNING. */+export const CURSOR_APPROVAL_READS_MS: readonly number[] = [CURSOR_APPROVAL_DELAY_MS, 4000, 10000]++/**+ * The dialog sits at the bottom of the screen. Only the last few non-blank lines are looked at, so+ * a dialog left in scrollback by an earlier render cannot answer for the current one.+ * note: fixed window, widen if a taller dialog (long command preview) is ever measured.+ */+const TAIL_LINES = 30++/** Strip the box-drawing border and padding Cursor may draw around a row. */+function bare(line: string): string {+ return line.replace(/^[\s│┃|]+|[\s│┃|]+$/g, '')+}++/** PURE. Does the bottom of this capture hold one of `headings` followed by an option ending `hint`? */+function dialogIn(text: string, headings: ReadonlySet<string>, hint: string): boolean {+ const lines = text.split('\n').map(bare).filter(Boolean).slice(-TAIL_LINES)+ const at = lines.findIndex((l) => headings.has(l))+ if (at < 0) return false+ return lines.slice(at + 1).some((l) => l.endsWith(hint))+}++/** PURE. Does this pane capture end in a Cursor approval dialog? */+export function cursorApprovalIn(text: string): boolean {+ return dialogIn(text, CURSOR_APPROVAL_HEADINGS, '(y)')+}++/**+ * Plan mode's hand-off. MEASURED on 2026.10.01-e373342 (`--mode plan`): the turn ENDS (`stop`,+ * status `completed`, normalized `done`) and then the pane shows `Ready to build?` /+ * `→ 1. Yes, build locally (b)` / [`2. Yes, build in cloud (c)`] / `No, propose changes (p or Esc)`.+ * No hook marks it. Claude's equivalent (ExitPlanMode, a PermissionRequest) is `blocked`, so this is+ * too. Answering `b` fires no beforeSubmitPrompt; the build's first parent tool event clears it.+ */+export const CURSOR_PLAN_HEADINGS: ReadonlySet<string> = new Set(['Ready to build?'])++/** A plan box border row once `bare` has stripped its side bars. */+const BORDER = /^[─━└┘╰╯┌┐╭╮\s]+$/++/**+ * PURE. Does this pane capture END in plan mode's "Ready to build?" prompt? Stricter than the+ * approval test: the answered prompt STAYS in the transcript, and measured, the build's own `stop`+ * found it 30 lines up with the finished build below it. So nothing but option rows (ending in a+ * `(key)` hint) and the box border may follow the heading.+ */+export function cursorPlanPromptIn(text: string): boolean {+ const lines = text.split('\n').map(bare).filter(Boolean).slice(-TAIL_LINES)+ let at = lines.length - 1+ while (at >= 0 && !CURSOR_PLAN_HEADINGS.has(lines[at])) at--+ if (at < 0) return false+ const tail = lines.slice(at + 1)+ return tail.some((l) => l.endsWith('(b)')) && tail.every((l) => /\([^()]*\)$/.test(l) || BORDER.test(l))+}++/**+ * The AskQuestion box (bundle: `ask-question-tool-ui.tsx`). Its title is the model's own (measured+ * `Color preference`, `Quick preferences`) or the default `Clarifying Questions`, so it is not+ * matched. Rows as `bare` leaves them: `Question 1 of 2`, an option `› [ ] Red` / `[x] Blue`, and the+ * fixed footer, which wraps on a narrow pane (measured at 60 columns: `... · Enter` / `next/submit ·+ * Esc to skip`).+ */+const QUESTION_ROW = /^Question \d+ of \d+$/+const OPTION_ROW = /^(› )?\[[ x]\] /+const QUESTION_FOOTER_END = 'Esc to skip'++/**+ * PURE. Does this pane capture END in an AskQuestion box? The answered box stays in the transcript+ * as a summary (`AskQuestion <title> (1)` and `[x]` rows) without the footer, so the footer must be+ * the last row above the bottom border, with a `Question N of M` row and an option row above it.+ */+export function cursorQuestionIn(text: string): boolean {+ const lines = text.split('\n').map(bare).filter(Boolean).slice(-TAIL_LINES)+ let end = lines.length+ while (end > 0 && BORDER.test(lines[end - 1])) end--+ if (end === 0 || !lines[end - 1].endsWith(QUESTION_FOOTER_END)) return false+ let at = end - 1+ while (at >= 0 && !QUESTION_ROW.test(lines[at])) at--+ return at >= 0 && lines.slice(at + 1, end).some((l) => OPTION_ROW.test(l))+}++export interface CursorApprovalWatchDeps {+ /** The node's pane text ('' or null = cannot see it). */+ readPane: (nodeId: string) => Promise<string | null>+ /** Where the synthetic `blocked` goes: the hook server's normalized listener. */+ emit: (ev: NormalizedAgentEvent) => void+ /** Override the whole read schedule (tests). Default CURSOR_APPROVAL_READS_MS. */+ readsMs?: readonly number[]+}++export interface CursorApprovalWatch {+ /** Feed every cursor hook payload, after its normalized event was emitted. */+ observe(nodeId: string, payload: Record<string, unknown>, verified: boolean): void+ /** The node was closed or recycled: drop its timers, and let no read still in flight emit. */+ release(nodeId: string): void+}++const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)++/** The pending key of the one plan-prompt watch per node (a tool_use_id is never empty). */+const PLAN = ''+/** The pending key of the one question-box watch per node (no measured tool_use_id has a NUL). */+const QUESTION = '\0question'++interface Pending {+ /** The next read, null while a read is in flight or once the reads are spent. */+ timer: ReturnType<typeof setTimeout> | null+ /** A SUBAGENT's tool call: normalizeCursor drops its events, so this watch also clears its block. */+ child: boolean+ /** Its read matched a dialog. */+ blocked: boolean+}++interface NodeWatch {+ /** tool_use_id (or PLAN) → its watch. */+ calls: Map<string, Pending>+ /** The PARENT chat id, learned from the node's parent events. A synthetic event for a child's+ * call carries this, never the child's id, which would overwrite the node's resume id. */+ sessionId?: string+ /** This watch has the node in `blocked`: one dialog is one `blocked`, however many pending calls+ * read it (measured: a parent call and a child call both read the child's dialog). */+ blocked: boolean+ /** A read came back empty or timed out: no more reads until the next turn edge. pane-probe.ts's+ * rule: retrying an unreadable pane on a short timer stacks ssh children, then logins. */+ broken: boolean+}++export function createCursorApprovalWatch(deps: CursorApprovalWatchDeps): CursorApprovalWatch {+ const reads = deps.readsMs ?? CURSOR_APPROVAL_READS_MS+ const nodes = new Map<string, NodeWatch>()+ // Nodes with a pane capture outstanding. At most one per node, and it outlives release, turn+ // edges and sessionEnd: it is cleared only when the capture itself settles, because a probe that+ // timed out abandons the WAIT, not the ssh child (pane-probe.ts), so a replacement session must not+ // start a second one beside it. A due read finding its node here is skipped, never handed the+ // other read's result: that snapshot may belong to another turn.+ const inFlight = new Set<string>()+ const nodeFor = (nodeId: string): NodeWatch => {+ let w = nodes.get(nodeId)+ if (!w) nodes.set(nodeId, (w = { calls: new Map(), blocked: false, broken: false }))+ return w+ }++ const drop = (w: NodeWatch, id: string): void => {+ const p = w.calls.get(id)+ if (p?.timer) clearTimeout(p.timer)+ w.calls.delete(id)+ }+ /** Turn edge: nothing of the old turn is still waiting, and the breaker gets a fresh turn. */+ const dropAll = (w: NodeWatch): void => {+ for (const id of [...w.calls.keys()]) drop(w, id)+ w.blocked = false+ w.broken = false+ }++ const emit = (nodeId: string, w: NodeWatch, state: 'blocked' | 'waiting' | 'working', verified: boolean): void => {+ const sessionId = w.sessionId+ deps.emit({ nodeId, agentId: 'cursor', ...(sessionId ? { sessionId } : {}), kind: 'state', state, verified })+ }++ const schedule = (nodeId: string, w: NodeWatch, id: string, p: Pending, verified: boolean, step: number): void => {+ const next = step + 1+ if (next >= reads.length) return+ p.timer = setTimeout(() => void check(nodeId, w, id, verified, next), reads[next] - reads[step])+ }++ const check = async (nodeId: string, w: NodeWatch, id: string, verified: boolean, step: number): Promise<void> => {+ const p = w.calls.get(id)+ if (!p) return+ p.timer = null+ if (w.broken) return+ if (inFlight.has(nodeId)) return schedule(nodeId, w, id, p, verified, step)+ inFlight.add(nodeId)+ const raw = Promise.resolve().then(() => deps.readPane(nodeId))+ void raw.catch(() => null).then(() => inFlight.delete(nodeId))+ const text = await probeWithin(() => raw)+ // Re-check: a release, a post or a new turn that landed during the read already ended the watch.+ if (nodes.get(nodeId) !== w || w.calls.get(id) !== p) return+ if (!text) {+ w.broken = true+ for (const q of w.calls.values()) {+ if (q.timer) clearTimeout(q.timer)+ q.timer = null+ }+ return+ }+ const seen = id === PLAN ? cursorPlanPromptIn : id === QUESTION ? cursorQuestionIn : cursorApprovalIn+ if (seen(text)) {+ p.blocked = true+ if (!w.blocked) emit(nodeId, w, id === QUESTION ? 'waiting' : 'blocked', verified)+ w.blocked = true+ return // the call stays pending only so a post can still end it+ }+ schedule(nodeId, w, id, p, verified, step)+ }++ const arm = (nodeId: string, w: NodeWatch, id: string, child: boolean, verified: boolean): void => {+ drop(w, id)+ if (w.broken) return+ const p: Pending = { timer: null, child, blocked: false }+ w.calls.set(id, p)+ p.timer = setTimeout(() => void check(nodeId, w, id, verified, 0), reads[0])+ }++ return {+ observe(nodeId, payload, verified) {+ const ev = payload.hook_event_name+ const isTool = ev === 'preToolUse' || ev === 'postToolUse' || ev === 'postToolUseFailure'+ // A subagent's tool call (the SAME predicate normalizeCursor uses: captured children carry no+ // parent_tool_call_id, only generation_id === conversation_id). It applies to TOOL events only:+ // the parent's own sessionStart/sessionEnd carry generation_id === conversation_id too.+ // A child's dialog is drawn on the PARENT's pane (measured 2026.10.01), so it is watched like+ // the parent's own calls.+ const child = isTool && isCursorChildToolEvent(payload)+ if (ev === 'sessionEnd') {+ if (payload.is_background_agent === true) return // not this node's session (normalizeCursor)+ const w = nodes.get(nodeId)+ if (w) dropAll(w)+ nodes.delete(nodeId)+ return+ }+ const w = nodeFor(nodeId)+ // Only a parent event names the node's session: any event with generation_id ===+ // conversation_id (a child's tool call, or a child's non-tool event such as+ // beforeShellExecution) carries the CHILD's chat id, which would replace the resume id.+ if (!isCursorChildToolEvent(payload)) {+ const sid = str(payload.conversation_id) ?? str(payload.session_id)+ if (sid) w.sessionId = sid+ }+ const id = str(payload.tool_use_id)+ if (ev === 'preToolUse') {+ drop(w, PLAN) // the agent is building after all+ drop(w, QUESTION) // a tool is running: the question box is not up+ if (!child && w.blocked) {+ // A parent tool call means the node is working. A plain call already normalizes to+ // `working`, but a `Task` normalizes to `subagent-start` and its child's events to+ // nothing, so a plan prompt answered with a delegated build would otherwise stay blocked.+ w.blocked = false+ emit(nodeId, w, 'working', verified)+ }+ // The parent's `Task` never gets a postToolUse (measured), so a read hung on it could only+ // see its CHILD's dialog, which the child's own call already watches and later clears.+ if (!id || (!child && payload.tool_name === 'Task')) return+ arm(nodeId, w, id, child, verified)+ } else if (isTool && id) {+ const p = w.calls.get(id)+ drop(w, id)+ if (!child) {+ w.blocked = false // normalizes to `working`, which already replaced any block+ } else if (p?.blocked && ![...w.calls.values()].some((q) => q.blocked)) {+ // A child's post normalizes to nothing, so the block this watch raised would stick.+ w.blocked = false+ emit(nodeId, w, 'working', verified)+ }+ // Quiet again: the model may ask next. A child's post counts too: the parent's `Task`+ // never posts, and the parent may ask once its child is done.+ if (!w.blocked) arm(nodeId, w, QUESTION, false, verified)+ } else if (ev === 'stop' || ev === 'beforeSubmitPrompt') {+ dropAll(w)+ // A completed turn may end on plan mode's "Ready to build?": the same bounded reads.+ if (ev === 'stop' && payload.status === 'completed') arm(nodeId, w, PLAN, false, verified)+ // A new turn may open on a question: the same bounded reads.+ // note: fixed schedule; a box first drawn after the last read of a quiet stretch stays RUNNING.+ if (ev === 'beforeSubmitPrompt') arm(nodeId, w, QUESTION, false, verified)+ }+ },+ release(nodeId) {+ const w = nodes.get(nodeId)+ if (!w) return+ dropAll(w)+ nodes.delete(nodeId)+ }+ }+}diff --git a/src/core/agents/hook-server.cursor-approval.test.ts b/src/core/agents/hook-server.cursor-approval.test.tsnew file mode 100644index 000000000..9ff1dbf2c--- /dev/null+++ b/src/core/agents/hook-server.cursor-approval.test.ts@@ -0,0 +1,97 @@+// The hook server's cursor approval seam (core/agents/cursor-approval.ts) over real POSTs: a+// pending preToolUse earns one pane read and a `blocked` on the SAME listener both shells install;+// the read stays off for every other agent and when no reader is wired.+import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { hookServer } from './hook-server'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { CURSOR_APPROVAL_DELAY_MS } from './cursor-approval'+import type { NormalizedAgentEvent } from '@shared/agents/normalize'++const DIALOG = ' Run this command?\n Not in allowlist: touch\n → Run (once) (y)\n'+const QUESTION_BOX = [+ ' │ Clarifying Questions │',+ ' │ Question 1 of 1 │',+ ' │ 1. Do you prefer red or blue? │',+ ' │ › [ ] Red │',+ ' │ ↑/↓ option · ←/→ question · Space select · Enter next/submit · Esc to skip │',+ ' └──────┘',+ ''+].join('\n')+let dir = ''+let events: NormalizedAgentEvent[] = []+let screen = DIALOG+const readPane = vi.fn(async (_nodeId: string) => screen)++function post(agent: string, payload: Record<string, unknown>): Promise<Response> {+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/${agent}`, {+ method: 'POST',+ headers: { 'X-Nodeterm-Hook-Token': hookServer.getToken(), 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ nodeId: 'term-cur-1', payload: JSON.stringify(payload) }).toString()+ })+}+const settle = (): Promise<void> => new Promise((r) => setTimeout(r, CURSOR_APPROVAL_DELAY_MS + 200))++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'hooksrv-cursor-approval-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setListener((e) => events.push(e))+ hookServer.setPaneReader(readPane)+})+afterAll(() => {+ hookServer.stop()+ rmSync(dir, { recursive: true, force: true })+})+beforeEach(() => {+ events = []+ screen = DIALOG+ readPane.mockClear()+})++describe('hook server: cursor approval watch', () => {+ it('a preToolUse with no post goes blocked after one read', async () => {+ await post('cursor', { hook_event_name: 'preToolUse', tool_use_id: 'u1', conversation_id: 'c1' })+ await settle()+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(readPane).toHaveBeenCalledWith('term-cur-1')+ expect(events.map((e) => e.state)).toEqual(['working', 'blocked'])+ expect(events[1]).toMatchObject({ agentId: 'cursor', sessionId: 'c1', kind: 'state' })+ // The next hook event (approve or skip) puts it back to working.+ await post('cursor', { hook_event_name: 'postToolUse', tool_use_id: 'u1', conversation_id: 'c1' })+ expect(events.at(-1)?.state).toBe('working')+ await post('cursor', { hook_event_name: 'stop', status: 'aborted', conversation_id: 'c1' }) // ends the quiet reads+ })++ it('a post in time reads nothing; another agent never reads', async () => {+ await post('cursor', { hook_event_name: 'preToolUse', tool_use_id: 'u2', conversation_id: 'c1' })+ await post('cursor', { hook_event_name: 'postToolUse', tool_use_id: 'u2', conversation_id: 'c1' })+ await post('cursor', { hook_event_name: 'stop', status: 'aborted', conversation_id: 'c1' })+ await post('claude', { hook_event_name: 'PreToolUse', tool_use_id: 'u3', session_id: 's', tool_name: 'Bash' })+ await settle()+ expect(readPane).not.toHaveBeenCalled()+ expect(events.some((e) => e.state === 'blocked')).toBe(false)+ })++ it('a prompt that ends on the AskQuestion box goes waiting; stop replaces it', async () => {+ screen = QUESTION_BOX+ await post('cursor', { hook_event_name: 'beforeSubmitPrompt', conversation_id: 'c1', prompt: 'ask me' })+ await settle()+ expect(readPane).toHaveBeenCalledTimes(1)+ expect(events.map((e) => e.state)).toEqual(['working', 'waiting'])+ expect(events[1]).toMatchObject({ agentId: 'cursor', sessionId: 'c1', kind: 'state', nodeId: 'term-cur-1' })+ await post('cursor', { hook_event_name: 'stop', status: 'error', conversation_id: 'c1' })+ expect(events.at(-1)?.state).toBe('done')+ })+})++describe('both shells wire the reader', () => {+ it.each(['src/main/index.ts', 'src/server/index.ts'])('%s calls setPaneReader with captureSession', (file) => {+ const src = readFileSync(join(__dirname, '../../..', file), 'utf8')+ expect(src).toMatch(/hookServer\.setPaneReader\(\(nodeId\) => ptyManager\.captureSession\(nodeId\)\)/)+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 79a9fcdd7..6d298cf7d 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -1,6 +1,7 @@import { REPORT_OUTCOME_CONTROL_REFUSAL } from '../../shared/station-outcome'import { sessionContextWindow } from '../model-window'import { labelHeldForRevision } from './permission-decision'+import { createCursorApprovalWatch, type CursorApprovalWatch } from './cursor-approval'import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'import { randomUUID, timingSafeEqual } from 'crypto'import { readFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'@@ -515,6 +516,18 @@ export class HookServer {this.listener = cb}+ /** Cursor's approval prompt has no hook, so a pending tool call earns up to three pane reads+ * (CURSOR_APPROVAL_READS_MS, core/agents/cursor-approval.ts). Both shells pass their pty manager's `captureSession`;+ * unset = cursor never shows NEEDS YOU, as before. The synthetic `blocked` rides `listener`. */+ private cursorWatch: CursorApprovalWatch | null = null+ setPaneReader(readPane: (nodeId: string) => Promise<string | null>): void {+ this.cursorWatch = createCursorApprovalWatch({ readPane, emit: (e) => this.listener?.(e) })+ }+ /** A node was closed or recycled: its pending pane reads must not resurrect it as `blocked`. */+ releaseCursorNode(nodeId: string): void {+ this.cursorWatch?.release(nodeId)+ }+private grokPermissionGate: GrokPermissionGate | null = nullprivate grokGateDeps: GrokPermissionGateDeps | undefined/** Test seam: the grok permission gate's file/timer deps. */@@ -1177,6 +1190,7 @@ export class HookServer {// order is kept per node.else if (agentId === 'codex') this.codexGate().handle(nodeId, payload, labelled)else if (labelled && this.listener) this.listener(labelled)+ if (agentId === 'cursor') this.cursorWatch?.observe(nodeId, payload, verified)}res.writeHead(204)res.end()diff --git a/src/core/agents/hooks/cursor.test.ts b/src/core/agents/hooks/cursor.test.tsnew file mode 100644index 000000000..f2303a019--- /dev/null+++ b/src/core/agents/hooks/cursor.test.ts@@ -0,0 +1,166 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { spawnSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { CURSOR_HOOK_EVENTS } from '../../../shared/agents/hook-events'+import { applyCursorHooks, cursorCommandFor, installCursorHooks, removeCursorHooks } from './cursor'++let home: string+let hooksJson: string+let script: string+const found = (): string => '/x/cursor-agent'+const read = (): Record<string, any> => JSON.parse(fs.readFileSync(hooksJson, 'utf8')) // eslint-disable-line @typescript-eslint/no-explicit-any++beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'cursor-hooks-'))+ hooksJson = path.join(home, '.cursor', 'hooks.json')+ script = path.join(home, '.nodeterm', 'agent-hooks', 'cursor.sh')+})+afterEach(() => fs.rmSync(home, { recursive: true, force: true }))++const install = (extra = {}) => installCursorHooks({ hooksJson, scriptPath: script, findCursorAgent: found, platform: 'linux', ...extra })+// One open, then fstat + read on the same descriptor: no check-then-use window on the path.+const snapshot = (p: string): { text: string; mode: number; mtimeMs: number } => {+ const fd = fs.openSync(p, 'r')+ try {+ const st = fs.fstatSync(fd)+ return { text: fs.readFileSync(fd, 'utf8'), mode: st.mode, mtimeMs: st.mtimeMs }+ } finally {+ fs.closeSync(fd)+ }+}+const ours = (entries: { command?: string }[]) => entries.filter((e) => e.command?.includes('.nodeterm/agent-hooks/cursor.sh'))++describe('installCursorHooks', () => {+ it('writes nothing on Windows: the command is POSIX sh and a bad byte denies every tool', () => {+ expect(install({ platform: 'win32' })).toBe('refused')+ expect(fs.existsSync(hooksJson)).toBe(false)+ expect(fs.existsSync(script)).toBe(false)+ })++ it('creates a version-1 file with one entry of ours on each of the five events, and the script', () => {+ expect(install()).toBe('installed')+ const cfg = read()+ expect(cfg.version).toBe(1)+ expect(Object.keys(cfg.hooks).sort()).toEqual([...CURSOR_HOOK_EVENTS].sort())+ for (const ev of CURSOR_HOOK_EVENTS) {+ expect(cfg.hooks[ev]).toHaveLength(1)+ expect(cfg.hooks[ev][0].timeout).toBe(5)+ }+ const sh = snapshot(script)+ expect(sh.mode & 0o111).not.toBe(0)+ expect(sh.text).toContain('/hook/cursor')+ })++ it('is idempotent: a second install writes nothing and never duplicates', () => {+ install()+ const before = snapshot(hooksJson)+ install()+ const after = snapshot(hooksJson)+ expect(after.text).toBe(before.text)+ expect(after.mtimeMs).toBe(before.mtimeMs)+ })++ it("keeps the user's own hooks and keys, on our events and on others", () => {+ const mine = { command: 'bash /home/u/my-gate.sh', matcher: 'Shell' }+ const herdr = { command: "bash '/x/herdr-agent-state.sh' session" }+ fs.mkdirSync(path.dirname(hooksJson), { recursive: true })+ fs.writeFileSync(hooksJson, JSON.stringify({ version: 1, extra: { a: 1 }, hooks: { preToolUse: [mine], sessionStart: [herdr] } }))+ install()+ install()+ const cfg = read()+ expect(cfg.extra).toEqual({ a: 1 })+ expect(cfg.hooks.sessionStart).toEqual([herdr])+ expect(cfg.hooks.preToolUse[0]).toEqual(mine)+ expect(ours(cfg.hooks.preToolUse)).toHaveLength(1)+ })++ it('sweeps our entry off an event we no longer subscribe, and keeps the rest of that event', () => {+ const other = { command: 'other' }+ fs.mkdirSync(path.dirname(hooksJson), { recursive: true })+ fs.writeFileSync(hooksJson, JSON.stringify({ version: 1, hooks: { afterAgentResponse: [{ command: cursorCommandFor(script) }, other], sessionStart: [{ command: cursorCommandFor(script) }] } }))+ install()+ const cfg = read()+ expect(cfg.hooks.afterAgentResponse).toEqual([other])+ expect(cfg.hooks.sessionStart).toBeUndefined()+ })++ it('does not claim a user script that merely shares the name', () => {+ const theirs = { command: 'sh /home/u/work/agent-hooks/cursor.sh' }+ fs.mkdirSync(path.dirname(hooksJson), { recursive: true })+ fs.writeFileSync(hooksJson, JSON.stringify({ version: 1, hooks: { stop: [theirs] } }))+ install()+ expect(read().hooks.stop[0]).toEqual(theirs)+ removeCursorHooks({ hooksJson })+ expect(read().hooks.stop).toEqual([theirs])+ })++ it('leaves an unparseable or mis-shaped file byte-for-byte', () => {+ fs.mkdirSync(path.dirname(hooksJson), { recursive: true })+ for (const raw of ['{ not json', '[]', JSON.stringify({ hooks: [] }), JSON.stringify({ hooks: { stop: 'x' } })]) {+ fs.writeFileSync(hooksJson, raw)+ install()+ expect(fs.readFileSync(hooksJson, 'utf8')).toBe(raw)+ }+ })++ it('writes nothing at all when cursor-agent is not installed', () => {+ expect(install({ findCursorAgent: () => null })).toBe('no-cursor')+ expect(fs.existsSync(path.join(home, '.cursor'))).toBe(false)+ expect(fs.existsSync(script)).toBe(false)+ })++ it('refuses a command that cursor would truncate as a // comment', () => {+ const odd = `${home}/a//b/cursor.sh`+ expect(install({ scriptPath: odd })).toBe('refused')+ expect(fs.existsSync(hooksJson)).toBe(false)+ })++ it('removes only our entries, and never creates the file', () => {+ removeCursorHooks({ hooksJson })+ expect(fs.readdirSync(home)).not.toContain('.cursor')+ const mine = { command: 'mine' }+ fs.mkdirSync(path.dirname(hooksJson), { recursive: true })+ fs.writeFileSync(hooksJson, JSON.stringify({ version: 1, hooks: { stop: [mine] } }))+ install()+ removeCursorHooks({ hooksJson })+ expect(read()).toEqual({ version: 1, hooks: { stop: [mine] } })+ })+})++describe('applyCursorHooks', () => {+ it('does not mutate its input', () => {+ const input = { version: 1, hooks: { stop: [{ command: 'x' }] } }+ const snapshot = JSON.stringify(input)+ applyCursorHooks(input, 'cmd')+ expect(JSON.stringify(input)).toBe(snapshot)+ })+})++describe('the hook command is a silent gate-safe wrapper (cursor denies on bad JSON or exit 2)', () => {+ const run = (cmd: string, input = '{}') => spawnSync('sh', ['-c', cmd], { input, encoding: 'utf8' })++ it.skipIf(process.platform === 'win32')('prints nothing and exits 0 when the script exits 2 and writes garbage', () => {+ fs.mkdirSync(path.dirname(script), { recursive: true })+ fs.writeFileSync(script, 'echo not-json\necho oops >&2\nexit 2\n')+ const r = run(cursorCommandFor(script))+ expect(r.stdout).toBe('')+ expect(r.stderr).toBe('')+ expect(r.status).toBe(0)+ })++ it.skipIf(process.platform === 'win32')('prints nothing and exits 0 when the script is gone', () => {+ const r = run(cursorCommandFor(path.join(home, 'gone.sh')))+ expect(r.stdout).toBe('')+ expect(r.status).toBe(0)+ })++ it.skipIf(process.platform === 'win32')('the REAL script prints nothing and exits 0 outside nodeterm (no NODETERM_NODE_ID)', () => {+ install()+ const env = { PATH: process.env.PATH ?? '', HOME: home }+ const r = spawnSync('sh', ['-c', cursorCommandFor(script)], { input: JSON.stringify({ hook_event_name: 'preToolUse' }), encoding: 'utf8', env })+ expect(r.stdout).toBe('')+ expect(r.status).toBe(0)+ })+})diff --git a/src/core/agents/hooks/cursor.ts b/src/core/agents/hooks/cursor.tsnew file mode 100644index 000000000..e7b7fdc33--- /dev/null+++ b/src/core/agents/hooks/cursor.ts@@ -0,0 +1,147 @@+// Cursor Agent CLI status-hook installer: registered in hooks/index.ts (runs at every launch).+//+// WHERE. `cursor-agent` reads `~/.cursor/hooks.json` (user), `<workspace>/.cursor/hooks.json`+// (project) and, as Claude compat, the hooks of `~/.claude/settings.json`. The user file is SHARED+// with the Cursor IDE and with other tools (this machine's holds another tool's `sessionStart`+// entry), so we merge into it instead of owning it: our entries are flat `{command, timeout}`+// items appended to each subscribed event, every other entry and key survives, and a file we+// cannot parse (or whose `hooks` is not an object of arrays) is left untouched. Publishing goes+// through the shared settings transaction (`updateSettingsFile`): symlink-safe, mode-keeping,+// locked, ENOENT-only creation.+//+// SAFETY. `preToolUse` is a gate: Cursor reads its stdout as a decision (invalid JSON denies) and+// exit code 2 denies. Empty stdout and any other exit code are fail-open (measured, and in the+// bundle's executeCommandHook). The command therefore runs the script with stdout+stderr on+// /dev/null and `|| :` (`silent`), and our script prints nothing anyway.+//+// TRAP. Cursor strips `//…` from hooks.json as JSONC comments before JSON.parse, ignoring quotes,+// so a command containing `//` would corrupt the WHOLE file for every tool. We refuse to write one.+import path from 'path'+import os from 'os'+import { chmodSync, existsSync, mkdirSync } from 'fs'+import { CURSOR_HOOK_EVENTS } from '@shared/agents/hook-events'+import { buildManagedHookCommand, normalizeHookCommand, writeManagedHookFileAtomic } from './install-helper'+import { buildManagedScript } from './managed-script'+import { updateSettingsFile } from './settings-file'+import { findExecutableSync } from '../../exec-path'++export const CURSOR_SCRIPT_FILE = 'cursor.sh'+/** Seconds Cursor waits for one handler (its default is 60). */+export const CURSOR_HOOK_TIMEOUT = 5++type Json = Record<string, unknown>+const isRecord = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)++// `os.homedir()` through the DEFAULT import so a test that spies it redirects the whole install.+export function cursorHooksJsonPath(home: string = os.homedir()): string {+ return path.join(home, '.cursor', 'hooks.json')+}+export function cursorScriptPath(home: string = os.homedir()): string {+ return path.join(home, '.nodeterm', 'agent-hooks', CURSOR_SCRIPT_FILE)+}++/** Where the vendor installer puts the CLI (`~/.local/bin/cursor-agent`, measured on macOS). */+export function findCursorAgent(): string | null {+ return findExecutableSync('cursor-agent', [path.join(os.homedir(), '.local', 'bin', 'cursor-agent')])+}++export function cursorCommandFor(scriptPath: string): string {+ return buildManagedHookCommand(scriptPath, { silent: true })+}++/** Ours = the command carries `.nodeterm/agent-hooks/cursor.sh` (anchored: a user's own+ * `~/work/agent-hooks/cursor.sh` is not ours). */+export function isCursorManagedCommand(command: unknown): boolean {+ return typeof command === 'string' && normalizeHookCommand(command).includes(`.nodeterm/agent-hooks/${CURSOR_SCRIPT_FILE}`)+}++const withoutOurs = (entries: unknown[]): unknown[] =>+ entries.filter((e) => !(isRecord(e) && isCursorManagedCommand(e.command)))++/**+ * Pure: `config` with exactly one entry of ours (`command`) on every event in `events` and none on+ * any other event. Throws on a shape we cannot merge into (the transaction then leaves the file).+ */+export function applyCursorHooks(config: Json, command: string | null, events: readonly string[] = CURSOR_HOOK_EVENTS): Json {+ const hooks = config.hooks+ if (hooks !== undefined && !isRecord(hooks)) throw new Error('hooks is not an object')+ const next: Json = {}+ for (const [event, entries] of Object.entries(hooks ?? {})) {+ if (!Array.isArray(entries)) throw new Error(`hooks.${event} is not a list`)+ const kept = withoutOurs(entries)+ if (command !== null && events.includes(event)) kept.push({ command, timeout: CURSOR_HOOK_TIMEOUT })+ // An event we emptied goes away; one that was already empty is someone else's and stays.+ if (kept.length || entries.length === 0) Object.defineProperty(next, event, { value: kept, enumerable: true, writable: true, configurable: true })+ }+ if (command !== null) {+ for (const event of events) {+ if (!(event in next)) Object.defineProperty(next, event, { value: [{ command, timeout: CURSOR_HOOK_TIMEOUT }], enumerable: true, writable: true, configurable: true })+ }+ }+ const out: Json = { ...config, hooks: next }+ // A file we create carries `version: 1`; one that exists keeps whatever it had.+ if (command !== null && Object.keys(config).length === 0) out.version = 1+ // Removing ours from a file that only we had touched leaves `{hooks:{}}`; that is fine, not ours to delete.+ return out+}++export interface CursorInstallOptions {+ /** Defaults to `~/.cursor/hooks.json`. Tests pass a temp path. */+ hooksJson?: string+ scriptPath?: string+ /** Is `cursor-agent` installed? Defaults to a file lookup (never a spawn). */+ findCursorAgent?: () => string | null+ writeScript?: boolean+ /** Defaults to `process.platform`. Tests pass `'win32'`. */+ platform?: NodeJS.Platform+}++export type CursorInstallOutcome = 'installed' | 'no-cursor' | 'refused'++export function installCursorHooks(opts: CursorInstallOptions = {}): CursorInstallOutcome {+ // The command is POSIX sh. Windows hook execution is unmeasured, and a non-JSON byte on+ // preToolUse denies the tool in every cursor session on the machine, so write nothing there+ // (antigravity's rule: refuse rather than write a command cmd.exe may misread).+ if ((opts.platform ?? process.platform) === 'win32') {+ console.warn('[agent-hooks] cursor install skipped: no measured Windows hook command yet')+ return 'refused'+ }+ const hooksJson = opts.hooksJson ?? cursorHooksJsonPath()+ const script = opts.scriptPath ?? cursorScriptPath()+ // Only where the CLI exists: the file is shared with the IDE and other tools.+ // note: one boot-time lookup (PATH + vendor dir), no login-shell re-probe like agy's two+ // passes; a cursor-agent living only on a shell-rc PATH is missed until it is on the app's PATH.+ let found: string | null+ try {+ found = (opts.findCursorAgent ?? findCursorAgent)()+ } catch {+ found = null+ }+ if (!found) return 'no-cursor'+ const command = cursorCommandFor(script)+ if (command.includes('//')) {+ console.warn('[agent-hooks] cursor install skipped: the hook command contains "//", which cursor strips as a comment')+ return 'refused'+ }+ if (opts.writeScript !== false) {+ try {+ mkdirSync(path.dirname(script), { recursive: true })+ writeManagedHookFileAtomic(script, buildManagedScript('cursor'), undefined, 0o755)+ chmodSync(script, 0o755)+ } catch (e) {+ console.warn('[agent-hooks] cursor script write failed', e)+ return 'refused'+ }+ }+ // updateSettingsFile answers false for "nothing to change" AND for "could not publish"; either+ // way the file is never half-written, and a later launch retries.+ updateSettingsFile(hooksJson, (config) => applyCursorHooks(config, command))+ return 'installed'+}++/** Remove our entries from every event. Never creates the file, never touches anything else. */+export function removeCursorHooks(opts: Pick<CursorInstallOptions, 'hooksJson'> = {}): void {+ const file = opts.hooksJson ?? cursorHooksJsonPath()+ if (!existsSync(file)) return+ updateSettingsFile(file, (config) => (config.hooks === undefined ? config : applyCursorHooks(config, null)))+}diff --git a/src/core/agents/hooks/index.ts b/src/core/agents/hooks/index.tsindex a0e717ac2..980688643 100644--- a/src/core/agents/hooks/index.ts+++ b/src/core/agents/hooks/index.ts@@ -9,6 +9,7 @@ import { installGrokHooks, removeGrokHooks } from './grok'import { ensureGrokHomeProbed, grokHomeDir, grokHomeFallbackWasSilent } from '../grok-paths'import { installCopilotHooks, removeCopilotHooks } from './copilot'import { installAntigravityHooksWithProbe, removeAntigravityHooks } from './antigravity'+import { installCursorHooks, removeCursorHooks } from './cursor'type HookInstaller = readonly [string, () => void]@@ -23,7 +24,9 @@ export const MANAGED_HOOK_INSTALLERS: readonly HookInstaller[] = [// call on the machine. Only where agy is installed, decided in two passes around the login-shell// PATH probe (the same shape as grok's $GROK_HOME re-install below); refuses on Windows while// cmd.exe has an AutoRun (antigravity-autorun.ts).- ['antigravity', () => void installAntigravityHooksWithProbe()]+ ['antigravity', () => void installAntigravityHooksWithProbe()],+ // Merges into the SHARED ~/.cursor/hooks.json (IDE + other tools), only where cursor-agent exists.+ ['cursor', () => void installCursorHooks()]]export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [@@ -33,7 +36,8 @@ export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [['opencode', removeOpencodeHooks],['grok', removeGrokHooks],['copilot', removeCopilotHooks],- ['antigravity', () => removeAntigravityHooks()]+ ['antigravity', () => removeAntigravityHooks()],+ ['cursor', () => removeCursorHooks()]]/**diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex aeb3b904a..1ca6e30e6 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -136,6 +136,13 @@ export interface ManagedHookCommandOptions {* the wrong answer for some events. Omitted ⇒ the branch prints nothing, as it always has.*/fallbackStdout?: string+ /**+ * Send the script's stdout AND stderr to /dev/null and force exit 0 (`sh q >/dev/null 2>&1 || :`).+ * For an agent that reads a hook's stdout/exit code as a permission decision (cursor: invalid JSON+ * on `preToolUse` DENIES, exit 2 denies) and is otherwise fail-open on silence. Omitted ⇒ the+ * command is byte-identical to before.+ */+ silent?: boolean}const shQuote = (s: string): string => `'${s.replaceAll("'", "'\\''")}'`@@ -181,8 +188,9 @@ export function buildManagedHookCommand(// printed (the script answers FIRST, then sources the endpoint file, whose syntax error would// otherwise leak out as `sh`'s status). So that branch forces 0, as the Windows wrapper does.// Every other agent's command stays byte-identical.- const exitZero = opts.fallbackStdout !== undefined ? ' || :' : ''- return `${prefix}if [ -r ${q} ]; then sh ${q}${exitZero}; else ${answer}cat >/dev/null 2>&1 || :; fi`+ const exitZero = opts.fallbackStdout !== undefined || opts.silent ? ' || :' : ''+ const quiet = opts.silent ? ' >/dev/null 2>&1' : ''+ return `${prefix}if [ -r ${q} ]; then sh ${q}${quiet}${exitZero}; else ${answer}cat >/dev/null 2>&1 || :; fi`}/**diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 6c448d2fd..86a5c2ef6 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -14,7 +14,7 @@ import {} from './agents/hook-endpoint-failover-sh'import { codexSandboxGuidanceLines } from './context-link-core'import { NODE_TOKEN_READ_SH } from './agents/node-token-sh'-import { AGENT_CONFIG, AGENT_HOOK_TARGETS, BUILTIN_AGENT_IDS } from '@shared/agents/config'+import { AGENT_CONFIG, AGENT_HOOK_TARGETS, BUILTIN_AGENT_IDS, MODEL_SWITCH_CAPABLE } from '@shared/agents/config'import { shimCommand, shimFence, windowsShimNoteLines, type ShimDialect } from '@shared/agents/shim-invocation'import { RETRYABLE } from './agents/agent-message-decide'import { FANOUT_PER_TURN, PAIR_MIN_INTERVAL_MS } from './agents/agent-message-flow'@@ -815,6 +815,11 @@ export function parseControlRequest(// pattern as context-link's get-linked-context block, distinct markers).const CC_START = '<!-- nodeterm:manage-canvas:start -->'const CC_END = '<!-- nodeterm:manage-canvas:end -->'+// Who honours `--model`, by label, from the one list that decides it (MODEL_SWITCH_CAPABLE), so the+// sentence cannot drift from the gate again (it named three agents after cursor and grok joined).+const MODEL_FLAG_AGENTS = ((labels: string[]) => `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`)(+ MODEL_SWITCH_CAPABLE.map((id) => AGENT_CONFIG[id].label)+)/** The two markers, for the SSH freshness probe, which must find the block exactly where the* merge below would. */@@ -956,8 +961,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {' not a leading `/model`.',' `--model <id>` picks the model the session launches with, instead of inheriting the',' default. Use it to keep a cheap station cheap: a node whose whole job is editing a README',- ' does not need the model you give the node rewriting a test suite. Honoured by claude, codex',- ' and copilot (and custom agents based on them); any other agent ignores it and launches',+ ` does not need the model you give the node rewriting a test suite. Honoured by ${MODEL_FLAG_AGENTS}`,+ ' (and custom agents based on them); any other agent ignores it and launches',' exactly as it would without the flag. The id is passed to the CLI as-is, so a name that',' agent does not recognise fails inside the session, not at open time — name a model you know.',...issueBindingDocLines(),@@ -1543,7 +1548,7 @@ Verbs:\`--model <id>\` decides which model the session LAUNCHES with, instead of inheriting theproject default. This is the lever for cost: a station whose job is editing a README does notneed the model you give the station rewriting a 1000-line test suite, and without this flag- every station you open runs on the same one. Honoured by claude, codex and copilot (and custom+ every station you open runs on the same one. Honoured by ${MODEL_FLAG_AGENTS} (and customagents declaring one of those as their base); every other agent IGNORES it and launches exactlyas it would have — the flag is never an error, so a mixed fan-out needs no special-casing. Theid goes to the CLI verbatim: an unknown name fails inside the session on its first turn, not atdiff --git a/src/core/context-ensure.test.ts b/src/core/context-ensure.test.tsindex dead66594..b25afabf3 100644--- a/src/core/context-ensure.test.ts+++ b/src/core/context-ensure.test.ts@@ -250,3 +250,44 @@ describe('remote (SSH-project) rehydration', () => {expect(calls).toBe(1)})})++describe('cursor rehydration: by id, on its own tail, never by cwd or from a remote node', () => {+ let cfg: string, prevCfg: string | undefined+ let cursor: ReturnType<typeof fakeTail>+ const tailForCursor = (agentId: string | undefined): ContextTail | undefined => (agentId === 'cursor' ? cursor : tailFor(agentId))+ beforeEach(() => {+ cfg = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-cursor-ensure-'))+ prevCfg = process.env.CURSOR_CONFIG_DIR+ process.env.CURSOR_CONFIG_DIR = cfg+ cursor = fakeTail()+ })+ afterEach(() => {+ if (prevCfg === undefined) delete process.env.CURSOR_CONFIG_DIR+ else process.env.CURSOR_CONFIG_DIR = prevCfg+ fs.rmSync(cfg, { recursive: true, force: true })+ })+ const writeStore = (id: string): string => {+ const dir = path.join(cfg, 'chats', 'bucket', id)+ fs.mkdirSync(dir, { recursive: true })+ const p = path.join(dir, 'store.db')+ fs.writeFileSync(p, '')+ return p+ }++ it('tracks the store for its session id on cursor’s tail only', async () => {+ const store = writeStore(SID)+ registerContextEnsureIpc({ tailFor: tailForCursor })+ await ensure({ agentId: 'cursor' })+ expect(cursor.tracked).toEqual([[SID, store]])+ expect(claude.tracked).toEqual([])+ })++ it('never adopts another chat or a claude transcript for the same cwd', async () => {+ writeStore('99999999-2222-3333-4444-555555555555') // a stranger's chat+ writeClaudeTranscript('11111111-2222-3333-4444-555555555555')+ registerContextEnsureIpc({ tailFor: tailForCursor })+ await ensure({ agentId: 'cursor' })+ expect(cursor.tracked).toEqual([])+ expect(claude.tracked).toEqual([])+ })+})diff --git a/src/core/context-ensure.ts b/src/core/context-ensure.tsindex 01c16394b..45e2a34ae 100644--- a/src/core/context-ensure.ts+++ b/src/core/context-ensure.ts@@ -27,6 +27,7 @@ import { IPC } from '../shared/ipc'import { platform } from './platform'import type { ContextTail } from './context-tail'import { locateCodex, locateGemini } from './handoff/locate'+import { locateCursorChat } from './cursor-chat'import { resolveTranscript } from './transcript-ipc'import { SESSION_ID_RE } from './transcript-reader'@@ -106,6 +107,10 @@ function localTranscriptFor(return locateCodex(q.sessionId)case 'gemini':return locateGemini(q.sessionId)+ // cursor: the chat's `store.db`, STRICTLY by id (cwd is never passed, so it cannot even order a+ // search, let alone stand in for the id). A remote node never gets here: `ensureRemote` is terminal.+ case 'cursor':+ return locateCursorChat(q.sessionId)default:return Promise.resolve(undefined)}diff --git a/src/core/context-link-render.ts b/src/core/context-link-render.tsindex 57d7a0b45..3e92f424a 100644--- a/src/core/context-link-render.ts+++ b/src/core/context-link-render.ts@@ -9,6 +9,7 @@// interpreter it needed exists only on the desktop. Moving the parsing here inverts it — the// remote side becomes a thin sh+curl client and the desktop does the reading and the parsing.import type { LinkDoc, LinkDocEntry } from './context-link-core'+import { linesFromCursor } from './cursor-chat'export type ContextLinkVerb = 'list' | 'summary' | 'transcript' | 'terminal'@@ -312,6 +313,9 @@ linesFromGrok.skipped = (buf: string): number => grokParse(buf).skippedexport function renderTranscriptLines(agent: string | undefined, buf: string): string[] {if (agent === 'gemini') return linesFromGemini(buf)if (agent === 'grok') return linesFromGrok(buf)+ // cursor's transcript text is newline-delimited message JSON built from its SQLite store+ // (`cursorTranscriptText`), not a file on disk.+ if (agent === 'cursor') return linesFromCursor(buf)const parse = agent === 'codex' ? linesFromCodex : linesFromClaudeconst lines: string[] = []for (const raw of buf.split('\n')) {diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex 0e654cf41..ed211023e 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -41,6 +41,7 @@ import {} from './context-link-render'import { hookServer } from './agents/hook-server'import { locateClaude, locateCodex, locateGemini, locateGrok } from './handoff/locate'+import { cursorTranscriptText, locateCursorChat } from './cursor-chat'export { setNodeTranscript } from './context-link-core'@@ -97,7 +98,21 @@ export interface ContextLinkDeps {// start mid-line, which only costs that one line (it fails to parse and is dropped).const REMOTE_TRANSCRIPT_MAX_BYTES = 2 * 1024 * 1024-const LINK_LOCATORS = { claude: locateClaude, codex: locateCodex, gemini: locateGemini, grok: locateGrok }+// cursor's locator takes (id, cwd?), NOT the shared (id, accountId?), wrapped so an account id can+// never be read as a cwd. It locates strictly by the whole-UUID chat id.+const LINK_LOCATORS = {+ claude: locateClaude,+ codex: locateCodex,+ gemini: locateGemini,+ grok: locateGrok,+ cursor: (sessionId: string) => locateCursorChat(sessionId)+}++/** Agents whose "transcript path" is not a text file: the path names a store the agent's own reader+ * turns into transcript text. Everything else is read as utf-8. */+const TRANSCRIPT_TEXT_READERS: Record<string, (p: string) => Promise<string | null>> = {+ cursor: cursorTranscriptText+}// The link documents, by node id — the same objects written to disk, kept in memory because they// are what authorizes a read (a node may only ever name a link inside ITS OWN document).@@ -178,6 +193,8 @@ async function fetchTranscript(node: LinkDocEntry): Promise<string | null> {? await deps.readRemoteFile(node.id, node.transcriptPath, REMOTE_TRANSCRIPT_MAX_BYTES): null}+ const read = node.agent ? TRANSCRIPT_TEXT_READERS[node.agent] : undefined+ if (read) return read(node.transcriptPath)try {return await fs.promises.readFile(node.transcriptPath, 'utf-8')} catch {diff --git a/src/core/context-tail.ts b/src/core/context-tail.tsindex c21675d50..5b79a93db 100644--- a/src/core/context-tail.ts+++ b/src/core/context-tail.ts@@ -300,6 +300,13 @@ export interface ContextTailOptions {* keeps paying for. The file is a few KB, so re-reading it whole costs nothing worth optimizing.*/wholeFile?: boolean+ /**+ * Replace the byte read entirely, for a source that is not a text file: cursor's numbers live in a+ * SQLite `store.db` (WAL), whose bytes parse as nothing. Called every tick with the key the last+ * successful read returned; a change gate lives in the source (return null when nothing changed+ * or the read failed, so the meter keeps its last value). `text` is handed to `parse` as one line.+ */+ readSource?: (path: string, lastKey: string | undefined) => Promise<{ text: string; key: string } | null>}interface Tracked {@@ -332,6 +339,8 @@ interface Tracked {* usage in it leaves the last known window alone.*/parsedWindow: number | null+ /** `readSource`'s last change key (undefined until its first successful read). */+ sourceKey?: string}export interface ContextTail {@@ -380,10 +389,24 @@ export function createContextTail(t.reading = truetry {let size = -1- try {- size = (await fs.promises.stat(t.path)).size- } catch {- // file not created yet / unreadable — skip the byte read, still reconcile below+ if (opts?.readSource) {+ const r = await opts.readSource(t.path, t.sourceKey)+ if (r) {+ t.sourceKey = r.key+ const latest = parse([r.text])+ if (latest) {+ t.used = latest.used+ t.model = latest.model ?? t.model+ t.effort = latest.effort ?? null+ t.parsedWindow = latest.window ?? t.parsedWindow+ }+ }+ } else {+ try {+ size = (await fs.promises.stat(t.path)).size+ } catch {+ // file not created yet / unreadable — skip the byte read, still reconcile below+ }}if (size >= 0) {const before = t.offsetdiff --git a/src/core/cursor-chat.real.test.ts b/src/core/cursor-chat.real.test.tsnew file mode 100644index 000000000..e394006f8--- /dev/null+++ b/src/core/cursor-chat.real.test.ts@@ -0,0 +1,23 @@+// Opt-in proof against REAL cursor-agent stores: NODETERM_CURSOR_REAL_STORES=<db>[,<db>…]. Asserts+// structure only and prints counts, never content. Skipped unless the variable is set.+import { describe, expect, it } from 'vitest'+import { parseCursorChat, readCursorStore } from './cursor-chat'++const stores = (process.env.NODETERM_CURSOR_REAL_STORES ?? '').split(',').filter(Boolean)++describe.skipIf(stores.length === 0)('real cursor stores', () => {+ for (const db of stores) {+ it(`reads ${db.split('/').slice(-3).join('/')}`, async () => {+ const s = await readCursorStore(db)+ expect(s).not.toBeNull()+ const p = parseCursorChat(s!.messages)+ const users = p.messages.filter((m) => m.role === 'user')+ const tools = p.messages.flatMap((m) => m.parts).filter((x) => x.kind === 'tool')+ console.log(`raw=${s!.messages.length} bubbles=${p.messages.length} users=${users.length} tools=${tools.length} withResult=${tools.filter((t) => t.kind === 'tool' && t.result).length} skipped=${p.skipped} model=${p.model} title=${s!.title ? 'set' : 'none'}`)+ expect(users.length).toBeGreaterThan(0)+ const all = JSON.stringify(p.messages)+ expect(all).not.toContain('<user_query>')+ expect(all).not.toContain('<user_info>')+ })+ }+})diff --git a/src/core/cursor-chat.test.ts b/src/core/cursor-chat.test.tsnew file mode 100644index 000000000..7b2d7c944--- /dev/null+++ b/src/core/cursor-chat.test.ts@@ -0,0 +1,372 @@+// Fixture-driven tests for core/cursor-chat.ts. The stores are SYNTHESIZED here (no private chat is+// committed): `buildStore` writes the layout measured on cursor-agent 2026.09.23/.28: meta key '0'+// = hex(JSON), sha256-addressed blobs, a protobuf root whose field 1 lists the message blob ids,+// with message shapes copied from a real chat that ran `echo` and a Write/Read/Grep turn.+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import crypto from 'node:crypto'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import type { DatabaseSync as Db } from 'node:sqlite'+import {+ cursorConfigDir,+ cursorContextParse,+ readCursorContextSource,+ rootTokenDetails,+ trackCursorContext,+ cursorTranscriptText,+ cursorUserText,+ linesFromCursor,+ locateCursorChat,+ parseCursorChat,+ readCursorChat,+ readCursorSessionName,+ readCursorStore,+ rootMessageIds+} from './cursor-chat'++const ID = '5667590a-e4c7-4f28-9d99-027f84c10837'+const OTHER = 'aaaaaaaa-e4c7-4f28-9d99-027f84c10837'+const CTX = '<user_info>\nOS Version: darwin\n</user_info>\n<rules>secret-rule-text</rules>'+const userMsg = (q: string) => ({+ role: 'user',+ content: [{ type: 'text', text: `<timestamp>Monday, Sep 28, 2026, 9:25 PM (UTC-4)</timestamp>\n<user_query>\n${q}\n</user_query>` }]+})+const reasoning = { type: 'redacted-reasoning', data: 'ENCRYPTED', providerOptions: { cursor: { modelName: 'composer-2.5-fast' } } }+const MESSAGES: unknown[] = [+ { role: 'system', content: 'SYSTEM PROMPT' },+ { role: 'user', content: CTX },+ userMsg('Run echo and tell me the word.'),+ {+ role: 'assistant',+ content: [reasoning, { type: 'tool-call', toolCallId: 't1', toolName: 'Shell', args: { command: 'echo fixture-ok', description: 'echo' } }],+ id: '1'+ },+ {+ role: 'tool',+ content: [+ {+ type: 'tool-result',+ toolCallId: 't1',+ toolName: 'Shell',+ result: 'Exit code: 0\n\nCommand output:\n\n```\nfixture-ok\n\n```\n\nCommand completed in 9 ms.\n\nShell state persists.',+ experimental_content: [{ type: 'text', text: 'dup' }]+ }+ ],+ id: 't1'+ },+ { role: 'assistant', content: [reasoning, { type: 'text', text: 'done' }], id: '1' },+ userMsg('Now write, read and grep a file.'),+ {+ role: 'assistant',+ content: [+ reasoning,+ { type: 'tool-call', toolCallId: 't2', toolName: 'Write', args: { path: '/w/hello.txt', contents: 'hi' } },+ { type: 'tool-call', toolCallId: 't3', toolName: 'Grep', args: { pattern: 'hi', path: '/w/hello.txt' } },+ { type: 'tool-call', toolCallId: 't4', toolName: 'Read', args: { path: '/w/missing.txt' } }+ ],+ id: '1'+ },+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: 't2', toolName: 'Write', result: 'Wrote contents to /w/hello.txt' }], id: 't2' },+ {+ role: 'tool',+ content: [{ type: 'tool-result', toolCallId: 't3', toolName: 'Grep', result: '<workspace_result workspace_path="/w">\nhello.txt\n 1:hi\n</workspace_result>' }],+ id: 't3'+ },+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: 't4', toolName: 'Read', result: 'Error: File not found' }], id: 't4' },+ { role: 'assistant', content: [{ type: 'text', text: 'Read failed, the rest worked.' }], id: '1' }+]++let Database: typeof Db+let root: string+let prevConfig: string | undefined++function varint(n: number): number[] {+ const out: number[] = []+ while (n >= 0x80) {+ out.push((n & 0x7f) | 0x80)+ n = Math.floor(n / 128)+ }+ return [...out, n]+}++/** `<root>/chats/<bucket>/<id>/store.db` with `messages` as the root's ordered field 1. */+function buildStore(bucket: string, id: string, messages: unknown[], name = 'New Agent', withRoot = true, tokens: [number, number] | null = [1, 2]): string {+ const dir = path.join(root, 'chats', bucket, id)+ fs.mkdirSync(dir, { recursive: true })+ const file = path.join(dir, 'store.db')+ const db = new Database(file)+ db.exec('PRAGMA journal_mode = WAL; CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB); CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT);')+ const put = db.prepare('INSERT INTO blobs (id, data) VALUES (?, ?)')+ const ids = messages.map((m) => {+ const data = Buffer.from(JSON.stringify(m))+ const h = crypto.createHash('sha256').update(data).digest('hex')+ put.run(h, data)+ return h+ })+ // Field 1 per message, then the noise a real root carries (5: token details, 9: a string, 26: a varint).+ const bytes: number[] = []+ for (const h of ids) bytes.push(0x0a, 0x20, ...Buffer.from(h, 'hex'))+ if (tokens) {+ const td = [0x08, ...varint(tokens[0]), 0x10, ...varint(tokens[1])]+ bytes.push(0x2a, td.length, ...td)+ }+ bytes.push(0x4a, 0x03, 0x61, 0x62, 0x63, 0xd0, 0x01, ...varint(1790645113982))+ const rootData = Buffer.from(bytes)+ const rootId = crypto.createHash('sha256').update(rootData).digest('hex')+ put.run(rootId, rootData)+ const meta = { agentId: id, latestRootBlobId: withRoot ? rootId : '', name, mode: 'default', createdAt: 1 }+ db.prepare("INSERT INTO meta (key, value) VALUES ('0', ?)").run(Buffer.from(JSON.stringify(meta)).toString('hex'))+ db.close()+ return file+}++beforeAll(async () => {+ ;({ DatabaseSync: Database } = await import('node:sqlite'))+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cursor-chat-'))+ prevConfig = process.env.CURSOR_CONFIG_DIR+ process.env.CURSOR_CONFIG_DIR = root+})+afterAll(() => {+ if (prevConfig === undefined) delete process.env.CURSOR_CONFIG_DIR+ else process.env.CURSOR_CONFIG_DIR = prevConfig+ fs.rmSync(root, { recursive: true, force: true })+})++describe('parseCursorChat', () => {+ const parsed = parseCursorChat(MESSAGES)+ it('shows typed prompts only: never the system prompt or injected context', () => {+ const users = parsed.messages.filter((m) => m.role === 'user').map((m) => m.parts)+ expect(users).toEqual([[{ kind: 'text', text: 'Run echo and tell me the word.' }], [{ kind: 'text', text: 'Now write, read and grep a file.' }]])+ const all = JSON.stringify(parsed.messages)+ for (const leak of ['SYSTEM PROMPT', 'secret-rule-text', '<user_query>', '<timestamp>', 'ENCRYPTED']) expect(all).not.toContain(leak)+ })+ it('attaches each result to its call, unwrapping the shell and search envelopes', () => {+ const tools = parsed.messages.flatMap((m) => m.parts).filter((p) => p.kind === 'tool')+ expect(tools.map((t) => [t.name, t.arg, t.result])).toEqual([+ ['Shell', 'echo fixture-ok', 'fixture-ok'],+ ['Write', '/w/hello.txt', 'Wrote contents to /w/hello.txt'],+ ['Grep', 'hi', 'hello.txt 1:hi'],+ ['Read', '/w/missing.txt', 'Error: File not found']+ ])+ })+ it('keeps assistant text, drops reasoning-only turns, and reports the newest model when stated', () => {+ expect(parsed.messages.filter((m) => m.role === 'assistant').flatMap((m) => m.parts).filter((p) => p.kind === 'text')).toHaveLength(2)+ // the newest assistant message states no model: absent, never carried from an older one+ expect(parsed.model).toBeUndefined()+ expect(parseCursorChat(MESSAGES.slice(0, 6)).model).toBe('composer-2.5-fast')+ })+ it('drops an orphan result and counts what it cannot map', () => {+ const p = parseCursorChat([{ role: 'tool', content: [{ type: 'tool-result', toolCallId: 'gone', result: 'x' }] }, 42, { role: 'weird' }])+ expect(p.messages).toEqual([])+ expect(p.skipped).toBe(2)+ })+ it('extracts the typed text from a user_query part only', () => {+ expect(cursorUserText('<timestamp>t</timestamp>\n<user_query>\nhi\nthere\n</user_query>')).toBe('hi\nthere')+ expect(cursorUserText('<system_reminder>x</system_reminder>')).toBeUndefined()+ expect(cursorUserText('<user_query>\n \n</user_query>')).toBeUndefined()+ })+})++describe('the store reader', () => {+ it('reads messages in order, the title, and rejects a malformed root', async () => {+ const file = buildStore('b1', ID, MESSAGES, 'Fixture chat')+ const s = await readCursorStore(file)+ expect(s?.title).toBe('Fixture chat')+ expect(s?.messages).toEqual(MESSAGES)+ expect(rootMessageIds(new Uint8Array([0x0a, 0x20, 1, 2]))).toBeNull() // truncated length-delimited field+ })+ it('treats the default name as no title and an empty root as an empty conversation', async () => {+ const file = buildStore('b-empty', OTHER, [], 'New Agent', false)+ expect(await readCursorStore(file)).toEqual({ messages: [] })+ })+ it('keeps the newest messages when the byte budget is exceeded', async () => {+ const file = buildStore('b-big', '11111111-e4c7-4f28-9d99-027f84c10837', [userMsg('old'), userMsg('mid'), userMsg('new')])+ const one = JSON.stringify(userMsg('new')).length+ const s = await readCursorStore(file, one + 5)+ expect(s?.messages).toEqual([userMsg('new')])+ })+ it('never parses a blob larger than the whole budget, even the newest one', async () => {+ const file = buildStore('b-huge', '22222222-e4c7-4f28-9d99-027f84c10837', [userMsg('old'), userMsg('x'.repeat(500))])+ const s = await readCursorStore(file, JSON.stringify(userMsg('old')).length + 5)+ expect(s?.messages).toEqual([userMsg('old')])+ })+ it('returns null for a file that is not a store, and never writes to a real one', async () => {+ const junk = path.join(root, 'junk.db')+ fs.writeFileSync(junk, 'not sqlite')+ expect(await readCursorStore(junk)).toBeNull()+ const file = path.join(root, 'chats', 'b1', ID, 'store.db')+ const before = fs.statSync(file).mtimeMs+ await readCursorStore(file)+ expect(fs.statSync(file).mtimeMs).toBe(before)+ })+})++describe('locateCursorChat', () => {+ it('finds a chat by its whole-UUID id, with or without the cwd bucket', async () => {+ const cwd = '/some/work/dir'+ const file = buildStore(crypto.createHash('md5').update(cwd).digest('hex'), '22222222-e4c7-4f28-9d99-027f84c10837', [])+ expect(await locateCursorChat('22222222-e4c7-4f28-9d99-027f84c10837', cwd)).toBe(file)+ expect(await locateCursorChat('22222222-e4c7-4f28-9d99-027f84c10837')).toBe(file)+ })+ it('never guesses: no id, a partial id or an unknown id is a miss (there is no cwd fallback)', async () => {+ expect(await locateCursorChat(undefined, '/some/work/dir')).toBeUndefined()+ expect(await locateCursorChat('22222222', '/some/work/dir')).toBeUndefined()+ expect(await locateCursorChat('../../etc/passwd')).toBeUndefined()+ expect(await locateCursorChat('33333333-e4c7-4f28-9d99-027f84c10837', '/some/work/dir')).toBeUndefined()+ })+ it('follows the CLI\'s config-dir rule', () => {+ expect(cursorConfigDir({ CURSOR_CONFIG_DIR: '/a' }, '/h')).toBe('/a')+ expect(cursorConfigDir({ XDG_CONFIG_HOME: '/x' }, '/h')).toBe('/x/cursor')+ expect(cursorConfigDir({}, '/h')).toBe('/h/.cursor')+ })+})++describe('readCursorChat (the chat:read-transcript leg)', () => {+ const page = { before: null, maxBytes: 256 * 1024 } as const+ it('answers a paged read with one page, the model and no older cursor', async () => {+ const r = await readCursorChat({ sessionId: ID }, { ...page })+ expect(r.found).toBe(true)+ expect(r.olderCursor).toBeNull()+ expect(r.unmatchedResults).toEqual([])+ expect(r.messages.map((m) => m.role)).toEqual(['user', 'assistant', 'assistant', 'user', 'assistant', 'assistant'])+ })+ it('answers the legacy unpaged read as {messages, found} only', async () => {+ const r = await readCursorChat({ sessionId: ID }, null)+ expect(Object.keys(r).sort()).toEqual(['found', 'messages'])+ })+ it('has nothing older to give', async () => {+ expect(await readCursorChat({ sessionId: ID }, { before: 5, maxBytes: 65536 })).toEqual({ messages: [], found: true, olderCursor: null, unmatchedResults: [] })+ })+ it('refuses a remote node BEFORE reading: unreadable, even though a same-id store exists here', async () => {+ expect(await readCursorChat({ sessionId: ID, remoteOnly: true }, { ...page })).toMatchObject({ found: false, unreadable: true })+ expect(await readCursorChat({ sessionId: ID, remoteOnly: true }, null)).toEqual({ messages: [], found: false })+ })+ it('is not found for no id or an unknown id, never another session', async () => {+ expect((await readCursorChat({}, { ...page })).found).toBe(false)+ expect((await readCursorChat({ sessionId: '44444444-e4c7-4f28-9d99-027f84c10837', cwd: '/some/work/dir' }, { ...page })).found).toBe(false)+ })+})++describe('the session name', () => {+ it('reads the chat\'s own name and answers null while it is still the default', async () => {+ expect(await readCursorSessionName(ID)).toBe('Fixture chat')+ expect(await readCursorSessionName(OTHER)).toBeNull()+ expect(await readCursorSessionName('55555555-e4c7-4f28-9d99-027f84c10837')).toBeNull()+ })+})++describe('Context Link text', () => {+ it('builds transcript text without reasoning or provider blobs, and renders display lines from it', async () => {+ const text = await cursorTranscriptText(path.join(root, 'chats', 'b1', ID, 'store.db'))+ expect(text).not.toContain('ENCRYPTED')+ expect(text).not.toContain('providerOptions')+ expect(linesFromCursor(text ?? '')).toEqual([+ 'user: Run echo and tell me the word.',+ ' $ Shell echo fixture-ok',+ ' = fixture-ok',+ 'assistant: done',+ 'user: Now write, read and grep a file.',+ ' $ Write /w/hello.txt',+ ' = Wrote contents to /w/hello.txt',+ ' $ Grep hi',+ ' = hello.txt 1:hi',+ ' $ Read /w/missing.txt',+ ' = Error: File not found',+ 'assistant: Read failed, the rest worked.'+ ])+ })+})++// ── Context meter ───────────────────────────────────────────────────────────────────────────────++describe('cursor context meter: the store numbers', () => {+ const pb = (...b: number[]) => Uint8Array.from(b)+ it('reads root field 5 (1 used, 2 max) and nothing else', () => {+ // field 1 noise, then field 5 = {1: 26794, 2: 200000}+ const td = [0x08, ...varint(26794), 0x10, ...varint(200000)]+ expect(rootTokenDetails(pb(0x0a, 0x01, 0x00, 0x2a, td.length, ...td))).toEqual({ used: 26794, max: 200000 })+ })+ it('states no meter without BOTH numbers, or on a malformed root (no guessed window)', () => {+ expect(rootTokenDetails(pb(0x2a, 0x02, 0x08, 0x05))).toBeNull() // used only+ expect(rootTokenDetails(pb(0x2a, 0x02, 0x10, 0x05))).toBeNull() // max only+ expect(rootTokenDetails(pb(0x2a, 0x04, 0x08, 0x00, 0x10, 0x05))).toBeNull() // used 0+ expect(rootTokenDetails(pb(0x2a, 0x09, 0x08))).toBeNull() // truncated+ expect(rootTokenDetails(pb(0x0a, 0x01, 0x00))).toBeNull() // no field 5+ })+ it('readCursorStore returns them with the store, and the name-only read carries them too', async () => {+ const f = buildStore('ctx1', ID.replace('5667', '1111'), MESSAGES, 'New Agent', true, [26794, 1000000])+ expect((await readCursorStore(f))?.tokens).toEqual({ used: 26794, max: 1000000 })+ expect((await readCursorStore(f, 0))?.tokens).toEqual({ used: 26794, max: 1000000 })+ expect((await readCursorStore(f, 0))?.messages).toEqual([])+ const bare = buildStore('ctx1', ID.replace('5667', '2222'), MESSAGES, 'New Agent', true, null)+ expect((await readCursorStore(bare))?.tokens).toBeUndefined()+ })+ it('window varies per session and is the store’s own max (256000 / 300000 / 1000000)', async () => {+ for (const [i, max] of [256000, 300000, 1000000].entries()) {+ const pre = ['aaaa', 'bbbb', 'cccc'][i]+ const f = buildStore('ctx2', ID.replace('5667', pre), [], 'x', true, [1000, max])+ const r = await readCursorContextSource(f, undefined)+ expect(cursorContextParse([r!.text])).toEqual({ used: 1000, window: max, model: null })+ }+ })+})++describe('cursor context meter: source gate and parse', () => {+ it('gives the tail one JSON line, then null while db + WAL are unchanged (no reopen)', async () => {+ const f = buildStore('ctx3', ID.replace('5667', '4444'), MESSAGES, 'x', true, [500, 200000])+ const first = await readCursorContextSource(f, undefined)+ expect(first && JSON.parse(first.text)).toEqual({ used: 500, max: 200000 })+ // the first read may checkpoint+delete the WAL (last connection closing), moving the key once+ const settled = await readCursorContextSource(f, first!.key)+ expect(await readCursorContextSource(f, settled?.key ?? first!.key)).toBeNull()+ // a write moves the WAL/db signature: read again, and the new used value shows+ const db = new Database(f)+ db.exec("INSERT INTO blobs (id, data) VALUES ('zz', x'00')")+ db.close()+ const again = await readCursorContextSource(f, settled?.key ?? first!.key)+ expect(again).not.toBeNull()+ })+ it('a missing or unreadable store is null (the meter keeps its last value)', async () => {+ expect(await readCursorContextSource(path.join(root, 'nope', 'store.db'), undefined)).toBeNull()+ })+ it('parse: the last valid line wins; garbage and non-positive numbers give null', () => {+ expect(cursorContextParse(['{"used":1,"max":2}', 'torn{', '{"used":5,"max":10}'])).toEqual({ used: 5, window: 10, model: null })+ expect(cursorContextParse('{"used":0,"max":10}')).toBeNull()+ expect(cursorContextParse('{"used":3}')).toBeNull()+ expect(cursorContextParse('')).toBeNull()+ })+})++describe('trackCursorContext: found by id, never by a payload path', () => {+ const tailStub = () => {+ const tracked: [string, string][] = []+ return { tracked, track: (i: string, p: string) => void tracked.push([i, p]), pathFor: (i: string) => tracked.find((t) => t[0] === i)?.[1] }+ }+ it('tracks the store under the chats root for conversation_id, ignoring transcript_path', async () => {+ const id = ID.replace('5667', '5555')+ const f = buildStore('ctx4', id, MESSAGES)+ const t = tailStub()+ expect(await trackCursorContext(t, { conversation_id: id, transcript_path: '/etc/passwd', hook_event_name: 'stop' })).toBe(id)+ expect(t.tracked).toEqual([[id, f]])+ // a repeat event is a no-op+ await trackCursorContext(t, { conversation_id: id })+ expect(t.tracked).toHaveLength(1)+ })+ it('an id with no store, a non-UUID id, or no id tracks nothing (never another chat)', async () => {+ buildStore('ctx4', ID.replace('5667', '6666'), MESSAGES)+ const t = tailStub()+ await trackCursorContext(t, { conversation_id: '12345678-e4c7-4f28-9d99-027f84c10837' })+ await trackCursorContext(t, { conversation_id: '../../etc' })+ await trackCursorContext(t, {})+ await trackCursorContext(t, null)+ expect(t.tracked).toEqual([])+ })+ it('falls back to session_id (equal to conversation_id in every capture)', async () => {+ const id = ID.replace('5667', '7777')+ buildStore('ctx4', id, MESSAGES)+ const t = tailStub()+ await trackCursorContext(t, { session_id: id })+ expect(t.tracked.map((x) => x[0])).toEqual([id])+ })+})diff --git a/src/core/cursor-chat.ts b/src/core/cursor-chat.tsnew file mode 100644index 000000000..1842462c5--- /dev/null+++ b/src/core/cursor-chat.ts@@ -0,0 +1,577 @@+// Cursor Agent CLI's conversation as the ⌘M panel's structured messages, plus the locator and the+// read-only store reader behind it.+//+// Where it lives (MEASURED on cursor-agent 2026.09.23 and 2026.09.28, macOS): the CLI keeps each+// chat in `<config>/chats/<md5(cwd)>/<chatId>/store.db`, where `<config>` is `$CURSOR_CONFIG_DIR`,+// else `$XDG_CONFIG_HOME/cursor`, else `~/.cursor` (the CLI's own `cursor-config` paths module), and+// `md5(cwd)` hashes the PHYSICAL cwd. `<chatId>` is a UUID and is the id `cursor-agent --resume` takes+// and the stream-json `session_id`. It is a SQLite database (WAL mode), read here with the built-in+// `node:sqlite` (Electron 42 ships Node 24; the repo's `engines` floor already has it), READ-ONLY:+// meta (key '0') = hex(utf8 JSON) {agentId, latestRootBlobId (hex), name, mode, createdAt, …}+// blobs (id = sha256 hex, data) content-addressed. The ROOT blob (`latestRootBlobId`) is protobuf+// (`ConversationStateStructure`); its field 1, repeated, is the ordered list of 32-byte ids of+// the model-context MESSAGES, each a JSON blob in the AI-SDK shape:+// system {role, content: string}+// user {role, content: string} harness context (`<user_info>`, rules, skills), never typed; or+// {role, content: [{type:'text', text}]} whose typed prompt is `<user_query>…</user_query>`+// beside `<timestamp>` / `<system_reminder>` parts+// assistant {role, content: [reasoning | redacted-reasoning | text | tool-call {toolCallId,+// toolName, args}], id}; `providerOptions.cursor.modelName` rides its reasoning parts+// tool {role, content: [{type:'tool-result', toolCallId, toolName, result, experimental_content}]}+// The `~/.cursor/projects/<slug>/agent-transcripts/<id>/<id>.jsonl` file the CLI ALSO writes is NOT+// used: measured, its text parts read `[REDACTED]`, it has no tool results, and it lost the user line+// of a failed turn. The store is the whole conversation.+//+// Never a cwd fallback: a chat is found ONLY by its whole-UUID id. The cwd merely picks the bucket to+// look in first. Compaction replaces the model's context, so older turns are not in the root's message+// list; they are not shown (grok has the same limit).+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import crypto from 'node:crypto'+import type { ChatMessage, ChatPart, ChatTranscriptResult } from '../shared/types'+import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'+import { CHAT_PAGE_MAX_BYTES, type ChatTranscriptPage } from '../shared/chat-page'+import { metaString, summarizeResult } from './transcript-reader'+import { opencodePageMessages } from './opencode-chat'+import { isCursorBackgroundEvent, isCursorChildToolEvent } from '../shared/agents/normalize'+import { recordRawToolEvent } from './agent-status-mirror'++type ToolPart = Extract<ChatPart, { kind: 'tool' }>+type Obj = Record<string, unknown>+const isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)++// ── Pure parsing ────────────────────────────────────────────────────────────────────────────────++/** The text a person typed in one user-message part, or undefined when the part is not a prompt+ * (`<timestamp>`, `<system_reminder>`, injected context). Exactly one wrapper newline is dropped. */+export function cursorUserText(text: string): string | undefined {+ const open = text.indexOf('<user_query>')+ if (open < 0) return undefined+ const start = open + '<user_query>'.length+ const end = text.lastIndexOf('</user_query>')+ if (end < start) return undefined+ const t = text.slice(start, end).replace(/^\n/, '').replace(/\n$/, '')+ return t.trim() ? t : undefined+}++/** Salient argument keys, in priority order (`pattern` before `path`: a grep's meaning is its pattern). */+const ARG_KEYS = ['command', 'pattern', 'glob_pattern', 'path', 'target_directory', 'target_notebook', 'query', 'search_term', 'url', 'description', 'prompt']++export function cursorToolArg(args: unknown): string {+ if (typeof args === 'string') return args.slice(0, CHAT_TOOL_ARG_MAX)+ if (!isObj(args)) return ''+ for (const k of ARG_KEYS) {+ const v = args[k]+ if (typeof v === 'string' && v) return v.slice(0, CHAT_TOOL_ARG_MAX)+ }+ const raw = JSON.stringify(args)+ return raw === '{}' ? '' : raw.slice(0, CHAT_TOOL_ARG_MAX)+}++function resultText(p: Obj): string {+ if (typeof p.result === 'string') return p.result+ if (Array.isArray(p.experimental_content)) {+ return p.experimental_content.map((c) => (isObj(c) && typeof c.text === 'string' ? c.text : '')).filter(Boolean).join('\n')+ }+ return p.result === undefined ? '' : JSON.stringify(p.result)+}++/** Shell results wrap their output in an envelope ("Exit code: 0 / Command output: / ```…```"), and+ * search results in `<workspace_result>`; a chip wants the payload, not the envelope. */+function unwrapResult(text: string): string {+ const sh = /^Exit code: (-?\d+)\n\nCommand output:\n\n```\n([\s\S]*?)\n*```/.exec(text)+ if (sh) return sh[1] === '0' ? sh[2] : `Exit code ${sh[1]}\n${sh[2]}`+ const ws = /^<workspace_result[^>]*>\n?([\s\S]*?)\n?<\/workspace_result>\s*$/.exec(text)+ return ws ? ws[1] : text+}++export interface CursorChatParse {+ messages: ChatMessage[]+ /** The newest assistant message's `providerOptions.cursor.modelName` (absent when it states none). */+ model?: string+ /** Messages/parts this reader could not map. Diagnostic only, never on the wire. */+ skipped: number+}++/** Ordered message objects (from the store, in order) → bubbles. */+export function parseCursorChat(raw: readonly unknown[]): CursorChatParse {+ const messages: ChatMessage[] = []+ const toolById = new Map<string, ToolPart>()+ let skipped = 0+ let lastAssistant: Obj | undefined+ for (const m of raw) {+ if (!isObj(m)) {+ skipped+++ continue+ }+ const parts: unknown[] = Array.isArray(m.content) ? m.content : []+ switch (m.role) {+ case 'system':+ break+ case 'user': {+ // A string user message is harness context, never typed. Typed text is a `<user_query>`.+ const texts: ChatPart[] = []+ for (const p of parts) {+ const t = isObj(p) && p.type === 'text' && typeof p.text === 'string' ? cursorUserText(p.text) : undefined+ if (t !== undefined) texts.push({ kind: 'text', text: t })+ }+ if (texts.length) messages.push({ role: 'user', parts: texts })+ break+ }+ case 'assistant': {+ lastAssistant = m+ const out: ChatPart[] = []+ if (typeof m.content === 'string' && m.content.trim()) out.push({ kind: 'text', text: m.content })+ for (const p of parts) {+ if (!isObj(p)) {+ skipped+++ continue+ }+ if (p.type === 'text') {+ if (typeof p.text === 'string' && p.text.trim()) out.push({ kind: 'text', text: p.text })+ } else if (p.type === 'tool-call') {+ const tool: ToolPart = { kind: 'tool', name: typeof p.toolName === 'string' && p.toolName ? p.toolName : 'tool', arg: cursorToolArg(p.args) }+ out.push(tool)+ if (typeof p.toolCallId === 'string') toolById.set(p.toolCallId, tool)+ } else if (p.type !== 'reasoning' && p.type !== 'redacted-reasoning') {+ skipped+++ }+ }+ if (out.length) messages.push({ role: 'assistant', parts: out })+ break+ }+ case 'tool':+ for (const p of parts) {+ if (!isObj(p) || p.type !== 'tool-result') {+ skipped+++ continue+ }+ // An orphan result (its call is outside the window) is dropped, like every other reader.+ const tool = typeof p.toolCallId === 'string' ? toolById.get(p.toolCallId) : undefined+ const s = tool ? summarizeResult(unwrapResult(resultText(p))) : ''+ if (tool && s) tool.result = s+ }+ break+ default:+ skipped+++ }+ }+ const out: CursorChatParse = { messages, skipped }+ const modelOf = (a: Obj | undefined): string | undefined => {+ for (const p of Array.isArray(a?.content) ? (a.content as unknown[]) : []) {+ const cur = isObj(p) && isObj(p.providerOptions) ? p.providerOptions.cursor : undefined+ const name = isObj(cur) ? metaString(cur.modelName) : undefined+ if (name) return name+ }+ return undefined+ }+ const model = modelOf(lastAssistant)+ if (model !== undefined) out.model = model+ return out+}++/** Newline-delimited JSON of message objects: the raw transcript text Context Link and the handoff+ * exchange, so cursor fits the same "text in, lines out" shape as every other agent. */+export function parseCursorNdjson(raw: string): unknown[] {+ const out: unknown[] = []+ for (const l of raw.split('\n')) {+ if (!l.trim()) continue+ try {+ out.push(JSON.parse(l))+ } catch {+ /* a partial line: dropped */+ }+ }+ return out+}++/** Context Link's display lines (`user: …`, `assistant: …`, ` $ tool arg`, ` = result`). */+export function linesFromCursor(raw: string): string[] {+ const res: string[] = []+ for (const m of parseCursorChat(parseCursorNdjson(raw)).messages) {+ for (const p of m.parts) {+ if (p.kind === 'text') res.push(`${m.role}: ${p.text}`)+ else if (p.kind === 'tool') {+ res.push(` $ ${p.name}${p.arg ? ` ${p.arg}` : ''}`)+ if (p.result) res.push(` = ${p.result}`)+ }+ }+ }+ return res+}++// ── Locating the store ──────────────────────────────────────────────────────────────────────────++/** A whole UUID: cursor's chat ids. A suffix or prefix of one must never match another chat. */+export const CURSOR_CHAT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++/** The CLI's own config-dir rule (`cursor-config` paths): CURSOR_CONFIG_DIR, XDG_CONFIG_HOME/cursor, ~/.cursor. */+export function cursorConfigDir(env: NodeJS.ProcessEnv = process.env, home: string = os.homedir()): string {+ if (env.CURSOR_CONFIG_DIR?.trim()) return env.CURSOR_CONFIG_DIR+ if (env.XDG_CONFIG_HOME?.trim()) return path.join(env.XDG_CONFIG_HOME, 'cursor')+ return path.join(home, '.cursor')+}++const md5 = (s: string): string => crypto.createHash('md5').update(s).digest('hex')++// A hit is cached per id (a store never moves); a miss is not, since the chat may not exist yet.+const storeCache = new Map<string, string>()++/**+ * `<chats>/<bucket>/<chatId>/store.db` for ONE chat id, or undefined. `cwd` only orders the search+ * (its md5 bucket, physical and as written, first); every bucket is then tried, because the id alone+ * is the identity and the phone path carries no cwd. No id, or one that is not a whole UUID, is a miss.+ */+export async function locateCursorChat(chatId: string | undefined, cwd?: string): Promise<string | undefined> {+ if (!chatId || !CURSOR_CHAT_ID_RE.test(chatId)) return undefined+ const cached = storeCache.get(chatId)+ if (cached) {+ try {+ if ((await fs.promises.stat(cached)).isFile()) return cached+ } catch {+ storeCache.delete(chatId)+ }+ }+ const chats = path.join(cursorConfigDir(), 'chats')+ const buckets: string[] = []+ if (cwd) {+ buckets.push(md5(path.resolve(cwd)))+ try {+ buckets.push(md5(await fs.promises.realpath(cwd)))+ } catch {+ /* no such cwd */+ }+ }+ try {+ buckets.push(...(await fs.promises.readdir(chats)))+ } catch {+ return undefined+ }+ for (const b of new Set(buckets)) {+ const p = path.join(chats, b, chatId, 'store.db')+ try {+ if ((await fs.promises.stat(p)).isFile()) {+ storeCache.set(chatId, p)+ return p+ }+ } catch {+ /* not in this bucket */+ }+ }+ return undefined+}++// ── Reading the store (read-only) ───────────────────────────────────────────────────────────────++/** Raw JSON bytes of message blobs read per call, newest first. note: a chat past this shows only+ * its newest part; a ranged/paged store read if anyone needs deeper history. */+export const CURSOR_READ_MAX_BYTES = 16 * 1024 * 1024+const DEFAULT_TITLE = 'New Agent'++/** One protobuf field: varint value `v`, or length-delimited bytes `b`. Fixed32/64 are skipped. */+type PbField = { f: number; v?: number; b?: Uint8Array }++/** The fields of one protobuf message, in order, or null when it is malformed/truncated. */+function pbFields(buf: Uint8Array): PbField[] | null {+ const out: PbField[] = []+ let i = 0+ const varint = (): number | null => {+ let r = 0+ // up to 10 bytes: the root carries a 41-bit ms timestamp+ for (let s = 0; s < 70; s += 7) {+ if (i >= buf.length) return null+ const c = buf[i++]+ r += (c & 0x7f) * 2 ** s+ if (c < 0x80) return r+ }+ return null+ }+ while (i < buf.length) {+ const tag = varint()+ if (tag === null) return null+ const wire = tag & 7+ const f = tag >>> 3+ if (wire === 0) {+ const v = varint()+ if (v === null) return null+ out.push({ f, v })+ } else if (wire === 1 || wire === 5) i += wire === 1 ? 8 : 4+ else if (wire === 2) {+ const len = varint()+ if (len === null || i + len > buf.length) return null+ out.push({ f, b: buf.subarray(i, i + len) })+ i += len+ } else return null+ }+ return out+}++/** The ids in the root blob's field 1 (`root_prompt_messages_json`, repeated bytes), in order. */+export function rootMessageIds(buf: Uint8Array): string[] | null {+ const fields = pbFields(buf)+ if (!fields) return null+ return fields.filter((x) => x.f === 1 && x.b?.length === 32).map((x) => Buffer.from(x.b as Uint8Array).toString('hex'))+}++/**+ * The agent's own context numbers: root field 5 (`token_details`) = {1 used_tokens, 2 max_tokens}.+ * MEASURED (cursor-agent 2026.09.28): matches the TUI's `/context`; `max` varies per session+ * (200000 / 256000 / 300000 / 1000000), so it is read, never inferred from the model. Null unless+ * BOTH are present and usable (no trustworthy denominator, no meter: CLAUDE.md rule 6).+ */+export function rootTokenDetails(buf: Uint8Array): { used: number; max: number } | null {+ const td = pbFields(buf)?.find((x) => x.f === 5 && x.b)?.b+ const inner = td && pbFields(td)+ if (!inner) return null+ const used = inner.find((x) => x.f === 1 && x.v !== undefined)?.v+ const max = inner.find((x) => x.f === 2 && x.v !== undefined)?.v+ return used !== undefined && used > 0 && max !== undefined && max > 0 ? { used, max } : null+}++export interface CursorStore {+ /** Message objects, oldest first. */+ messages: unknown[]+ /** The chat's own name; undefined until cursor names it (its default is "New Agent"). */+ title?: string+ /** The root's `token_details` (see `rootTokenDetails`); absent when it states none. */+ tokens?: { used: number; max: number }+}++const asText = (d: unknown): string => (typeof d === 'string' ? d : Buffer.from(d as Uint8Array).toString('utf8'))++/** One consistent read of a store; null when it cannot be read (no node:sqlite, locked, corrupt). */+export async function readCursorStore(dbPath: string, maxBytes: number = CURSOR_READ_MAX_BYTES): Promise<CursorStore | null> {+ let db: import('node:sqlite').DatabaseSync | undefined+ try {+ const { DatabaseSync } = await import('node:sqlite')+ db = new DatabaseSync(dbPath, { readOnly: true, timeout: 2000 })+ db.exec('BEGIN')+ const row = db.prepare("SELECT value FROM meta WHERE key = '0'").get() as { value?: string } | undefined+ const meta: unknown = row?.value ? JSON.parse(Buffer.from(row.value, 'hex').toString('utf8')) : {}+ const m = isObj(meta) ? meta : {}+ const name = typeof m.name === 'string' ? m.name.trim() : ''+ const store: CursorStore = { messages: [] }+ if (name && name !== DEFAULT_TITLE) store.title = name.slice(0, 200)+ const rootId = typeof m.latestRootBlobId === 'string' ? m.latestRootBlobId : ''+ if (!rootId) return store+ const blob = db.prepare('SELECT data FROM blobs WHERE id = ?')+ const size = db.prepare('SELECT length(data) AS n FROM blobs WHERE id = ?')+ const root = blob.get(rootId) as { data?: Uint8Array } | undefined+ const tokens = root?.data ? rootTokenDetails(root.data) : null+ if (tokens) store.tokens = tokens+ if (maxBytes <= 0) return store // maxBytes 0 = the name and the token numbers, no messages+ const ids = root?.data ? rootMessageIds(root.data) : null+ if (!ids) return null+ let total = 0+ const newestFirst: unknown[] = []+ for (let k = ids.length - 1; k >= 0; k--) {+ const n = (size.get(ids[k]) as { n?: number } | undefined)?.n+ if (n === undefined) continue // a message this machine does not hold+ if (total + n > maxBytes && newestFirst.length) break+ if (n > maxBytes) continue // over the cap on its own: never parsed, even as the newest+ total += n+ try {+ newestFirst.push(JSON.parse(asText((blob.get(ids[k]) as { data: unknown }).data)))+ } catch {+ /* not a JSON message blob */+ }+ }+ store.messages = newestFirst.reverse()+ return store+ } catch {+ return null+ } finally {+ try {+ db?.close()+ } catch {+ /* already closed */+ }+ }+}++/** The transcript text Context Link and the handoff read: one message per line, without the fields+ * that only bloat it (`providerOptions` carries encrypted reasoning, `experimental_content` repeats `result`). */+export async function cursorTranscriptText(dbPath: string): Promise<string | null> {+ const s = await readCursorStore(dbPath)+ if (!s) return null+ return s.messages+ .map((m) => {+ if (!isObj(m)) return ''+ const { providerOptions: _p, ...rest } = m+ if (Array.isArray(rest.content)) {+ rest.content = rest.content+ .filter((c) => !(isObj(c) && (c.type === 'reasoning' || c.type === 'redacted-reasoning')))+ .map((c) => {+ if (!isObj(c)) return c+ const { providerOptions: _q, experimental_content: _e, ...keep } = c+ return keep+ })+ }+ return JSON.stringify(rest)+ })+ .filter(Boolean)+ .join('\n')+}++/** The session's own name for `TITLE_READ_CAPABLE`, or null. By id only, local only: a remote node's+ * chat is on its host, and a whole-UUID id cannot name a chat on this machine by accident. */+export async function readCursorSessionName(sessionId: string): Promise<string | null> {+ const p = await locateCursorChat(sessionId)+ if (!p) return null+ return (await readCursorStore(p, 0))?.title ?? null+}++/**+ * `chat:read-transcript` for a cursor node. Refusals: a REMOTE node is refused before anything is+ * read (its chat is in the HOST's store; there is no remote leg yet), and a local failure is a+ * plain not-found like copilot's, so `unreadable` can only mean "remote" (`CHAT_LOCAL_ONLY`). One+ * page always (`olderCursor: null`): a store has no byte offsets to page by.+ */+export async function readCursorChat(+ q: { sessionId?: string; cwd?: string; remoteOnly?: boolean },+ page: ChatTranscriptPage | null+): Promise<ChatTranscriptResult> {+ const notFound = (): ChatTranscriptResult =>+ page ? { messages: [], found: false, olderCursor: null, unmatchedResults: [] } : { messages: [], found: false }+ if (q.remoteOnly) return page ? { ...notFound(), unreadable: true } : notFound()+ if (page && page.before !== null) return { messages: [], found: true, olderCursor: null, unmatchedResults: [] }+ const p = await locateCursorChat(q.sessionId, q.cwd)+ if (!p) return notFound()+ // note: no change gate/cache (opencode's export needs one at 1.5 s; this read is milliseconds).+ const store = await readCursorStore(p)+ if (!store) return notFound()+ const parsed = parseCursorChat(store.messages)+ const messages = opencodePageMessages(parsed.messages, page ? page.maxBytes : CHAT_PAGE_MAX_BYTES)+ if (!page) return { messages, found: true }+ return { messages, found: true, olderCursor: null, unmatchedResults: [], ...(parsed.model !== undefined ? { model: parsed.model } : {}) }+}++// ── Context meter (`USAGE_CAPABLE`) ─────────────────────────────────────────────────────────────++/**+ * `ContextTail.readSource` for a cursor `store.db`: the numbers via the ONE store reader+ * (`readCursorStore`, messages skipped), handed to `cursorContextParse` as a one-line JSON. The+ * change gate is the db + `-wal` (mtime, size): WAL mode leaves `store.db` itself untouched between+ * checkpoints, and the tail polls at 1 Hz, so an unchanged store costs two stats, not an open.+ * note: polled by the shared tail rather than a bespoke hook-triggered reader; hook events only+ * (re)track the store path. A stat-gated poll is cheap enough, and the meter needs no new timer.+ */+export async function readCursorContextSource(dbPath: string, lastKey: string | undefined): Promise<{ text: string; key: string } | null> {+ let key = ''+ for (const f of [dbPath, `${dbPath}-wal`]) {+ try {+ const st = await fs.promises.stat(f)+ key += `${st.mtimeMs}:${st.size};`+ } catch {+ key += '-;' // no WAL file: a checkpointed store+ }+ }+ if (key === lastKey) return null+ const tokens = (await readCursorStore(dbPath, 0))?.tokens+ return tokens ? { text: JSON.stringify(tokens), key } : null+}++/** `ContextTail` parse for cursor: the last `{used,max}` line. `window` is the store's own `max`. */+export function cursorContextParse(text: string | string[]): { used: number; window: number; model: null } | null {+ const lines = Array.isArray(text) ? text : text.split('\n')+ for (let i = lines.length - 1; i >= 0; i--) {+ try {+ const o: unknown = JSON.parse(lines[i])+ if (isObj(o) && typeof o.used === 'number' && typeof o.max === 'number' && o.used > 0 && o.max > 0) {+ return { used: o.used, window: o.max, model: null }+ }+ } catch {+ /* not a JSON line */+ }+ }+ return null+}++/**+ * One hook event of a cursor node → its context tail. The store is found STRICTLY by the event's+ * `conversation_id` (`locateCursorChat`, under the chats root only); the payload's `transcript_path`+ * names the redacted agent-transcripts jsonl and is never read, so there is no payload path to jail+ * and a forged POST cannot aim a read anywhere. Shared by both shells (invariant 11). A repeat event+ * for a tracked session is a no-op, and a chat cursor has not written yet is retried by the next one.+ * Returns the session id (the shells record it for tail release), undefined when the payload has none.+ */+export async function trackCursorContext(+ tail: { track(id: string, path: string): void; pathFor(id: string): string | undefined },+ payload: unknown,+ live: () => boolean = () => true+): Promise<string | undefined> {+ const p = isObj(payload) ? payload : {}+ const id = typeof p.conversation_id === 'string' ? p.conversation_id : typeof p.session_id === 'string' ? p.session_id : undefined+ if (!id || tail.pathFor(id)) return id+ const cwd = Array.isArray(p.workspace_roots) && typeof p.workspace_roots[0] === 'string' ? p.workspace_roots[0] : undefined+ const path = await locateCursorChat(id, cwd)+ if (path && live()) tail.track(id, path)+ return id+}++/** nodeId -> a token for its current life. `releaseCursorRaw` drops it, so a store lookup that was+ * already in flight when the node was destroyed or recycled finds a different token when it lands+ * and tracks nothing (it used to restart a 1 Hz poll on the old store, review 2026-10-03). */+const nodeEpoch = new Map<string, object>()++/** Both shells' `releaseNodeTails` (pty:destroy / pty:recycle): fence `applyCursorRaw`'s pending lookups. */+export function releaseCursorRaw(nodeId: string): void {+ nodeEpoch.delete(nodeId)+}++/**+ * The ONE cursor step both shells' raw hook listeners run (`src/main/index.ts`,+ * `src/server/agent-status.ts`), so the two cannot drift (CLAUDE.md rules 10 and 11). It used to be+ * written inline in each shell as two `agentId === 'cursor'` branches, and the first one returned,+ * so the second (the subagent tracker) never ran in either shell: a subagent card started from the+ * normalizer but never ended (review 2026-10-02).+ *+ * Order matters:+ * 1. The subagent tracker sees EVERY event, child ones included (they feed its live tail) and remote+ * ones (its end emit reads no local file).+ * 2. A remote node is not metered from this machine's disk.+ * 3. A child's tool event (`isCursorChildToolEvent`: generation_id === conversation_id) never+ * re-points the node at the child's chat once the node has a session of its own. Before this it+ * replaced the node's session id (the resume id) and leaked a 1 Hz tail on the child store.+ * A node with no session yet still tracks it, so a headless run whose own tool events look like+ * a child's keeps its meter.+ */+export function applyCursorRaw(+ deps: {+ tail: { track(id: string, path: string): void; pathFor(id: string): string | undefined }+ subagents: { onRaw(agentId: 'cursor', nodeId: string | undefined, payload: unknown): void }+ nodeSession: Map<string, string>+ isRemote: (nodeId: string) => boolean+ },+ nodeId: string | undefined,+ payload: unknown+): void {+ deps.subagents.onRaw('cursor', nodeId, payload)+ // A background agent's lifecycle event is not this node's: no Stop activity, no meter re-point.+ if (isCursorBackgroundEvent(payload)) return+ // The phone's "what it is doing now" line, remote nodes included (it needs no file). Translated to+ // the claude-shaped names `recordRawToolEvent` gates on, as grok's branch does; a child's tool+ // call is not the parent's activity.+ if (nodeId && isObj(payload)) {+ const ev = payload.hook_event_name+ if (ev === 'preToolUse' && typeof payload.tool_name === 'string' && !isCursorChildToolEvent(payload)) {+ recordRawToolEvent(nodeId, { hook_event_name: 'PreToolUse', tool_name: payload.tool_name, tool_input: payload.tool_input })+ } else if (ev === 'stop' || ev === 'sessionEnd') {+ recordRawToolEvent(nodeId, { hook_event_name: 'Stop' })+ }+ }+ if (!nodeId || deps.isRemote(nodeId)) return+ const current = deps.nodeSession.get(nodeId)+ if (current && isCursorChildToolEvent(payload)) return+ let epoch = nodeEpoch.get(nodeId)+ if (!epoch) nodeEpoch.set(nodeId, (epoch = {}))+ const live = (): boolean => nodeEpoch.get(nodeId) === epoch+ void trackCursorContext(deps.tail, payload, live).then((id) => {+ if (!id || !live()) return+ // A slower scan for an older event must not overwrite a newer association.+ const now = deps.nodeSession.get(nodeId)+ if (now && now !== id && isCursorChildToolEvent(payload)) return+ deps.nodeSession.set(nodeId, id)+ })+}diff --git a/src/core/cursor-cli.test.ts b/src/core/cursor-cli.test.tsnew file mode 100644index 000000000..afeab0d74--- /dev/null+++ b/src/core/cursor-cli.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest'+import { cursorCapsFromRunner } from './cursor-cli'++describe('cursorCapsFromRunner', () => {+ it('asks `models` and parses the answer', async () => {+ const asked: string[][] = []+ const caps = await cursorCapsFromRunner(async (a) => (asked.push(a), 'Available models\n\nauto - Auto\n'))+ expect(asked).toEqual([['models']])+ expect(caps.models).toEqual([{ id: 'auto', name: 'Auto' }])+ })+ it('fails open to no models when the CLI fails', async () => {+ expect((await cursorCapsFromRunner(async () => null)).models).toEqual([])+ })+})diff --git a/src/core/cursor-cli.ts b/src/core/cursor-cli.tsnew file mode 100644index 000000000..a864fc304--- /dev/null+++ b/src/core/cursor-cli.ts@@ -0,0 +1,64 @@+// Probe for the LOCAL cursor-agent CLI: its model catalogue only (`cursor-agent models`).+// Session-id minting needs no probe (see UNCONDITIONAL_SESSION_ID_CAPABLE in shared/agents/config).+// Rule 9: cursor's own probe, never claude's or grok's. The list is account-scoped and network-backed,+// so every failure (missing CLI, offline, timeout, unparseable) fails open to [] = no model switching.+import { execFile } from 'child_process'+import { promisify } from 'util'+import { IPC } from '../shared/ipc'+import { directExecutableInvocation } from './exec-path'+import { findInLoginPath } from './pty-manager'+import { platform } from './platform'+import { cursorModelsFrom } from '../shared/agents/model-gateway'+import { UNKNOWN_CURSOR_CLI_CAPS, type CursorCliCaps } from '../shared/types'++const execFileP = promisify(execFile)+// The call goes to the network; ~1.5 s measured, so leave room without hanging boot.+const PROBE_TIMEOUT_MS = 10_000++/** Pure composition around an injected runner, so the wiring is testable. Never rejects. */+export async function cursorCapsFromRunner(+ run: (args: string[]) => Promise<string | null>+): Promise<CursorCliCaps> {+ return { models: cursorModelsFrom(await run(['models'])) }+}++export function probeCursorCliAt(bin: string): Promise<CursorCliCaps> {+ return cursorCapsFromRunner(async (args) => {+ try {+ const invocation = directExecutableInvocation(bin, args)+ if (!invocation) return null+ const { stdout } = await execFileP(invocation.executable, invocation.args, {+ ...invocation.options,+ timeout: PROBE_TIMEOUT_MS+ })+ return stdout+ } catch {+ return null+ }+ })+}++let cached: Promise<CursorCliCaps> | null = null++async function probe(): Promise<CursorCliCaps> {+ const bin = await findInLoginPath('cursor-agent').catch(() => null)+ return bin ? probeCursorCliAt(bin) : UNKNOWN_CURSOR_CLI_CAPS+}++/** The local cursor-agent's catalogue. Memoized for the process lifetime (note: an account+ * switch or a model shipped mid-session shows after a restart). A failed probe is NOT kept, so the+ * next ask retries. Never rejects. */+export function cursorCliCaps(): Promise<CursorCliCaps> {+ if (!cached) {+ cached = probe().then((c) => {+ if (!c.models.length) cached = null+ return c+ })+ }+ return cached+}++/** Both shells call this (Invariant 11), or the picker works on one surface only. */+export function registerCursorCliIpc(): void {+ platform().handle(IPC.cursorCliCaps, () => cursorCliCaps())+}diff --git a/src/core/cursor-raw.test.ts b/src/core/cursor-raw.test.tsnew file mode 100644index 000000000..8b969dc66--- /dev/null+++ b/src/core/cursor-raw.test.ts@@ -0,0 +1,181 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import fs, { readFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { applyCursorRaw, releaseCursorRaw } from './cursor-chat'+import { createCursorSubagentTracker } from './cursor-subagents'+import type { SubagentTail } from './subagent-tail'+import type { NormalizedAgentEvent } from '../shared/agents/normalize'+import { _inboxSnapshot, _resetForTest } from './agent-status-mirror'++// Review 2026-10-02: both shells returned from their first cursor branch, so the subagent tracker+// below it never ran, and a child's tool events re-pointed the node's session (and leaked a tail).+// This replays the captured interactive subagent turn through the ONE step both shells now call.+const fx = JSON.parse(+ readFileSync(path.join(__dirname, '../shared/agents/__fixtures__/cursor/subagent-payloads.json'), 'utf8')+) as { events: Record<string, unknown>[] }+const CONFIG = '/cfg/.cursor'+const ev = fx.events.map((e) =>+ typeof e.transcript_path === 'string'+ ? { ...e, transcript_path: (e.transcript_path as string).replace('<home>/.cursor', CONFIG) }+ : e+)+const PARENT = ev[0].conversation_id as string+const CHILD = ev.find((e) => e.tool_name === 'Read')!.conversation_id as string++function rig(isRemote = false) {+ const emitted: NormalizedAgentEvent[] = []+ const tracked: string[] = []+ const finished: string[] = []+ const tail: SubagentTail = { track: () => {}, trackFile: () => {}, finish: (id) => void finished.push(id) }+ const subagents = createCursorSubagentTracker({ tail, emit: (e) => void emitted.push(e), configDir: () => CONFIG })+ const nodeSession = new Map<string, string>()+ const ctx = { track: (id: string) => void tracked.push(id), pathFor: () => undefined }+ const deps = { tail: ctx, subagents, nodeSession, isRemote: () => isRemote }+ return { emitted, tracked, finished, nodeSession, run: (p: Record<string, unknown>) => applyCursorRaw(deps, 'n1', p) }+}++const settle = () => new Promise((r) => setTimeout(r, 20))++describe('applyCursorRaw over the captured subagent turn', () => {+ it('ends the subagent card on the parent stop (the tracker is reachable)', async () => {+ const r = rig()+ for (const e of ev) {+ r.run(e)+ await settle()+ }+ const kinds = r.emitted.map((e) => e.kind)+ expect(kinds).toContain('subagent-end')+ })++ it("keeps the node on the PARENT chat: a child's tool events never re-point it", async () => {+ const r = rig()+ for (const e of ev) {+ r.run(e)+ await settle()+ expect(r.nodeSession.get('n1')).toBe(PARENT)+ }+ expect(r.nodeSession.get('n1')).not.toBe(CHILD)+ })++ it('a remote node still gets subagent cards but no local meter or session association', async () => {+ const r = rig(true)+ for (const e of ev) {+ r.run(e)+ await settle()+ }+ expect(r.emitted.map((e) => e.kind)).toContain('subagent-end')+ expect(r.nodeSession.size).toBe(0)+ })+})++describe("applyCursorRaw feeds the phone's activity line", () => {+ const activity = () => _inboxSnapshot().nodes['n1']?.activity+ it('a parent tool call is the activity, a child one is not, and stop clears it', () => {+ _resetForTest()+ const r = rig(true) // remote too: the line needs no file+ r.run({ hook_event_name: 'preToolUse', conversation_id: PARENT, generation_id: 'g1', tool_name: 'Shell', tool_input: { command: 'npm test' } })+ expect(activity()).toBe('Running npm test')+ r.run(ev.find((e) => e.hook_event_name === 'preToolUse' && e.tool_name === 'Read')!) // the child's Read+ expect(activity()).toBe('Running npm test')+ r.run({ hook_event_name: 'stop', conversation_id: PARENT, status: 'completed' })+ expect(activity()).toBeUndefined()+ _resetForTest()+ })+})++// Review 2026-10-03 (M2): a background agent's sessionEnd (normalizeCursor already drops it) ended+// every open parent Task card and handed its own id over as the parent's session.+describe("a background agent's lifecycle event is not the parent's", () => {+ const BG = '55555555-5555-4555-8555-555555555555'+ const task = (id: string) => ({ hook_event_name: 'preToolUse', conversation_id: PARENT, generation_id: 'turn', tool_name: 'Task', tool_use_id: id })++ it('keeps both cards open and the parent session, then the parent stop ends them', async () => {+ const r = rig()+ r.run(task('task-1'))+ r.run(task('task-2'))+ await settle()+ r.run({ hook_event_name: 'sessionEnd', conversation_id: BG, generation_id: BG, is_background_agent: true })+ r.run({ hook_event_name: 'stop', conversation_id: BG, generation_id: 'g', is_background_agent: true })+ await settle()+ expect(r.emitted.filter((e) => e.kind === 'subagent-end')).toEqual([])+ expect(r.finished).toEqual([])+ expect(r.nodeSession.get('n1')).toBe(PARENT)+ r.run({ hook_event_name: 'stop', conversation_id: PARENT, generation_id: 'turn', status: 'completed' })+ const ends = r.emitted.filter((e) => e.kind === 'subagent-end')+ expect(ends.map((e) => e.toolUseId)).toEqual(['task-1', 'task-2'])+ expect(ends.every((e) => e.sessionId === PARENT)).toBe(true)+ })++ it("a claimed child's own stop does not end the parent's cards", () => {+ const r = rig(true)+ // The captured turn up to (not including) the parent's stop: the child is claimed by then.+ const parentStop = ev.findIndex((e) => e.hook_event_name === 'stop' && e.conversation_id === PARENT)+ for (const e of ev.slice(0, parentStop)) r.run(e)+ r.run({ hook_event_name: 'stop', conversation_id: CHILD, generation_id: 'g', status: 'completed' })+ expect(r.emitted.filter((e) => e.kind === 'subagent-end')).toEqual([])+ })+})++// Review 2026-10-03 (M1): the store lookup is async; a node destroyed or recycled while it was in+// flight got its 1 Hz meter poll (and session association) re-created when it landed.+describe('a release fences a store lookup already in flight', () => {+ const ID = '22222222-2222-4222-8222-222222222222'+ let cfg = ''+ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllEnvs()+ if (cfg) fs.rmSync(cfg, { recursive: true, force: true })+ })++ it('tracks nothing and associates nothing after releaseCursorRaw', async () => {+ cfg = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-cursor-fence-'))+ vi.stubEnv('CURSOR_CONFIG_DIR', cfg)+ const db = path.join(cfg, 'chats', 'bucket', ID, 'store.db')+ fs.mkdirSync(path.dirname(db), { recursive: true })+ fs.writeFileSync(db, '')+ const realStat = fs.promises.stat.bind(fs.promises)+ let release!: () => void+ const gate = new Promise<void>((r) => (release = r))+ let entered!: () => void+ const sawStat = new Promise<void>((r) => (entered = r))+ vi.spyOn(fs.promises, 'stat').mockImplementation((async (p: fs.PathLike) => {+ if (String(p) === db) {+ entered()+ await gate+ }+ return realStat(p)+ }) as typeof fs.promises.stat)+ const r = rig()+ r.run({ hook_event_name: 'beforeSubmitPrompt', conversation_id: ID, generation_id: 'turn' })+ await sawStat+ releaseCursorRaw('n1') // pty:destroy / pty:recycle+ release()+ await settle()+ expect(r.tracked).toEqual([])+ expect(r.nodeSession.size).toBe(0)+ // The node's next life is metered again.+ r.run({ hook_event_name: 'beforeSubmitPrompt', conversation_id: ID, generation_id: 'turn2' })+ await settle()+ expect(r.tracked).toEqual([ID])+ expect(r.nodeSession.get('n1')).toBe(ID)+ releaseCursorRaw('n1')+ })+})++describe('both shells run the shared step and nothing else for cursor', () => {+ it('calls applyCursorRaw and has no second, unreachable cursor branch', () => {+ for (const f of ['src/main/index.ts', 'src/server/agent-status.ts']) {+ const src = readFileSync(path.join(__dirname, '../..', f), 'utf8').replace(/\r\n/g, '\n')+ expect(src, f).toContain('applyCursorRaw(')+ expect(src.match(/agentId === 'cursor'\) \{/g)?.length ?? 0, f).toBe(1)+ expect(src, f).not.toContain('cursorSubagents.onRaw(')+ // Parity for the two fixes the desktop has no harness for (the server's are behavioural tests):+ // the claude branch ignores Cursor's claude.sh payloads, and a closed node releases its Tasks.+ expect(src, f).toContain('if (isCursorPayload(payload)) return')+ expect(src, f).toContain('cursorSubagents.release(nodeId)')+ expect(src, f).toContain('releaseCursorRaw(nodeId)')+ expect(src, f).toMatch(/releaseCursorNode\??\.?\(nodeId\)/)+ }+ })+})diff --git a/src/core/cursor-subagents.test.ts b/src/core/cursor-subagents.test.tsnew file mode 100644index 000000000..65cc76b7e--- /dev/null+++ b/src/core/cursor-subagents.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import path from 'path'+import { createCursorSubagentFormatter, createCursorSubagentTracker, cursorChildTranscript } from './cursor-subagents'+import type { SubagentTail } from './subagent-tail'+import type { NormalizedAgentEvent } from '../shared/agents/normalize'++// Interactive TUI capture, cursor-agent 2026.10.01 (see the fixture's _provenance).+const fx = JSON.parse(+ readFileSync(path.join(__dirname, '../shared/agents/__fixtures__/cursor/subagent-payloads.json'), 'utf8')+) as { events: Record<string, unknown>[]; childTranscript: string[] }+const CONFIG = '/cfg/.cursor'+// The fixture's home is redacted to `<home>`; point it at the fake config dir.+const ev = fx.events.map((e) =>+ typeof e.transcript_path === 'string'+ ? { ...e, transcript_path: (e.transcript_path as string).replace('<home>/.cursor', CONFIG) }+ : e+)+const find = (name: string, tool?: string) => ev.find((e) => e.hook_event_name === name && (!tool || e.tool_name === tool))!+const TASK = find('preToolUse', 'Task')+const CHILD_PRE = find('preToolUse', 'Read')+const CHILD_POST = find('postToolUse', 'Read')+const STOP = find('stop')+const TASK_ID = TASK.tool_use_id as string+const CHILD = CHILD_POST.conversation_id as string++function rig() {+ const tracked: [string, string | undefined][] = []+ const finished: string[] = []+ const emitted: NormalizedAgentEvent[] = []+ const tail: SubagentTail = {+ track: () => {},+ trackFile: (id, file) => void tracked.push([id, file]),+ finish: (id) => void finished.push(id)+ }+ const t = createCursorSubagentTracker({ tail, emit: (e) => void emitted.push(e), configDir: () => CONFIG })+ const raw = (p: Record<string, unknown>, node = 'n1') => t.onRaw('cursor', node, p)+ return { tracked, finished, emitted, raw, release: (node: string) => t.release(node) }+}++describe('createCursorSubagentTracker over the captured turn', () => {+ it('tails the child from its first path-bearing event, then ends the card on the parent stop', () => {+ const r = rig()+ r.raw(TASK)+ r.raw(CHILD_PRE) // no transcript_path yet (measured null)+ expect(r.tracked).toEqual([])+ r.raw(CHILD_POST)+ expect(r.tracked).toEqual([[TASK_ID, `${CONFIG}/projects/private-tmp-ntc-f1-proj/agent-transcripts/${CHILD}/${CHILD}.jsonl`]])+ r.raw(CHILD_POST) // a claimed child is not re-tracked+ expect(r.tracked).toHaveLength(1)+ r.raw(STOP)+ expect(r.emitted).toEqual([+ { nodeId: 'n1', agentId: 'cursor', sessionId: STOP.conversation_id, kind: 'subagent-end', toolUseId: TASK_ID }+ ])+ expect(r.finished).toEqual([TASK_ID])+ r.raw(STOP) // a second stop has nothing left to end+ expect(r.emitted).toHaveLength(1)+ })++ it('note: two unclaimed Tasks make the child ambiguous, so no tail (cards still end on stop)', () => {+ const r = rig()+ r.raw(TASK)+ r.raw({ ...TASK, tool_use_id: 'tool_other' })+ r.raw(CHILD_POST)+ expect(r.tracked).toEqual([])+ r.raw(STOP)+ expect(r.emitted.map((e) => e.toolUseId)).toEqual([TASK_ID, 'tool_other'])+ })++ it('release (node closed or recycled mid-Task) finishes the child tail and forgets the node', () => {+ const r = rig()+ r.raw(TASK)+ r.raw(CHILD_POST)+ r.raw(TASK, 'n2')+ r.release('n1')+ expect(r.finished).toEqual([TASK_ID])+ r.raw(STOP) // the entry is gone: a late stop ends nothing for n1+ expect(r.emitted).toEqual([])+ r.release('n1') // idempotent+ expect(r.finished).toEqual([TASK_ID])+ r.raw(STOP, 'n2') // other nodes are untouched+ expect(r.emitted.map((e) => e.nodeId)).toEqual(['n2'])+ })++ it('keeps nodes apart and ignores events with no node', () => {+ const r = rig()+ r.raw(TASK, 'a')+ r.raw(STOP, 'b')+ expect(r.emitted).toEqual([])+ r.raw(STOP, undefined as unknown as string)+ r.raw(STOP, 'a')+ expect(r.emitted).toHaveLength(1)+ })+})++describe('cursorChildTranscript (the path comes from a hook POST)', () => {+ const ok = `${CONFIG}/projects/x/agent-transcripts/${CHILD}/${CHILD}.jsonl`+ it('accepts only the child\'s own file under <config>/projects', () => {+ expect(cursorChildTranscript(ok, CHILD, CONFIG)).toBe(ok)+ expect(cursorChildTranscript('/etc/passwd', CHILD, CONFIG)).toBeUndefined()+ expect(cursorChildTranscript(`${CONFIG}/projects/../../${CHILD}/${CHILD}.jsonl`, CHILD, CONFIG)).toBeUndefined()+ expect(cursorChildTranscript(ok.replace(`${CHILD}.jsonl`, 'other.jsonl'), CHILD, CONFIG)).toBeUndefined()+ expect(cursorChildTranscript(ok, 'not-a-uuid', CONFIG)).toBeUndefined()+ expect(cursorChildTranscript(null, CHILD, CONFIG)).toBeUndefined()+ expect(cursorChildTranscript('relative/x.jsonl', CHILD, CONFIG)).toBeUndefined()+ })+})++describe('createCursorSubagentFormatter', () => {+ it('renders the captured child transcript: task, tool call, answer, end; [REDACTED] dropped', () => {+ const out = createCursorSubagentFormatter()(fx.childTranscript.join('\n'))+ const lines = out.split('\n')+ expect(lines[0]).toMatch(/^You are the probe-reader agent/)+ expect(out).toContain('$ Read <workspace>/config.txt')+ expect(out).toContain('a=1')+ expect(out).not.toContain('[REDACTED]')+ expect(out).not.toContain('<timestamp>')+ expect(lines[lines.length - 1]).toBe('✓ done')+ })++ it('skips torn or foreign lines and names a failed end', () => {+ const f = createCursorSubagentFormatter()+ expect(f('{"role":"assistant"')).toBe('')+ expect(f('[1,2]\n"x"')).toBe('')+ expect(f('{"type":"turn_ended","status":"error"}')).toBe('✗ error')+ })+})diff --git a/src/core/cursor-subagents.ts b/src/core/cursor-subagents.tsnew file mode 100644index 000000000..86c833d7a--- /dev/null+++ b/src/core/cursor-subagents.ts@@ -0,0 +1,137 @@+// Cursor subagent cards: the END the hooks never send, and the child's live activity.+//+// MEASURED on cursor-agent 2026.10.01 (interactive TUI, three runs: two built-in `explore`+// children, one custom `.cursor/agents` child; `__fixtures__/cursor/subagent-payloads.json`):+// - `subagentStart` / `subagentStop` never fired, although subscribed.+// - the parent's `Task` tool gets a `preToolUse` (the card's start, in normalizeCursor) and NO+// `postToolUse`. The child ran synchronously every time: all its events landed before the+// parent's `stop`. So the parent's `stop` (or `sessionEnd`) is the end, emitted here.+// - the child's tool events carry the CHILD's chat id (`isCursorChildToolEvent`) and, from its+// first `postToolUse` on, its own `transcript_path`:+// `<config>/projects/<slug>/agent-transcripts/<childId>/<childId>.jsonl`, append-only JSONL+// `{role, message:{content:[text | tool_use]}}` lines ending `{"type":"turn_ended",status}`.+// Its assistant text is often `[REDACTED]`; tool calls and the final answer are kept.+// - the hook payloads hold NO key linking child to parent (no `parent_tool_call_id`). The child's+// store.db meta does (`subagentInfo.toolCallId`), but a child is claimed here only when exactly+// ONE of the node's open Tasks is unclaimed. note: parallel Tasks get cards without a tail;+// read the child meta's toolCallId if that ever matters.+//+// One definition for both shells (CLAUDE.md rule 10): src/main/index.ts and+// src/server/agent-status.ts each call `onRaw` from their raw hook listener.+import path from 'node:path'+import { isCursorBackgroundEvent, isCursorChildToolEvent, type NormalizedAgentEvent } from '../shared/agents/normalize'+import type { AgentId } from '../shared/agents/config'+import type { SubagentTail } from './subagent-tail'+import { CURSOR_CHAT_ID_RE, cursorConfigDir, cursorToolArg, cursorUserText } from './cursor-chat'++type Obj = Record<string, unknown>+const isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)+const REDACTED = '[REDACTED]'++/** One chunk of a child's agent-transcript JSONL as card text. Stateless, fresh per card. */+export function createCursorSubagentFormatter(): (text: string) => string {+ return (text: string): string => {+ const out: string[] = []+ for (const line of text.split('\n')) {+ let o: unknown+ try {+ o = JSON.parse(line)+ } catch {+ continue+ }+ if (!isObj(o)) continue+ if (o.type === 'turn_ended') {+ out.push(o.status === 'success' ? '✓ done' : `✗ ${typeof o.status === 'string' ? o.status : 'ended'}`)+ continue+ }+ const content = isObj(o.message) && Array.isArray(o.message.content) ? o.message.content : []+ for (const c of content) {+ if (!isObj(c)) continue+ if (c.type === 'text' && typeof c.text === 'string') {+ const t = o.role === 'user' ? cursorUserText(c.text) : c.text.replaceAll(REDACTED, '').trim()+ if (t) out.push(t)+ } else if (c.type === 'tool_use' && typeof c.name === 'string') {+ const arg = cursorToolArg(c.input)+ out.push(`$ ${c.name}${arg ? ` ${arg}` : ''}`)+ }+ }+ }+ return out.join('\n')+ }+}++/** The child's own transcript path, or undefined: absolute, under `<config>/projects/`, and named+ * `<childId>/<childId>.jsonl`. The path comes from a hook POST, so it is jailed like any other. */+export function cursorChildTranscript(p: unknown, childId: string, configDir: string = cursorConfigDir()): string | undefined {+ if (typeof p !== 'string' || !path.isAbsolute(p) || path.resolve(p) !== p) return undefined+ if (!CURSOR_CHAT_ID_RE.test(childId)) return undefined+ const root = path.join(configDir, 'projects') + path.sep+ if (!p.startsWith(root)) return undefined+ if (path.basename(p) !== `${childId}.jsonl` || path.basename(path.dirname(p)) !== childId) return undefined+ return p+}++interface NodeEntry {+ /** Task tool_use_ids started in this turn, in order. */+ open: string[]+ /** child chat id → the Task tool_use_id whose card it feeds. */+ children: Map<string, string>+}++export interface CursorSubagentTracker {+ onRaw(agentId: AgentId, nodeId: string | undefined, payload: unknown): void+ /** The node closed or was recycled mid-Task: no `stop` will come, so drop its entry and tails. */+ release(nodeId: string): void+}++export function createCursorSubagentTracker(deps: {+ tail: SubagentTail+ emit: (e: NormalizedAgentEvent) => void+ configDir?: () => string+}): CursorSubagentTracker {+ const nodes = new Map<string, NodeEntry>()+ return {+ onRaw(agentId, nodeId, payload) {+ if (!nodeId || !isObj(payload)) return+ const ev = payload.hook_event_name+ const conv = typeof payload.conversation_id === 'string' ? payload.conversation_id : undefined+ const isTool = ev === 'preToolUse' || ev === 'postToolUse' || ev === 'postToolUseFailure'+ if (isTool && isCursorChildToolEvent(payload)) {+ const e = nodes.get(nodeId)+ if (!e || !conv || e.children.has(conv)) return+ const claimed = new Set(e.children.values())+ const free = e.open.filter((id) => !claimed.has(id))+ if (free.length !== 1) return+ const file = cursorChildTranscript(payload.transcript_path, conv, deps.configDir?.())+ if (!file) return // a child's first preToolUse has no path yet; its postToolUse does+ e.children.set(conv, free[0])+ deps.tail.trackFile(free[0], file, createCursorSubagentFormatter)+ return+ }+ if (ev === 'preToolUse' && payload.tool_name === 'Task' && typeof payload.tool_use_id === 'string') {+ const e: NodeEntry = nodes.get(nodeId) ?? { open: [], children: new Map() }+ if (!e.open.includes(payload.tool_use_id)) e.open.push(payload.tool_use_id)+ nodes.set(nodeId, e)+ return+ }+ if (ev === 'stop' || ev === 'sessionEnd') {+ // A background agent's end, or a claimed child's own, is not the parent's: it must not end+ // the parent's cards or stand in as its session id (normalizeCursor drops it the same way).+ if (isCursorBackgroundEvent(payload)) return+ const e = nodes.get(nodeId)+ if (!e || (conv && e.children.has(conv))) return+ nodes.delete(nodeId)+ for (const toolUseId of e.open) {+ deps.emit({ nodeId, agentId, sessionId: conv, kind: 'subagent-end', toolUseId })+ deps.tail.finish(toolUseId)+ }+ }+ },+ release(nodeId) {+ const e = nodes.get(nodeId)+ if (!e) return+ nodes.delete(nodeId)+ for (const toolUseId of e.open) deps.tail.finish(toolUseId)+ }+ }+}diff --git a/src/core/pty-manager.separate-submit.test.ts b/src/core/pty-manager.separate-submit.test.tsnew file mode 100644index 000000000..753352912--- /dev/null+++ b/src/core/pty-manager.separate-submit.test.ts@@ -0,0 +1,345 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { readFileSync } from 'fs'+import path from 'path'+import { submitsSeparately, typesChatInput } from '../shared/agents/config'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++/** Every promisified execFile (runAsync / runWithStdin), in order: the envelope tests read it. */+const execCalls = vi.hoisted(() => [] as string[][])+vi.mock('child_process', async () => {+ const { promisify } = await import('util')+ const execFile = (_f: string, _a: string[], a?: unknown, b?: unknown): unknown => {+ const cb = (typeof a === 'function' ? a : b) as ((e: null, r: { stdout: string; stderr: string }) => void) | undefined+ cb?.(null, { stdout: '', stderr: '' })+ return {}+ }+ Object.assign(execFile, {+ [promisify.custom]: (file: string, args: string[]) => {+ execCalls.push([file, ...args])+ const child = { stdin: { on: () => undefined, end: () => undefined } }+ return Object.assign(Promise.resolve({ stdout: '', stderr: '' }), { child })+ }+ })+ return { execFile, execFileSync: (): string => '' }+})+vi.mock('./exec-path', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./exec-path')>()),+ findExecutableSync: (bin: string) => (bin === 'ssh' ? '/usr/bin/ssh' : null)+}))+vi.mock('./session-host-backend', async () => (await import('./__fixtures__/no-session-host')).noSessionHost())+vi.mock('node-pty', () => ({ spawn: () => ({}) }))++// Review 2026-10-02: cursor ignores an Enter bundled into the same tmux invocation as a bracketed+// paste, and only the rename path split it, so chat sends, phone sends, canvas `write` and trigger+// deliveries to a Cursor node sat unsubmitted. The split now lives in the ONE funnel every one-way+// writer reaches, `PtyManager.sendText`. A full PtyManager rig is out of reach here, so this pins+// the wiring at source level; the behaviour itself was checked live (chat send to a Cursor node).+const src = readFileSync(path.join(__dirname, 'pty-manager.ts'), 'utf8').replace(/\r\n/g, '\n')+const sendText = src.slice(src.indexOf(' async sendText('), src.indexOf(' private async deliverText('))++describe('PtyManager.sendText separate submit', () => {+ it('cursor is the agent that needs it, and the pane learns its agent at create', () => {+ expect(submitsSeparately('cursor')).toBe(true)+ expect(submitsSeparately('claude')).toBe(false)+ expect(src).toMatch(/if \(options\.agentId\) this\.agentByKey\.set\(key, options\.agentId\)/)+ })++ it('pastes without Enter, then sends a bare Enter, on the tmux paths only', () => {+ expect(sendText).toContain('submitsSeparately(capabilityAgentId(')+ expect(sendText).toContain("this.deliverText(persistKey, text, false, live)")+ expect(sendText).toContain("this.deliverText(persistKey, '', true, live)")+ expect(sendText).toContain('!live?.nativeWindowsPane')+ expect(sendText).toContain('!live?.sessionHost')+ // A paste that landed but whose Enter did not is never reported as delivered.+ expect(sendText).toContain("'pasted-not-submitted'")+ })+})++// Loading pty-manager cold takes 1-3.5 s here (more under a parallel run). Done inside a test it ate+// that test's 5 s budget and timed the first rig out; load it once, under its own budget.+let PtyManager: typeof import('./pty-manager').PtyManager+beforeAll(async () => {+ ;({ PtyManager } = await import('./pty-manager'))+}, 60_000)++/** The two tmux calls a separate-submit send makes, recorded in order on a real PtyManager. */+interface Internals {+ agentByKey: Map<string, string>+ liveSessionForPersistKey(k: string): unknown+ deliverText(k: string, text: string, enter: boolean): Promise<true | false | 'pasted-not-submitted'>+ sendText(k: string, text: string, opts?: { enter?: boolean }): Promise<unknown>+ sendTyped(k: string, text: string, agentId: string): Promise<unknown>+ sendChatPrompt(k: string, text: string, agentId: string): Promise<unknown>+ captureSession(k: string): Promise<string>+ sendEnvelope(k: string, envelope: string): Promise<boolean>+ sendEnvelopeNow(k: string, envelope: string): Promise<boolean>+ setRelayNodeResolver(r: unknown): void+ tmuxPath: string | null+ sessionByPersistKey(k: string): unknown+}++describe('PtyManager.sendText: overlapping separate-submit sends do not interleave (review 2026-10-03)', () => {+ beforeEach(() => {+ initPlatform(fakePlatform())+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+ })++ async function rig(agent: string, paste: (text: string) => true | false = () => true) {+ const mgr = new PtyManager() as unknown as Internals+ mgr.agentByKey.set('n1', agent)+ mgr.liveSessionForPersistKey = () => ({})+ const calls: [string, boolean][] = []+ mgr.deliverText = async (_k, text, enter) => {+ calls.push([text, enter])+ return text ? paste(text) : true+ }+ return { mgr, calls }+ }++ it('cursor: paste1, Enter, paste2, Enter', async () => {+ const { mgr, calls } = await rig('cursor')+ const sends = Promise.all([mgr.sendText('n1', 'first'), mgr.sendText('n1', 'second')])+ await vi.advanceTimersByTimeAsync(400)+ expect(await sends).toEqual([true, true])+ expect(calls).toEqual([+ ['first', false],+ ['', true],+ ['second', false],+ ['', true]+ ])+ })++ it('a failed paste keeps its own result and does not stall the next send', async () => {+ const { mgr, calls } = await rig('cursor', (t) => t !== 'first')+ const sends = Promise.all([mgr.sendText('n1', 'first'), mgr.sendText('n1', 'second')])+ await vi.advanceTimersByTimeAsync(400)+ expect(await sends).toEqual([false, true])+ expect(calls).toEqual([+ ['first', false],+ ['second', false],+ ['', true]+ ])+ })++ it('claude keeps its one-shot paste+Enter', async () => {+ const { mgr, calls } = await rig('claude')+ expect(await Promise.all([mgr.sendText('n1', 'first'), mgr.sendText('n1', 'second')])).toEqual([true, true])+ expect(calls).toEqual([+ ['first', true],+ ['second', true]+ ])+ })+})++// b27b3800 sends chat-view prompts as TYPED text, but only for TYPED_INPUT_CAPABLE (claude). Cursor+// keeps the paste, so its chat send must still reach the split: paste, gap, bare Enter. Every write+// into a pane now queues on `serializePaneWrite`, so an envelope cannot land between the two halves.+describe('PtyManager.sendChatPrompt: the typed chat path leaves cursor on the split paste', () => {+ beforeEach(() => {+ initPlatform(fakePlatform())+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+ })++ async function rig(agent: string) {+ const mgr = new PtyManager() as unknown as Internals+ mgr.agentByKey.set('n1', agent)+ mgr.liveSessionForPersistKey = () => ({})+ mgr.captureSession = async () => ''+ const calls: unknown[][] = []+ mgr.deliverText = async (_k, text, enter) => {+ calls.push([text, enter])+ return true+ }+ mgr.sendTyped = async (_k, text, agentId) => {+ calls.push(['typed', text, agentId])+ return true+ }+ mgr.sendEnvelopeNow = async (_k, envelope) => {+ calls.push(['envelope', envelope])+ return true+ }+ return { mgr, calls }+ }++ it('cursor is not typed: its chat prompt is pasted, then submitted by a separate Enter', async () => {+ expect(typesChatInput('cursor')).toBe(false)+ const { mgr, calls } = await rig('cursor')+ const sent = mgr.sendChatPrompt('n1', 'line one\nline two', 'cursor')+ await vi.advanceTimersByTimeAsync(200)+ expect(await sent).toBe(true)+ expect(calls).toEqual([+ ['line one\nline two', false],+ ['', true]+ ])+ })++ it('claude takes the typed path and never the split', async () => {+ const { mgr, calls } = await rig('claude')+ expect(await mgr.sendChatPrompt('n1', 'hi', 'claude')).toBe(true)+ expect(calls).toEqual([['typed', 'hi', 'claude']])+ })++ it('an envelope arriving mid-split waits until the cursor Enter is sent', async () => {+ const { mgr, calls } = await rig('cursor')+ const both = Promise.all([mgr.sendChatPrompt('n1', 'prompt', 'cursor'), mgr.sendEnvelope('n1', 'env')])+ await vi.advanceTimersByTimeAsync(200)+ expect(await both).toEqual([true, true])+ expect(calls).toEqual([+ ['prompt', false],+ ['', true],+ ['envelope', 'env']+ ])+ })+})++describe('PtyManager forgets a deleted node\'s agent', () => {+ it('drops agentByKey on delete, keeps it across a recycle', () => {+ const end = src.slice(src.indexOf("if (intent === 'delete') {"), src.indexOf('} else this.tombstones.delete(persistKey)'))+ expect(end).toContain('this.agentByKey.delete(persistKey)')+ })+})++// Review merge2: the split keyed on create()'s record alone, so after a restart an unmounted Cursor+// node got the one-shot paste+Enter; agent envelopes never split; and the bare Enter could answer a+// Cursor dialog that opened during the gap.+describe('PtyManager: separate submit after restart, for envelopes, and never into a dialog', () => {+ const PLAN = ' Ready to build?\n → Yes, build locally (b)\n No, propose changes (p or Esc)\n'+ const APPROVAL = ' Run this command?\n → Run (once) (y)\n Skip (esc or n)\n'+ const QUESTION = ' │ Question 1 of 1 │\n │ › [ ] Red │\n │ Space select · Enter next/submit · Esc to skip │\n └────┘\n'++ beforeEach(() => {+ initPlatform(fakePlatform())+ vi.useFakeTimers()+ execCalls.length = 0+ })+ afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+ })++ const resolver = (...agents: (string | undefined)[]) => ({+ placements: () => agents.map((agentId, i) => ({ projectId: `p${i}`, node: { agentId } })),+ refFor: () => undefined,+ projectIsRemote: () => false+ })++ async function rig(opts: { create?: string; placed?: (string | undefined)[]; screen?: () => Promise<string> }) {+ const mgr = new PtyManager() as unknown as Internals+ if (opts.create) mgr.agentByKey.set('n1', opts.create)+ if (opts.placed) mgr.setRelayNodeResolver(resolver(...opts.placed))+ mgr.liveSessionForPersistKey = () => ({})+ mgr.captureSession = opts.screen ?? (async () => 'idle composer')+ const calls: [string, boolean][] = []+ mgr.deliverText = async (_k, text, enter) => {+ calls.push([text, enter])+ return true+ }+ return { mgr, calls }+ }++ async function send(mgr: Internals): Promise<unknown> {+ const sent = mgr.sendText('n1', 'hi')+ await vi.advanceTimersByTimeAsync(400)+ return sent+ }++ it('no create(), every placement says cursor: sendText splits', async () => {+ const { mgr, calls } = await rig({ placed: ['cursor', 'cursor'] })+ expect(await send(mgr)).toBe(true)+ expect(calls).toEqual([['hi', false], ['', true]])+ })++ it('placements that disagree, or name no agent, keep the one-shot paste+Enter', async () => {+ for (const placed of [['cursor', 'claude'], [undefined], ['cursor', undefined]]) {+ const { mgr, calls } = await rig({ placed })+ expect(await send(mgr)).toBe(true)+ expect(calls).toEqual([['hi', true]])+ }+ })++ /** A clean pane at the pre-paste read, then `dialog` from the post-paste read on. */+ const opensAfterPaste = (dialog: string) => {+ let reads = 0+ return async () => (reads++ === 0 ? 'idle composer' : dialog)+ }++ it('a Cursor dialog that opens after the paste gets no Enter', async () => {+ for (const dialog of [PLAN, APPROVAL, QUESTION]) {+ const { mgr, calls } = await rig({ create: 'cursor', screen: opensAfterPaste(dialog) })+ expect(await send(mgr)).toBe('pasted-not-submitted')+ expect(calls).toEqual([['hi', false]])+ }+ })++ it('a Cursor dialog already on screen gets nothing written at all', async () => {+ for (const dialog of [PLAN, APPROVAL, QUESTION]) {+ const { mgr, calls } = await rig({ create: 'cursor', screen: async () => dialog })+ expect(await send(mgr)).toBe(false)+ expect(calls).toEqual([])+ }+ })++ it('a clean, empty or failed capture still gets the Enter', async () => {+ const screens = [async () => 'idle composer', async () => '', () => Promise.reject(new Error('gone'))]+ for (const screen of screens) {+ const { mgr, calls } = await rig({ create: 'cursor', screen })+ expect(await send(mgr)).toBe(true)+ expect(calls).toEqual([['hi', false], ['', true]])+ }+ })++ /** The paste/Enter shape of each tmux invocation an envelope made, local or over ssh. */+ const shapes = (): string[] =>+ execCalls+ .map((c) => c.join(' '))+ .filter((c) => c.includes('paste-buffer') || c.includes('Enter'))+ .map((c) => (c.includes('paste-buffer') ? (c.includes('Enter') ? 'paste+Enter' : 'paste') : 'Enter'))++ async function envelope(agent: string, ssh: boolean, screen = async () => 'idle composer') {+ const { mgr } = await rig({ create: agent, screen })+ mgr.tmuxPath = '/usr/bin/tmux'+ mgr.sessionByPersistKey = () =>+ ssh ? { sshRemote: { conn: { host: 'box', user: 'me' }, controlPath: '/tmp/cm.sock' } } : {}+ const sent = mgr.sendEnvelope('n1', 'envelope body')+ await vi.advanceTimersByTimeAsync(400)+ const ok = await sent+ return { ok, shapes: shapes(), files: execCalls.map((c) => c[0]) }+ }++ for (const ssh of [false, true]) {+ const leg = ssh ? 'ssh' : 'local'+ it(`${leg}: a cursor envelope is pasted, then submitted by a bare Enter`, async () => {+ const r = await envelope('cursor', ssh)+ expect(r).toMatchObject({ ok: true, shapes: ['paste', 'Enter'] })+ expect(new Set(r.files)).toEqual(new Set([ssh ? '/usr/bin/ssh' : '/usr/bin/tmux']))+ })++ it(`${leg}: a claude envelope keeps its one paste+Enter`, async () => {+ expect(await envelope('claude', ssh)).toMatchObject({ ok: true, shapes: ['paste+Enter'] })+ })++ it(`${leg}: a cursor envelope pasted before a dialog opens gets no Enter, and counts as written`, async () => {+ expect(await envelope('cursor', ssh, opensAfterPaste(PLAN))).toMatchObject({ ok: true, shapes: ['paste'] })+ })++ it(`${leg}: a cursor envelope meeting a dialog writes nothing and answers 'dialog'`, async () => {+ expect(await envelope('cursor', ssh, async () => PLAN)).toEqual({ ok: 'dialog', shapes: [], files: [] })+ })+ }++ it('an empty envelope is still refused before anything is written', async () => {+ const { mgr } = await rig({ create: 'cursor' })+ mgr.tmuxPath = '/usr/bin/tmux'+ expect(await mgr.sendEnvelope('n1', '')).toBe(false)+ expect(execCalls).toEqual([])+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 16978a072..054a99d38 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -24,6 +24,7 @@ import {} from '../shared/types'import { bundledTmuxPath, findCommand, findFixedTmux, tmuxInstall } from './tmux-hint'import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'+import { cursorApprovalIn, cursorPlanPromptIn, cursorQuestionIn } from './agents/cursor-approval'import { findAgy, pathWithAgyDir } from './agents/hooks/antigravity'import { currentIntegrationLifecycle } from './agent-integrations'import {@@ -181,6 +182,7 @@ import { ensureNodeToken, ensureRemoteNodeToken, sweepNodeToken } from './agentsimport { clearNode as clearNodeAgentStatus } from './agent-status-mirror'import {capabilityAgentId,+ submitsSeparately,hasSharedIdentity,readsScreenDialogs,setCustomAgentBaseResolver,@@ -1129,8 +1131,15 @@ function screenGate(screen: string): ChatPromptBlocked | null {* survives, so reopening the node or restarting the app reattaches and continues* where it left off. Without tmux, it falls back to a plain shell (no persistence).*/+/** Gap between a paste and its separate Enter for SEPARATE_SUBMIT_AGENTS (the rename path's+ * measured shape: paste, then Enter as its own tmux invocation). */+const SEPARATE_SUBMIT_DELAY_MS = 150+export class PtyManager {private sessions = new Map<string, Session>()+ /** persistKey -> the agent id its pane was created for (this app run). `sendText` asks it so an+ * agent in SEPARATE_SUBMIT_AGENTS gets its Enter as a second write (see `sendText`). */+ private agentByKey = new Map<string, string>()/** persistKey (node id) → live sessionId. The index that makes `pty:create` idempotent:* a second client asking for the same node subscribes to the running session. */private byPersistKey = new Map<string, string>()@@ -2504,6 +2513,7 @@ export class PtyManager {private async create(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {const key = options.persistKeyif (!key) return this.spawnNew(clientId, options)+ if (options.agentId) this.agentByKey.set(key, options.agentId)// SECURITY — the choke point for the node id. Every session spawn (local tmux, plain shell,// SSH remote) goes through here, `pty:create` validates its payload nowhere, and node ids come// from `.nodeterm/project.json` — a file that travels in a cloned/shared repo and is written on@@ -6406,7 +6416,6 @@ export class PtyManager {opts?: { enter?: boolean; typedFor?: AgentId }): Promise<TextDeliveryResult> {const enter = opts?.enter ?? true- const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)// `typedFor` (the ⌘M chat view, set only by `sendChatPrompt`): deliver as keystrokes, not a// paste — see core/typed-input.ts. Only a SUBMITTED prompt on a tmux backend; everything else@@ -6415,6 +6424,63 @@ export class PtyManager {const typed = await this.sendTyped(persistKey, text, opts.typedFor)if (typed !== null) return typed}+ // An agent whose TUI ignores an Enter bundled into the same tmux invocation as a bracketed paste+ // (SEPARATE_SUBMIT_AGENTS, cursor: MEASURED, the line sits unsubmitted in its composer) gets the+ // paste and then a bare Enter as a second write. ONE place for every one-way writer: the chat+ // composer, the phone, canvas `write`, trigger delivery and rename all reach here (review+ // 2026-10-02 found only rename split it). Windows panes and the session host already submit+ // with a separate, settled Enter, so they are left alone. The paste and its Enter run inside+ // `serializePaneWrite`, so two overlapping sends cannot interleave as paste, paste, Enter, Enter.+ if (enter && text && !live?.nativeWindowsPane && !live?.sessionHost && this.submitsSeparatelyKey(persistKey)) {+ if (await this.cursorDialogShowing(persistKey)) return false // nothing written+ const pasted = await this.deliverText(persistKey, text, false, live)+ if (pasted !== true) return pasted+ await new Promise((r) => setTimeout(r, SEPARATE_SUBMIT_DELAY_MS))+ if (await this.cursorDialogShowing(persistKey)) return 'pasted-not-submitted'+ const entered = await this.deliverText(persistKey, '', true, live)+ return entered === true ? true : 'pasted-not-submitted'+ }+ return this.deliverText(persistKey, text, enter, live)+ }++ /**+ * The agent a pane runs: create()'s record this app run, else this machine's workspace records+ * (`setRelayNodeResolver`) when every placement agrees. After a restart a node not mounted yet+ * (off-screen canvas `write`, trigger, phone send) has no create() record.+ */+ private agentForKey(persistKey: string): string | undefined {+ const known = this.agentByKey.get(persistKey)+ if (known) return known+ const ids = new Set((this.relayNodes?.placements(persistKey) ?? []).map((p) => p.node.agentId))+ return ids.size === 1 ? [...ids][0] : undefined+ }++ /** Does this pane's agent ignore an Enter bundled with its paste (SEPARATE_SUBMIT_AGENTS)? */+ private submitsSeparatelyKey(persistKey: string): boolean {+ const agent = this.agentForKey(persistKey)+ return !!agent && submitsSeparately(capabilityAgentId(agent as AgentId))+ }++ /**+ * Is a Cursor dialog (approval, AskQuestion, plan "Ready to build?") on screen? The split's bare+ * Enter must not answer one that opened during the gap. An empty or failed capture is not+ * evidence (the `sendChatPrompt` rule): the Enter goes as before.+ * note: Cursor detectors only; SEPARATE_SUBMIT_AGENTS is cursor alone today.+ * note: fail-open on a blind capture: failing closed would block every send whenever the pane+ * cannot be read (e.g. ssh missing).+ */+ private async cursorDialogShowing(persistKey: string): Promise<boolean> {+ const screen = await this.captureSession(persistKey).catch(() => '')+ return cursorApprovalIn(screen) || cursorQuestionIn(screen) || cursorPlanPromptIn(screen)+ }++ private async deliverText(+ persistKey: string,+ text: string,+ enter: boolean,+ live: ReturnType<PtyManager['liveSessionForPersistKey']>+ ): Promise<TextDeliveryResult> {+ const target = sessionName(persistKey)// A direct (non-persistent) Windows PTY has no session-host entry and no tmux: it is typed// into through the pane itself. Routing it to the session host below failed every time.if (live?.nativeWindowsPane) return live.nativeWindowsPane.sendText(text, enter)@@ -7032,11 +7098,11 @@ export class PtyManager {* accidental submit a messaging delivery must never perform — an empty envelope refuses here.* (`buildEnvelope` can never return '', so this is a guard against a future caller, not a path.)*/- async sendEnvelope(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean> {+ async sendEnvelope(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean | 'dialog'> {return this.serializePaneWrite(persistKey, () => this.sendEnvelopeNow(persistKey, envelope, expected))}- private async sendEnvelopeNow(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean> {+ private async sendEnvelopeNow(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean | 'dialog'> {if (envelope.length === 0) return falseconst live = this.liveSessionForPersistKey(persistKey)if (this.isZellij(persistKey, live)) return false@@ -7046,24 +7112,36 @@ export class PtyManager {return expected ? sessionHostMessageEnvelope(target, envelope, expected) : false}const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote- try {- if (sshRemote) {- const ssh = findSsh()- if (!ssh) return false- const plan = remotePasteDelivery(sshRemote.conn, sshRemote.controlPath, target, envelope, true)+ const deliver = async (body: string, enter: boolean): Promise<boolean> => {+ try {+ if (sshRemote) {+ const ssh = findSsh()+ if (!ssh) return false+ const plan = remotePasteDelivery(sshRemote.conn, sshRemote.controlPath, target, body, enter)+ if (!plan) return false+ return await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))+ }+ if (!this.tmuxPath) return false+ const tmuxPath = this.tmuxPath+ const plan = localPasteDelivery(TMUX_SOCKET, target, body, enter)if (!plan) return false- return await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))+ return await runPasteDelivery(plan, (args, input) => runWithStdin(tmuxPath, args, input))+ } catch {+ // A builder throwing (an unsafe target) lands here; `runPasteDelivery` itself answers false+ // rather than throwing, so the buffer sweep is never skipped.+ return false}- if (!this.tmuxPath) return false- const tmuxPath = this.tmuxPath- const plan = localPasteDelivery(TMUX_SOCKET, target, envelope, true)- if (!plan) return false- return await runPasteDelivery(plan, (args, input) => runWithStdin(tmuxPath, args, input))- } catch {- // A builder throwing (an unsafe target) lands here; `runPasteDelivery` itself answers false- // rather than throwing, so the buffer sweep is never skipped.- return false}+ if (!this.submitsSeparatelyKey(persistKey)) return deliver(envelope, true)+ // `sendText`'s split, inlined: this op already holds the pane's `serializePaneWrite` slot, so+ // calling `sendText` here would queue behind itself. A dialog before the paste writes nothing+ // ('dialog'). Once the paste is in, the answer is `true` whatever the Enter does (the+ // `DeliveryDeps.sendEnvelope` contract), so the receipt watch reports `stalled`, not `targetGone`.+ if (await this.cursorDialogShowing(persistKey)) return 'dialog'+ if (!(await deliver(envelope, false))) return false+ await new Promise((r) => setTimeout(r, SEPARATE_SUBMIT_DELAY_MS))+ if (!(await this.cursorDialogShowing(persistKey))) await deliver('', true)+ return true}/**@@ -7679,8 +7757,11 @@ export class PtyManager {// `tombstones`); a RECYCLE explicitly forgets, because the node is not going anywhere and its// replacement session must be spawnable. Recorded even when no live session exists in this// process: the node may be deleted from a canvas whose terminal was never opened here.- if (intent === 'delete') this.tombstone(persistKey, clientId)- else this.tombstones.delete(persistKey)+ if (intent === 'delete') {+ this.tombstone(persistKey, clientId)+ // The node is gone; a recycle keeps it, and its respawn's create() re-records the agent.+ this.agentByKey.delete(persistKey)+ } else this.tombstones.delete(persistKey)if (dyingId && dying) {this.byPersistKey.delete(persistKey)dying.indexKey = undefineddiff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.tsindex 8e216725b..4fb365c17 100644--- a/src/core/transcript-ipc.ts+++ b/src/core/transcript-ipc.ts@@ -25,6 +25,7 @@ import { readGeminiChatTranscript } from './gemini-chat'import { chatMessagesFromCodex, locateCodexRollout, parseCodexChatWindow } from './codex-chat'import { chatMessagesFromCopilot, locateCopilotTranscript, parseCopilotChatWindow } from './copilot-chat'import { readOpencodeChat, type OpencodeExportRun } from './opencode-chat'+import { readCursorChat } from './cursor-chat'import { locateGrok } from './handoff/locate'import { capabilityAgentId } from '../shared/agents/config'import {@@ -414,6 +415,10 @@ export async function readChatTranscript(if (agentId && capabilityAgentId(agentId) === 'opencode') {return readOpencodeChat({ sessionId, remoteOnly }, page, deps.opencodeExport)}+ // Cursor keeps chats in a SQLite store (`~/.cursor/chats/<md5 cwd>/<id>/store.db`), found strictly by+ // its whole-UUID id, never claude's resolver, whose cwd fallback would answer with a stranger's+ // session. Local only (`CHAT_LOCAL_ONLY`). See core/cursor-chat.ts.+ if (agentId && capabilityAgentId(agentId) === 'cursor') return readCursorChat({ sessionId, cwd, remoteOnly }, page)if (page) return readChatPage({ sessionId, cwd, accountId, nodeId, ...(remoteOnly ? { remoteOnly } : {}) }, page, deps)const remote = deps.readRemote ? await deps.readRemote({ sessionId, cwd, accountId, nodeId }) : null// A resolved-but-unreadable remote file is NOT "no conversation yet" — the read faileddiff --git a/src/core/usage/cursor-usage.test.ts b/src/core/usage/cursor-usage.test.tsnew file mode 100644index 000000000..aabe7717d--- /dev/null+++ b/src/core/usage/cursor-usage.test.ts@@ -0,0 +1,164 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { readFileSync } from 'fs'+import path from 'path'+import {+ mapCursorLimits,+ holdCursorLastGood,+ fetchCursorUsage,+ tokenSubject,+ cursorAuthFile,+ resetCursorUsageHold+} from './cursor-usage'+import type { ProviderUsage } from '../../shared/types'++// Synthetic, shaped like a measured GetCurrentPeriodUsage reply (cursor-agent 2026.10.01). No real ids.+const START = 1_790_000_000_000+const END = START + 30 * 24 * 60 * 60 * 1000+const BODY = {+ billingCycleStart: String(START),+ billingCycleEnd: String(END),+ planUsage: {+ totalSpend: 12000,+ includedSpend: 8000,+ bonusSpend: 4000,+ limit: 20000,+ remainingBonus: true,+ bonusTooltip: 'synthetic',+ autoPercentUsed: 12.5,+ apiPercentUsed: 100,+ totalPercentUsed: 40+ },+ spendLimitUsage: { limitType: 'user' },+ enabled: true+}++const jwt = (sub: string): string =>+ ['e30', Buffer.from(JSON.stringify({ sub })).toString('base64url'), 'sig'].join('.')++const reply = (status: number, body: unknown = BODY): typeof fetch =>+ (async () => new Response(JSON.stringify(body), { status })) as typeof fetch++describe('mapCursorLimits', () => {+ it('maps total, Auto and API percentages with the billing reset', () => {+ const limits = mapCursorLimits(BODY)+ expect(limits.map((l) => [l.kind, l.scopeLabel, l.usedPercent])).toEqual([+ ['monthly', null, 40],+ ['monthly_scoped', 'Auto', 12.5],+ ['monthly_scoped', 'API', 100]+ ])+ expect(limits[0].resetsAt).toBe(END)+ expect(limits[0].windowMinutes).toBe(30 * 24 * 60)+ })++ it('falls back to included spend over the limit, as the CLI does', () => {+ const { totalPercentUsed: _t, autoPercentUsed: _a, apiPercentUsed: _p, ...plan } = BODY.planUsage+ expect(mapCursorLimits({ ...BODY, planUsage: plan })[0].usedPercent).toBe(40)+ })++ it('draws nothing (never 0%) without planUsage or a total', () => {+ expect(mapCursorLimits({ billingCycleEnd: String(END) })).toEqual([])+ expect(mapCursorLimits({ planUsage: { limit: 0 } })).toEqual([])+ expect(mapCursorLimits(null)).toEqual([])+ })+})++describe('fetchCursorUsage', () => {+ beforeEach(() => resetCursorUsageHold())++ it('is unavailable when not signed in, and asks nothing', async () => {+ let called = false+ const u = await fetchCursorUsage({+ readToken: async () => null,+ fetchImpl: (async () => { called = true; return new Response('{}') }) as typeof fetch+ })+ expect(u.status).toBe('unavailable')+ expect(called).toBe(false)+ })++ it('sends the token only in the Authorization header', async () => {+ const token = jwt('user|synthetic')+ let seen: { url: string; init?: RequestInit } | null = null+ const u = await fetchCursorUsage({+ readToken: async () => token,+ fetchImpl: (async (url: string, init?: RequestInit) => {+ seen = { url, init }+ return new Response(JSON.stringify(BODY), { status: 200 })+ }) as typeof fetch+ })+ expect(u.status).toBe('ok')+ expect(u.limits).toHaveLength(3)+ expect(seen!.url).not.toContain(token)+ expect(seen!.init?.body).toBe('{}')+ expect((seen!.init?.headers as Record<string, string>).authorization).toBe(`Bearer ${token}`)+ })++ it('never parses a reply past 256 KB, and still maps a normal one', async () => {+ const huge = { ...BODY, pad: 'x'.repeat(300 * 1024) }+ const big = await fetchCursorUsage({ readToken: async () => jwt('a'), fetchImpl: reply(200, huge) })+ expect(big).toMatchObject({ status: 'unavailable', limits: [] })+ const ok = await fetchCursorUsage({ readToken: async () => jwt('a'), fetchImpl: reply(200) })+ expect(ok.status).toBe('ok')+ })++ it('reads an expired token (401) as unavailable', async () => {+ const u = await fetchCursorUsage({ readToken: async () => jwt('a'), fetchImpl: reply(401) })+ expect(u.status).toBe('unavailable')+ })++ it('keeps the last good numbers through a 5xx or a network failure', async () => {+ const token = jwt('a')+ const good = await fetchCursorUsage({ readToken: async () => token, fetchImpl: reply(200) })+ const failed = await fetchCursorUsage({ readToken: async () => token, fetchImpl: reply(503) })+ expect(failed.status).toBe('error')+ expect(failed.limits).toEqual(good.limits)+ const thrown = await fetchCursorUsage({+ readToken: async () => token,+ fetchImpl: (async () => { throw new Error('offline') }) as typeof fetch+ })+ expect(thrown.status).toBe('error')+ expect(thrown.limits).toEqual(good.limits)+ })++ it('does not hold one login numbers for another login', async () => {+ await fetchCursorUsage({ readToken: async () => jwt('a'), fetchImpl: reply(200) })+ const other = await fetchCursorUsage({ readToken: async () => jwt('b'), fetchImpl: reply(500) })+ expect(other.status).toBe('error')+ expect(other.limits).toEqual([])+ })+})++describe('holdCursorLastGood', () => {+ const now = START + 1000+ const usage = (over: Partial<ProviderUsage>): ProviderUsage => ({+ provider: 'cursor', account: null, updatedAt: now, status: 'ok', limits: mapCursorLimits(BODY), ...over+ })++ it('refuses past an hour or after the reset', () => {+ const fail = usage({ status: 'error', limits: [] })+ expect(holdCursorLastGood({ sub: 'a', usage: usage({ updatedAt: now - 2 * 3600_000 }) }, fail, 'a', now).limits).toEqual([])+ expect(holdCursorLastGood({ sub: 'a', usage: usage({}) }, fail, 'a', END + 1).limits).toEqual([])+ expect(holdCursorLastGood({ sub: 'a', usage: usage({}) }, fail, 'a', now).limits).toHaveLength(3)+ })+})++describe('credential handling', () => {+ it('reads the sub claim and nothing else', () => {+ expect(tokenSubject(jwt('user|x'))).toBe('user|x')+ expect(tokenSubject('not-a-jwt')).toBeNull()+ })++ it('knows the CLI file-store path per platform', () => {+ expect(cursorAuthFile('linux', {}, '/h')).toBe(path.join('/h', '.config', 'cursor', 'auth.json'))+ expect(cursorAuthFile('linux', { XDG_CONFIG_HOME: '/x' }, '/h')).toBe(path.join('/x', 'cursor', 'auth.json'))+ expect(cursorAuthFile('darwin', {}, '/h')).toBe(path.join('/h', '.cursor', 'auth.json'))+ })++ it('never puts the token on an argv (source pin)', () => {+ const src = readFileSync(path.join(__dirname, 'cursor-usage.ts'), 'utf8').replace(/\r\n/g, '\n')+ const call = src.slice(src.indexOf("'/usr/bin/security'"), src.indexOf('{ timeout: 5000 }'))+ expect(call).toContain("['find-generic-password', '-a', 'cursor-user', '-s', 'cursor-access-token', '-w']")+ expect(call).not.toContain('${')+ expect(call).not.toContain('Bearer')+ expect(src.match(/execFileP\(/g)).toHaveLength(1)+ })+})diff --git a/src/core/usage/cursor-usage.ts b/src/core/usage/cursor-usage.tsnew file mode 100644index 000000000..ffdf0ee84--- /dev/null+++ b/src/core/usage/cursor-usage.ts@@ -0,0 +1,203 @@+// Cursor plan usage: the same numbers the CLI's own `/usage` command shows.+//+// Source, measured on cursor-agent 2026.10.01-e373342: the CLI's `src/usage/usage-data.ts` calls+// `aiserver.v1.DashboardService/GetCurrentPeriodUsage` (Connect protocol, so plain JSON over POST+// works) on its backend `https://api2.cursor.sh`. `planUsage` carries the plan's included-usage+// percentages (total, Auto bucket, API bucket); `billingCycleEnd` is the reset (epoch ms, as a+// string because it is an int64).+//+// The credential is the CLI's own login, read and never written or refreshed (refreshing would+// rotate the token under a live `cursor-agent`). Where it lives is the CLI's `cli-credentials`+// store: the macOS login Keychain (account `cursor-user`, service `cursor-access-token`, written by+// `/usr/bin/security`, so reading it with the same binary raises no prompt); everywhere else, and+// on macOS with AGENT_CLI_CREDENTIAL_STORE=file, an `auth.json` with `accessToken`. The token only+// ever travels in-process: the `security` call's argv holds the service name, the value comes+// back on stdout.+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { execFile } from 'child_process'+import { promisify } from 'util'+import type { ProviderUsage, UsageLimit } from '../../shared/types'+import { HOLD_LAST_GOOD_MAX_MS } from './claude-usage-map'++const execFileP = promisify(execFile)++const USAGE_URL = 'https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage'+const FETCH_TIMEOUT_MS = 8000+/** A usage reply is a few fields; a body past this is not one and is never parsed. */+const MAX_BODY_BYTES = 256 * 1024++/** The reply's JSON, or null when it runs past MAX_BODY_BYTES (the read stops there). */+async function cappedJson(res: Response): Promise<unknown> {+ const reader = res.body?.getReader()+ if (!reader) return null+ const chunks: Uint8Array[] = []+ let total = 0+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ total += value.byteLength+ if (total > MAX_BODY_BYTES) {+ await reader.cancel()+ return null+ }+ chunks.push(value)+ }+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))+}++/** The CLI's `auth.json` path when it uses the file store (its own `getAuthFilePath`). */+export function cursorAuthFile(platform = process.platform, env = process.env, home = os.homedir()): string {+ if (platform === 'win32') return path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Cursor', 'auth.json')+ if (platform === 'darwin') return path.join(home, '.cursor', 'auth.json')+ return path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'cursor', 'auth.json')+}++export async function readCursorToken(): Promise<string | null> {+ if (process.platform === 'darwin') {+ try {+ const { stdout } = await execFileP(+ '/usr/bin/security',+ ['find-generic-password', '-a', 'cursor-user', '-s', 'cursor-access-token', '-w'],+ { timeout: 5000 }+ )+ const token = stdout.trim()+ if (token) return token+ } catch {+ // no Keychain item (signed out, or the file store): fall through to auth.json+ }+ }+ try {+ const j = JSON.parse(await fs.readFile(cursorAuthFile(), 'utf-8')) as Record<string, unknown>+ return typeof j.accessToken === 'string' && j.accessToken ? j.accessToken : null+ } catch {+ return null+ }+}++/** The login's `sub` claim, used only to refuse holding one account's numbers for another. */+export function tokenSubject(token: string): string | null {+ try {+ const payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf-8'))+ return typeof payload?.sub === 'string' ? payload.sub : null+ } catch {+ return null+ }+}++function num(value: unknown): number | null {+ const n = typeof value === 'string' ? Number(value) : value+ return typeof n === 'number' && Number.isFinite(n) ? n : null+}++function limit(kind: string, scopeLabel: string | null, percent: number, resetsAt: number | null, windowMinutes: number | null): UsageLimit {+ return {+ kind,+ group: 'monthly',+ usedPercent: Math.min(100, Math.max(0, percent)),+ severity: null,+ resetsAt,+ windowMinutes,+ scopeLabel,+ isActive: false+ }+}++/**+ * A GetCurrentPeriodUsage body → limits. No `planUsage` (the CLI's enterprise/spend-only case)+ * or no total is an empty list: nothing honest to draw, never a fabricated 0%.+ */+export function mapCursorLimits(body: unknown): UsageLimit[] {+ if (!body || typeof body !== 'object') return []+ const b = body as Record<string, any>+ const plan = b.planUsage as Record<string, unknown> | undefined+ if (!plan || typeof plan !== 'object') return []++ const end = num(b.billingCycleEnd)+ const start = num(b.billingCycleStart)+ const resetsAt = end && end > 0 ? end : null+ const windowMinutes = resetsAt && start && start > 0 && resetsAt > start ? Math.round((resetsAt - start) / 60_000) : null++ // The CLI's own fallback: no percentage → included spend over the limit.+ const cap = num(plan.limit)+ const spent = num(plan.includedSpend)+ const total = num(plan.totalPercentUsed) ?? (cap && cap > 0 && spent !== null ? (spent / cap) * 100 : null)+ if (total === null) return []++ const out = [limit('monthly', null, total, resetsAt, windowMinutes)]+ const auto = num(plan.autoPercentUsed)+ if (auto !== null) out.push(limit('monthly_scoped', 'Auto', auto, resetsAt, windowMinutes))+ const api = num(plan.apiPercentUsed)+ if (api !== null) out.push(limit('monthly_scoped', 'API', api, resetsAt, windowMinutes))+ return out+}++/**+ * A failed read keeps the last good numbers of the SAME login (the `holdLastGood` rule Claude+ * uses): status 'error', old limits, old `updatedAt`. Refuses when a different login answered,+ * the numbers are older than an hour, or the billing period has reset since.+ */+export function holdCursorLastGood(+ prev: { sub: string | null; usage: ProviderUsage } | null,+ next: ProviderUsage,+ sub: string | null,+ now: number+): ProviderUsage {+ if (next.status !== 'error' || !prev || prev.usage.limits.length === 0) return next+ if (prev.sub !== sub) return next+ if (now - prev.usage.updatedAt > HOLD_LAST_GOOD_MAX_MS) return next+ if (prev.usage.limits.some((l) => l.resetsAt !== null && l.resetsAt <= now)) return next+ return { ...prev.usage, status: 'error' }+}++function snapshot(limits: UsageLimit[], status: ProviderUsage['status']): ProviderUsage {+ return { provider: 'cursor', limits, account: null, updatedAt: Date.now(), status }+}++// note: one process-wide slot, since Cursor has one login per machine; per-account slots if+// nodeterm ever manages several Cursor logins.+let lastGood: { sub: string | null; usage: ProviderUsage } | null = null++/** Cursor usage. Never rejects. `deps` exist for tests. */+export async function fetchCursorUsage(+ deps: { readToken?: () => Promise<string | null>; fetchImpl?: typeof fetch } = {}+): Promise<ProviderUsage> {+ const token = await (deps.readToken ?? readCursorToken)().catch(() => null)+ // Signed out: no row, exactly like the other CLI-credential providers.+ if (!token) return snapshot([], 'unavailable')+ const sub = tokenSubject(token)+ let fresh: ProviderUsage+ try {+ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ const res = await (deps.fetchImpl ?? fetch)(USAGE_URL, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ 'connect-protocol-version': '1'+ },+ body: '{}',+ signal: ctrl.signal+ }).finally(() => clearTimeout(t))+ // Only the CLI renews its token, so an expired one is "nothing to show", not a failure.+ if (res.status === 401 || res.status === 403) fresh = snapshot([], 'unavailable')+ else if (!res.ok) fresh = snapshot([], 'error')+ else {+ const limits = mapCursorLimits(await cappedJson(res))+ fresh = snapshot(limits, limits.length > 0 ? 'ok' : 'unavailable')+ }+ } catch {+ fresh = snapshot([], 'error')+ }+ const out = holdCursorLastGood(lastGood, fresh, sub, Date.now())+ if (fresh.status === 'ok') lastGood = { sub, usage: fresh }+ else if (fresh.status === 'unavailable') lastGood = null+ return out+}++/** Test seam: forget the held snapshot. */+export function resetCursorUsageHold(): void {+ lastGood = null+}diff --git a/src/core/usage/usage-service.codex-accounts.test.ts b/src/core/usage/usage-service.codex-accounts.test.tsindex 41d62587a..e493a2a4f 100644--- a/src/core/usage/usage-service.codex-accounts.test.ts+++ b/src/core/usage/usage-service.codex-accounts.test.ts@@ -29,6 +29,7 @@ const { fetchCodexUsage } = vi.hoisted(() => ({}))vi.mock('./codex-usage', () => ({ fetchCodexUsage }))+vi.mock('./cursor-usage', () => ({ fetchCursorUsage: async () => unavailableRow('cursor') }))vi.mock('./gemini-usage', () => ({ fetchGeminiUsage: async () => unavailableRow('gemini') }))vi.mock('./grok-usage', () => ({ fetchGrokUsage: async () => unavailableRow('grok') }))vi.mock('./kimi-usage', () => ({ fetchKimiUsage: async () => unavailableRow('kimi') }))diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsindex d2eade358..3132d5efd 100644--- a/src/core/usage/usage-service.ts+++ b/src/core/usage/usage-service.ts@@ -24,6 +24,7 @@ import {type RemoteUsageTarget} from './remote-claude-usage'import { fetchCodexUsage } from './codex-usage'+import { fetchCursorUsage } from './cursor-usage'import { fetchRemoteCodexUsage } from './remote-codex-usage'import { fetchGeminiUsage } from './gemini-usage'import { fetchGrokUsage } from './grok-usage'@@ -65,6 +66,7 @@ const OTHER_PROVIDERS: { id: string; fetch: () => Promise<ProviderUsage> }[] = [// Codex is NOT here — it is account-scoped (one system row + one row per managed account,// built dynamically in runProviders so each row is keyed by its own accountId and can never// collapse into another). See the Codex block in runProviders and S6 §4.3 (no mixing).+ { id: 'cursor', fetch: () => fetchCursorUsage() },{ id: 'gemini', fetch: fetchGeminiUsage },{ id: 'grok', fetch: fetchGrokUsage },{ id: 'kimi', fetch: fetchKimiUsage },diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex 88c8259e6..391c6429b 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -24,6 +24,7 @@ import {CODEX_SANDBOX_BLOCKED_LINE,CODEX_SANDBOX_RETRY_LINE} from '../core/agents/hook-sandbox-hint-sh'+import { AGENT_CONFIG, MODEL_SWITCH_CAPABLE } from '../shared/agents/config'import { RETRYABLE } from '../core/agents/agent-message-decide'import {REQUEST_ID_HINT_LEAD,@@ -600,6 +601,9 @@ describe('parseControlRequest', () => {expect(body.toLowerCase()).toContain('ignore')// Per-role model is what lets ONE spawn-team call mix tiers; the JSON example must show it.expect(body).toContain('"model"')+ // The honoured-by list is MODEL_SWITCH_CAPABLE, by label (it once named three of five).+ const honoured = /Honoured by ([^(]+)\(/.exec(body.replace(/\s+/g, ' '))?.[1] ?? ''+ for (const id of MODEL_SWITCH_CAPABLE) expect(honoured, id).toContain(AGENT_CONFIG[id].label)}})diff --git a/src/main/context-ensure-wiring.test.ts b/src/main/context-ensure-wiring.test.tsindex ba40a2139..7da9a14b6 100644--- a/src/main/context-ensure-wiring.test.ts+++ b/src/main/context-ensure-wiring.test.ts@@ -29,6 +29,12 @@ describe('desktop remote context routing', () => {expect(h.locateClaude).not.toHaveBeenCalled()expect(h.claude.pathFor).not.toHaveBeenCalled()})+ it('Cursor on a remote node is a terminal "not yet": no local fallback, no claude locator', async () => {+ const h = harness()+ expect(await h.ensure({ ...q, agentId: 'cursor' })).toBe('unresolved')+ expect(h.locateClaude).not.toHaveBeenCalled()+ expect(h.claude.track).not.toHaveBeenCalled()+ })it('Claude retries unresolved discovery and tracks only the jailed resolver result', async () => {const h = harness(), ref = { path: '/remote/.claude/projects/r/session-1.jsonl' }expect(await h.ensure(q)).toBe('unresolved')diff --git a/src/main/handoff/index.test.ts b/src/main/handoff/index.test.tsindex 155f411d1..ad1a0d82c 100644--- a/src/main/handoff/index.test.ts+++ b/src/main/handoff/index.test.ts@@ -1,5 +1,6 @@-import { describe, it, expect } from 'vitest'+import { describe, it, expect, vi } from 'vitest'import { buildHandoff, handoffFilename } from './index'+import { setCustomAgentBaseResolver } from '../../shared/agents/config'describe('handoffFilename', () => {it('builds a filesystem-safe handoff filename', () => {@@ -33,6 +34,25 @@ describe('buildHandoff — grok as a transfer source', () => {expect(res).not.toEqual({ error: 'Transfer is not supported from grok.' })})+ it('cursor is a wired source, and a remote cursor node is refused before anything is read', async () => {+ const local = await buildHandoff({ sessionId: SESSION, agentId: 'cursor', sourceNodeId: 'term-1' })+ expect(local).not.toEqual({ error: 'Transfer is not supported from cursor.' })+ const remote = await buildHandoff({+ sessionId: SESSION,+ agentId: 'cursor',+ sourceNodeId: 'term-1',+ remote: {+ isRemoteNode: () => true,+ hookedTranscriptPath: () => '/should/never/be/read',+ readRemoteFile: async () => {+ throw new Error('read')+ },+ writeRemoteFile: async () => true+ }+ })+ expect(remote).toEqual({ error: 'Transferring a Cursor conversation from a remote (SSH) session is not supported yet.' })+ })+it('still refuses an agent whose renderer really is unwritten', async () => {const res = await buildHandoff({sessionId: SESSION,@@ -41,4 +61,28 @@ describe('buildHandoff — grok as a transfer source', () => {})expect(res).toEqual({ error: 'Transfer is not supported from opencode.' })})++ it('a custom cursor-base agent routes to the cursor reader (the menu already offers it Transfer)', async () => {+ setCustomAgentBaseResolver((id) => (id === 'my-cursor' ? 'cursor' : id === 'my-opencode' ? 'opencode' : undefined))+ vi.stubEnv('CURSOR_CONFIG_DIR', '/nonexistent-cursor-config')+ try {+ const local = await buildHandoff({ sessionId: SESSION, agentId: 'my-cursor', sourceNodeId: 'term-1', cwd: '/nonexistent' })+ // Reached the cursor locator: an honest "not found" on this machine, never the refusal.+ expect(local).toEqual({ error: "Couldn't find the source conversation transcript." })+ const remote = await buildHandoff({+ sessionId: SESSION,+ agentId: 'my-cursor',+ sourceNodeId: 'term-1',+ remote: { isRemoteNode: () => true, hookedTranscriptPath: () => '/x', readRemoteFile: async () => null, writeRemoteFile: async () => true }+ })+ expect(remote).toEqual({ error: 'Transferring a Cursor conversation from a remote (SSH) session is not supported yet.' })+ // A base with no renderer is still refused, by the name the user knows.+ expect(await buildHandoff({ sessionId: SESSION, agentId: 'my-opencode', sourceNodeId: 'term-1' })).toEqual({+ error: 'Transfer is not supported from my-opencode.'+ })+ } finally {+ setCustomAgentBaseResolver(null)+ vi.unstubAllEnvs()+ }+ })})diff --git a/src/main/handoff/index.ts b/src/main/handoff/index.tsindex 455c0dcad..499f800bb 100644--- a/src/main/handoff/index.ts+++ b/src/main/handoff/index.ts@@ -19,6 +19,9 @@ import { renderGeminiTranscript } from './render-gemini'import { renderGrokTranscript } from './render-grok'import { budgetHandoff } from './budget'import { locateClaude, locateCodex, locateGemini, locateGrok } from '../../core/handoff/locate'+import { cursorTranscriptText, locateCursorChat } from '../../core/cursor-chat'+import { renderCursorTranscript } from './render-cursor'+import { capabilityAgentId } from '../../shared/agents/config'export type HandoffResult = { filePath: string } | { error: string }@@ -29,14 +32,17 @@ const RENDERERS: Record<string, Renderer> = {claude: renderClaudeTranscript,codex: renderCodexTranscript,gemini: renderGeminiTranscript,- grok: renderGrokTranscript+ grok: renderGrokTranscript,+ cursor: renderCursorTranscript}const LOCATORS: Record<string, Locator> = {claude: locateClaude,codex: locateCodex,gemini: locateGemini,- grok: locateGrok+ grok: locateGrok,+ // (id, accountId?) is the shared shape; cursor's second parameter is a cwd, so it is not passed.+ cursor: (sessionId) => locateCursorChat(sessionId)}/** Filesystem-safe handoff filename for a node + ISO-ish timestamp. Node ids are@@ -80,8 +86,16 @@ export async function buildHandoff(opts: {}): Promise<HandoffResult> {const { sessionId, agentId, sourceNodeId, cwd, accountId } = optsif (!sessionId || !SESSION_ID_RE.test(sessionId)) return { error: 'No valid session id to transfer.' }- const render = RENDERERS[agentId]+ // Routing only: a custom agent's conversation is its base harness's (`canTransferFrom` already+ // resolves it, so the menu offers Transfer). The header still names the agent the user picked.+ const base = capabilityAgentId(agentId)+ const render = RENDERERS[base]if (!render) return { error: `Transfer is not supported from ${agentId}.` }+ // cursor's chat is a SQLite store on the node's host; there is no remote reader, and the hook-fed+ // path below is for an agent whose transcript is a text file. Refuse rather than read either.+ if (base === 'cursor' && opts.remote?.isRemoteNode(sourceNodeId)) {+ return { error: 'Transferring a Cursor conversation from a remote (SSH) session is not supported yet.' }+ }// Everything below branches on ONE question: does this node's session live on a remote host?const remote = opts.remote?.isRemoteNode(sourceNodeId) ? opts.remote : undefined@@ -101,12 +115,14 @@ export async function buildHandoff(opts: {raw = await remote.readRemoteFile(sourceNodeId, src, REMOTE_TRANSCRIPT_MAX_BYTES)if (raw === null) return { error: 'Failed to read the source transcript from the remote host.' }} else {- const locate = LOCATORS[agentId]+ const locate = LOCATORS[base]if (!locate) return { error: `Transfer is not supported from ${agentId}.` }const src = await locate(sessionId, accountId)if (!src) return { error: "Couldn't find the source conversation transcript." }try {- raw = await fs.promises.readFile(src, 'utf8')+ // cursor's `src` is its store.db: its own reader turns it into transcript text.+ raw = base === 'cursor' ? await cursorTranscriptText(src) : await fs.promises.readFile(src, 'utf8')+ if (raw === null) throw new Error('unreadable')} catch {return { error: 'Failed to read the source transcript.' }}diff --git a/src/main/handoff/render-cursor.test.ts b/src/main/handoff/render-cursor.test.tsnew file mode 100644index 000000000..f516d0038--- /dev/null+++ b/src/main/handoff/render-cursor.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest'+import { renderCursorTranscript } from './render-cursor'++const line = (o: unknown): string => JSON.stringify(o)+const NDJSON = [+ line({ role: 'system', content: 'SYSTEM PROMPT' }),+ line({ role: 'user', content: '<user_info>secret-rule-text</user_info>' }),+ line({ role: 'user', content: [{ type: 'text', text: '<user_query>\nRun echo and tell me the word.\n</user_query>' }] }),+ line({ role: 'assistant', content: [{ type: 'reasoning', text: 'ENCRYPTED' }, { type: 'text', text: 'On it.' }] }),+ line({ role: 'assistant', content: [{ type: 'tool-call', toolCallId: 't1', toolName: 'Write', args: { path: '/w/a.txt', contents: 'hi' } }] }),+ line({ role: 'tool', content: [{ type: 'tool-result', toolCallId: 't1', toolName: 'Write', result: 'Command completed in 9 ms.' }] })+].join('\n')++describe('renderCursorTranscript', () => {+ it('renders typed prompts, replies, and full tool args and results, without injected context', () => {+ const md = renderCursorTranscript(NDJSON)+ expect(md).toContain('## User\n\nRun echo and tell me the word.')+ expect(md).toContain('## Assistant\n\nOn it.')+ expect(md).toContain('### Tool call: Write')+ expect(md).toContain('"contents": "hi"')+ expect(md).toContain('Command completed in 9 ms.')+ for (const leak of ['secret-rule-text', 'SYSTEM PROMPT', 'ENCRYPTED']) expect(md).not.toContain(leak)+ })+ it('answers an empty string for empty or junk input', () => {+ expect(renderCursorTranscript('')).toBe('')+ expect(renderCursorTranscript('{not json\n')).toBe('')+ })+})diff --git a/src/main/handoff/render-cursor.ts b/src/main/handoff/render-cursor.tsnew file mode 100644index 000000000..a2f0f63ef--- /dev/null+++ b/src/main/handoff/render-cursor.ts@@ -0,0 +1,30 @@+// Renders cursor's conversation to full Markdown. The input is the transcript text+// `cursorTranscriptText` builds from the chat's SQLite store: one message JSON per line (see+// core/cursor-chat.ts for the shapes). Unlike the summarised chat view this keeps every tool call's+// arguments and every result in full. A user message that is not a `<user_query>` is harness context+// (rules, skills, environment), never something the human said, so it is left out; so is reasoning.+import { cursorUserText, parseCursorNdjson } from '../../core/cursor-chat'+import { blockText, fenceJson } from './format'++const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)++export function renderCursorTranscript(raw: string): string {+ const out: string[] = []+ for (const m of parseCursorNdjson(raw)) {+ if (!isObj(m) || !Array.isArray(m.content)) continue+ for (const c of m.content as unknown[]) {+ if (!isObj(c)) continue+ if (m.role === 'user' && c.type === 'text' && typeof c.text === 'string') {+ const t = cursorUserText(c.text)+ if (t !== undefined) out.push(`## User\n\n${t}`)+ } else if (m.role === 'assistant' && c.type === 'text' && typeof c.text === 'string' && c.text.trim()) {+ out.push(`## Assistant\n\n${c.text}`)+ } else if (m.role === 'assistant' && c.type === 'tool-call') {+ out.push(`### Tool call: ${String(c.toolName ?? 'tool')}\n\n${fenceJson(c.args)}`)+ } else if (m.role === 'tool' && c.type === 'tool-result') {+ out.push('### Tool result\n\n```\n' + blockText(c.result) + '\n```')+ }+ }+ }+ return out.join('\n\n')+}diff --git a/src/main/index.ts b/src/main/index.tsindex 80ef808eb..ed32569f5 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -280,18 +280,20 @@ import { createBackgroundTray, type BackgroundTray } from './tray'import { normalizeUnread, trayIconPath, type TrayState } from './tray-model'import { planBadge, rasterizeBadge } from './taskbar-badge'import { createSubagentTail } from '../core/subagent-tail'+import { createCursorSubagentTracker } from '../core/cursor-subagents'import { ClaudeSubagentLifecycle } from '../core/claude-subagent-lifecycle'import { claudeSubagentTranscriptPath, isClaudeAgentId } from '../shared/agents/claude-subagents'import { createContextTail, type TaskNotification } from '../core/context-tail'import { registerContextEnsureIpc } from '../core/context-ensure'import { grokContextParse, GROK_SIGNALS_FILE } from '../core/grok-signals'+import { applyCursorRaw, cursorContextParse, readCursorContextSource, releaseCursorRaw } from '../core/cursor-chat'import { GROK_CHAT_HISTORY_FILE } from '../core/agents/grok-paths'import { createGrokSubagentFormatter } from '../core/grok-subagent-format'import { geminiContextParse } from '../core/gemini-session'import { codexContextParse, codexContextModel } from '../core/codex-session'import { createCodexSubagentFormatter } from '../core/codex-subagent-format'import { codexHome } from '../core/usage/codex-usage'-import { isAsyncSubagentLaunch, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'+import { isAsyncSubagentLaunch, isCursorPayload, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'import { applyGrokHookSession } from '../core/grok-hook-session'import { agentAccountColor } from '../shared/agents/account-color'import { capabilityAgentId } from '../shared/agents/config'@@ -369,6 +371,7 @@ import { initCodexAccounts } from './codex-accounts'import { claudeCliCaps, registerClaudeCliIpc, type ClaudeCliCaps } from '../core/claude-cli'import type { CodexCliCaps } from '../shared/types'import { registerGrokCliIpc } from '../core/grok-cli'+import { registerCursorCliIpc } from '../core/cursor-cli'import { refreshCodexIdentityCaps, registerCodexIdentityIpc } from '../core/codex-identity-caps'import { codexCliCaps, registerCodexCliIpc } from '../core/codex-cli'import { registerWallpaperIpc, setWallpaperImageOps } from '../core/wallpaper'@@ -1720,6 +1723,7 @@ app.whenReady().then(async () => {// Invariant 11 for probes: registered in BOTH shells, or session-id minting silently works on// the desktop and not in the browser, with nothing to say which.registerGrokCliIpc()+ registerCursorCliIpc()registerCodexIdentityIpc()// What THIS machine's codex accepts for `--ask-for-approval`. Lazy + memoized inside the probe,// so registering it costs nothing until the first Codex launch line asks.@@ -2982,6 +2986,14 @@ app.whenReady().then(async () => {remoteSubagentTail.untrack(n.toolUseId)nodeSubagents.get(nodeId)?.delete(n.toolUseId)}+ // Cursor's subagent END (its hooks never send one) and child tail; same tracker in the server.+ const cursorSubagents = createCursorSubagentTracker({+ tail: subagentTail,+ emit: (ev) => {+ sendToMain(IPC.agentStatus, ev)+ recordAgentEvent(ev)+ }+ })// Every context tail pushes through here, so an agent's meter reaches the renderer, the Notch HUD// and the phone's context ring identically whichever CLI produced the numbers.const pushContextUpdate = (payload: unknown): void => {@@ -3020,6 +3032,12 @@ app.whenReady().then(async () => {parse: grokContextParse,wholeFile: true})+ // cursor's fourth tail. Its numbers are in a SQLite store, not a text file, so `readSource` replaces+ // the byte read (stat-gated on the db + WAL). Same construction in both shells (invariant 11).+ const cursorContextTail = createContextTail(pushContextUpdate, {+ parse: cursorContextParse,+ readSource: readCursorContextSource+ })// Remote (SSH-project) counterparts: a node whose pty runs on a remote host has its Claude// transcript on that host, so its meter / subagent transcript / search must read over the// project's ControlMaster. One RemoteFile bound to the SSH-project manager's own ssh runner@@ -3327,6 +3345,8 @@ app.whenReady().then(async () => {return codexContextTailcase 'gemini':return geminiContextTail+ case 'cursor':+ return cursorContextTaildefault:return undefined}@@ -3421,6 +3441,8 @@ app.whenReady().then(async () => {}}hookServer.setListener(emitAgentStatus)+ // Cursor NEEDS YOU: up to three pane reads per tool call still pending (core/agents/cursor-approval.ts).+ hookServer.setPaneReader((nodeId) => ptyManager.captureSession(nodeId))// Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the canvas Approve/Deny// buttons (and any relay client) answer a held Claude permission hook here. Route by the node's// project: an SSH project's hook runs on the REMOTE host (write over its ControlMaster), a local@@ -3749,6 +3771,21 @@ app.whenReady().then(async () => {const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])// Hook server validates session-env capacity and caller identity once for both shells.hookServer.setRawListener((agentId, nodeId, payload, _meta) => {+ if (agentId === 'cursor') {+ // One shared step (core/cursor-chat.ts `applyCursorRaw`): subagent cards, the meter, and the+ // child-event guard. A remote node gets cards but no meter (its chat is on the host).+ applyCursorRaw(+ {+ tail: cursorContextTail,+ subagents: cursorSubagents,+ nodeSession: nodeContextSession,+ isRemote: (id) => !!(ptyManager.sshRemoteForNode(id) || workspaceStore.sshProjectIdForNode(id))+ },+ nodeId,+ payload+ )+ return+ }if (agentId === 'grok') {// This branch records two associations, neither of which grok's envelope states outright.// Everything the claude path does below hangs off `transcript_path`. Grok DOES send one --@@ -3906,6 +3943,9 @@ app.whenReady().then(async () => {// Runs BEFORE the local/remote split so it covers remote (SSH) nodes too — it needs only// tool_name/tool_input, never the transcript path the split routes on.recordRawToolEvent(nodeId, payload)+ // Cursor runs claude.sh too (Claude settings import), often with a CHILD's chat id: recording it+ // here re-pointed the node's session, so the parent's cursor tail leaked past pty:destroy.+ if (isCursorPayload(payload)) return// Claude's native subagent hooks, BEFORE the child-event gate below: that gate ignores every// agent_id-tagged payload, and these carry the CHILD's agent_id with the PARENT's// transcript_path. All they drive here is the child's own transcript tail, started at@@ -4060,6 +4100,9 @@ app.whenReady().then(async () => {const releaseNodeTails = (nodeId: string): void => {claudeSubagents.forgetNode(nodeId)remoteCodexContext.release(nodeId)+ cursorSubagents.release(nodeId)+ releaseCursorRaw(nodeId)+ hookServer.releaseCursorNode(nodeId)const sessionId = nodeContextSession.get(nodeId)if (sessionId) {// Untrack both tails — untracking a non-tracked session is a no-op, so this is safe@@ -4072,6 +4115,7 @@ app.whenReady().then(async () => {geminiContextTail.untrack(sessionId)codexContextTail.untrack(sessionId)grokContextTail.untrack(sessionId)+ cursorContextTail.untrack(sessionId)remoteContextTail.untrack(sessionId)remoteTranscriptBySession.delete(sessionId)locatedTranscriptSessions.delete(sessionId)diff --git a/src/main/remote-ssh/remote-cursor-hooks.test.ts b/src/main/remote-ssh/remote-cursor-hooks.test.tsnew file mode 100644index 000000000..802222bce--- /dev/null+++ b/src/main/remote-ssh/remote-cursor-hooks.test.ts@@ -0,0 +1,105 @@+// RemoteHooks.installCursorRemote under a REAL /bin/sh against a fake host tree (the+// remote-settings-preservation.test.ts precedent). PATH is pinned to the system dirs so this+// machine's own cursor-agent cannot answer the host probe.+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { spawnSync } from 'child_process'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'+import path from 'path'+import { tmpdir } from 'os'+import { RemoteHooks } from './remote-hooks'+import { allRemote } from './remote-hooks.test-plan'+import { CURSOR_HOOK_EVENTS } from '@shared/agents/hook-events'++let home: string+beforeEach(() => { home = mkdtempSync(path.join(tmpdir(), 'nt-cursor-host-')) })+afterEach(() => rmSync(home, { recursive: true, force: true }))++const conn = { host: 'fixture', user: 'fixture' }+const hooksJson = (): string => path.join(home, '.cursor', 'hooks.json')+const script = (): string => path.join(home, '.nodeterm', 'agent-hooks', 'cursor.sh')++function giveHostCursor(): void {+ const bin = path.join(home, '.local', 'bin', 'cursor-agent')+ mkdirSync(path.dirname(bin), { recursive: true })+ writeFileSync(bin, '#!/bin/sh\n')+ chmodSync(bin, 0o755)+}++async function install(remoteDir = `${home}/.nodeterm`) {+ const calls: { command: string; stdin?: string }[] = []+ const rh = new RemoteHooks({ run: async (args, stdin) => {+ const command = args.at(-1)!+ calls.push({ command, stdin })+ const r = spawnSync('/bin/sh', ['-c', command], { input: stdin, encoding: 'utf8', env: { PATH: '/usr/bin:/bin', HOME: home } })+ if (r.error) throw r.error+ return { code: r.status ?? 1, stdout: r.stdout }+ } }, allRemote)+ await rh['installCursorRemote'](conn, '/fixture.sock', home, remoteDir)+ return calls+}++describe.skipIf(process.platform === 'win32')('remote cursor hook installer', () => {+ it('merges our five events into the host hooks.json, keeping other tools, content over stdin', async () => {+ giveHostCursor()+ mkdirSync(path.dirname(hooksJson()), { recursive: true })+ const foreign = { command: 'other-tool start', timeout: 9 }+ writeFileSync(hooksJson(), JSON.stringify({ version: 1, other: true, hooks: { sessionStart: [foreign], stop: [foreign] } }))+ const calls = await install()+ const doc = JSON.parse(readFileSync(hooksJson(), 'utf8'))+ expect(doc.other).toBe(true)+ expect(doc.hooks.sessionStart).toEqual([foreign])+ for (const ev of CURSOR_HOOK_EVENTS) {+ const ours = doc.hooks[ev].filter((e: { command: string }) => e.command.includes('.nodeterm/agent-hooks/cursor.sh'))+ expect(ours, ev).toHaveLength(1)+ expect(ours[0].command).not.toContain('//')+ }+ expect(doc.hooks.stop[0]).toEqual(foreign)+ expect(statSync(script()).mode & 0o777).toBe(0o755)+ // Never in argv: no command line carries the document or the script body.+ for (const c of calls) {+ expect(c.command).not.toContain('"hooks"')+ expect(c.command).not.toContain('other-tool')+ }+ // Idempotent: a second run publishes nothing (no lock/stdin transaction).+ const again = await install()+ expect(again.some((c) => c.command.includes('.nodeterm-lock'))).toBe(false)+ })++ it('creates the file when absent', async () => {+ giveHostCursor()+ await install()+ const doc = JSON.parse(readFileSync(hooksJson(), 'utf8'))+ expect(doc.version).toBe(1)+ expect(Object.keys(doc.hooks).sort()).toEqual([...CURSOR_HOOK_EVENTS].sort())+ })++ it('writes nothing on a host without cursor-agent', async () => {+ await install()+ expect(existsSync(hooksJson())).toBe(false)+ expect(existsSync(script())).toBe(false)+ })++ it('leaves an unparseable file byte-for-byte', async () => {+ giveHostCursor()+ mkdirSync(path.dirname(hooksJson()), { recursive: true })+ writeFileSync(hooksJson(), '{broken')+ await install()+ expect(readFileSync(hooksJson(), 'utf8')).toBe('{broken')+ })++ it('skips while another writer holds the lock', async () => {+ giveHostCursor()+ mkdirSync(path.dirname(hooksJson()), { recursive: true })+ writeFileSync(hooksJson(), '{}')+ mkdirSync(`${hooksJson()}.nodeterm-lock`)+ await install()+ expect(readFileSync(hooksJson(), 'utf8')).toBe('{}')+ })++ it('refuses a command holding "//" (cursor would strip it as a JSONC comment)', async () => {+ giveHostCursor()+ const calls = await install(`${home}//.nodeterm`)+ expect(calls).toEqual([])+ expect(existsSync(hooksJson())).toBe(false)+ })+})diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 1e0b800c5..d06392495 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -35,6 +35,7 @@ import {COPILOT_HOOK_FILE,isSafeRemoteCopilotHome} from '../../core/agents/hooks/copilot'+import { applyCursorHooks, cursorCommandFor, CURSOR_SCRIPT_FILE } from '../../core/agents/hooks/cursor'/*** Remote hook scripts get NO Codex thread-identity root.@@ -180,9 +181,10 @@ const accountConfigDir = (home: string, accountId: string) => `${home}/.nodeterm* codex 0.156.1 `debug prompt-input`, gemini 0.62.0 `skills list`, opencode 1.18.33 `debug skill`,* grok 1.0.44 `inspect --json`; copilot 1.0.89 documents it in `copilot skill --help`). One* env-independent dir is what a host we cannot introspect cheaply needs: `$COPILOT_HOME`,- * `$GROK_HOME` and `$XDG_CONFIG_HOME` on the host say nothing about it.+ * `$GROK_HOME` and `$XDG_CONFIG_HOME` on the host say nothing about it. cursor-agent loads+ * `~/.agents/skills` too (its bundle's skill roots, docs/cursor-agent.md; not run on a host).*/-const AGENTS_SKILLS_AGENTS: readonly string[] = ['codex', 'gemini', 'copilot', 'opencode', 'grok']+const AGENTS_SKILLS_AGENTS: readonly string[] = ['codex', 'gemini', 'copilot', 'opencode', 'grok', 'cursor']const claudeSkillsRoot = (home: string) => `${home}/.claude`const agentsSkillsRoot = (home: string) => `${home}/.agents`@@ -489,7 +491,9 @@ export class RemoteHooks {// grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME....(plan.install.has('grok') ? [this.installGrokRemote(conn, controlPath, home, remoteDir)] : []),// copilot: its own file/grammar under the HOST's $COPILOT_HOME hooks directory.- ...(plan.install.has('copilot') ? [this.installCopilotRemote(conn, controlPath, home, remoteDir)] : [])+ ...(plan.install.has('copilot') ? [this.installCopilotRemote(conn, controlPath, home, remoteDir)] : []),+ // cursor: merge into the host's SHARED ~/.cursor/hooks.json, only where cursor-agent exists.+ ...(plan.install.has('cursor') ? [this.installCursorRemote(conn, controlPath, home, remoteDir)] : [])])for (const r of installs) {if (r.status === 'rejected') {@@ -539,6 +543,10 @@ export class RemoteHooks {if (plan.remove.has('codex')) {await stripRemoteSettingsFile(`${home}/.codex/hooks.json`, run, (cfg) => (stripCodexManagedHooks(cfg as CodexHooksConfig) ?? cfg) as Record<string, unknown>)}+ if (plan.remove.has('cursor')) {+ // Our entries only (exact managed command); the IDE's and other tools' hooks stay.+ await stripRemoteSettingsFile(`${home}/.cursor/hooks.json`, run, (cfg) => (cfg.hooks === undefined ? cfg : applyCursorHooks(cfg, null)))+ }// Files we own outright: grok's and copilot's hook configs, and our hook scripts.const owned: string[] = []if (plan.remove.has('grok')) {@@ -928,6 +936,40 @@ export class RemoteHooks {}}+ /**+ * Install Cursor's status hook on the host: the same pure merge as the local installer+ * (`applyCursorHooks`: other tools' entries survive, an unparseable file is left alone) through+ * the locked stdin transaction (`updateRemoteSettingsFile`). Only where `cursor-agent` is on the+ * host (PATH, or the vendor's `~/.local/bin`, which a non-login ssh shell often lacks): the file+ * is shared with the Cursor IDE, so a host without the CLI gets nothing written. A command+ * holding `//` is refused (cursor strips it as a JSONC comment and the whole file breaks).+ * Fail-open, but logged (`warnNotInstalled`).+ */+ private async installCursorRemote(+ conn: SshConnection,+ controlPath: string,+ home: string,+ remoteDir: string+ ): Promise<void> {+ try {+ const script = `${remoteDir}/agent-hooks/${CURSOR_SCRIPT_FILE}`+ const command = cursorCommandFor(script)+ if (command.includes('//')) return+ const probe = await this.r.run(childArgs(conn, controlPath,+ `command -v cursor-agent >/dev/null 2>&1 || [ -x ${posixQuote(`${home}/.local/bin/cursor-agent`)} ]`))+ if (probe.code !== 0) return+ await this.writeOwnedFile(conn, controlPath, script, buildManagedScript('cursor', REMOTE_IDENTITY_ROOT), {+ mode: '755'+ })+ await updateRemoteSettingsFile(`${home}/.cursor/hooks.json`,+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),+ (cfg) => applyCursorHooks(cfg, command))+ } catch (e) {+ // Fail-open for the connect, not silent: the remote cursor session runs without status hooks.+ warnNotInstalled('cursor status hook', e)+ }+ }+private async resolveCopilotHome(conn: SshConnection,controlPath: string,diff --git a/src/main/remote-ssh/remote-integration-consent.test.ts b/src/main/remote-ssh/remote-integration-consent.test.tsindex 9cb7cf736..d8e60ec29 100644--- a/src/main/remote-ssh/remote-integration-consent.test.ts+++ b/src/main/remote-ssh/remote-integration-consent.test.ts@@ -3,7 +3,7 @@// wrote there (a file the user changed is kept and reported), and a host the user keeps has its// older builds' instruction blocks stripped.import { spawnSync } from 'child_process'-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import path from 'path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -114,6 +114,36 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.applyIntegrationRemovexpect(has('.claude/skills/manage-nodeterm-canvas/SKILL.md')).toBe(true)})+ it('cursor: installed only when the plan installs it, skills in ~/.agents, a removal strips only our entries', async () => {+ const bin = path.join(home, '.local/bin/cursor-agent')+ mkdirSync(path.dirname(bin), { recursive: true })+ writeFileSync(bin, '#!/bin/sh\n')+ chmodSync(bin, 0o755)+ // A host that has cursor-agent but whose plan does not install cursor gets nothing of cursor's.+ await new RemoteHooks(hostRunner(), () => plan(['claude'], [])).installAgentHooks(conn, '/fixture.sock', home)+ expect(has('.cursor/hooks.json')).toBe(false)+ expect(has('.nodeterm/agent-hooks/cursor.sh')).toBe(false)++ const on = new RemoteHooks(hostRunner(), () => plan(['cursor'], []))+ await on.installAgentHooks(conn, '/fixture.sock', home)+ await on.installAgentTools(conn, '/fixture.sock', home)+ expect(read('.cursor/hooks.json')).toContain('agent-hooks/cursor.sh')+ expect(has('.nodeterm/agent-hooks/cursor.sh')).toBe(true)+ expect(has('.agents/skills/manage-nodeterm-canvas/SKILL.md')).toBe(true)+ expect(has('.agents/skills/get-linked-context/SKILL.md')).toBe(true)+ // The Cursor IDE's own hook beside ours.+ const cfg = JSON.parse(read('.cursor/hooks.json')) as { hooks: Record<string, unknown[]> }+ cfg.hooks.stop.push({ command: 'ide-hook' })+ writeFileSync(path.join(home, '.cursor/hooks.json'), JSON.stringify(cfg))++ await new RemoteHooks(hostRunner(), () => plan([], ['cursor'])).applyIntegrationRemovals(conn, '/fixture.sock', home, [])+ const after = read('.cursor/hooks.json')+ expect(after).not.toContain('agent-hooks/cursor.sh')+ expect(after).toContain('ide-hook')+ expect(has('.nodeterm/agent-hooks/cursor.sh')).toBe(false)+ expect(has('.agents/skills/manage-nodeterm-canvas')).toBe(false)+ })+it("an answered host has older builds' instruction blocks stripped, keeping the user's text", async () => {mkdirSync(path.join(home, '.codex'), { recursive: true })writeFileSync(path.join(home, '.codex/AGENTS.md'), `# mine\n\n${frameCanvasControlBlock('OLD 17 KB')}\n`)diff --git a/src/preload/index.ts b/src/preload/index.tsindex 60f3bdfce..bb08a0483 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -681,6 +681,9 @@ const api: NodeTerminalApi = {cliCaps: () => ipcRenderer.invoke(IPC.grokCliCaps),takenSessionIds: (cwd) => ipcRenderer.invoke(IPC.grokTakenSessionIds, cwd)},+ cursor: {+ cliCaps: () => ipcRenderer.invoke(IPC.cursorCliCaps)+ },agent: {envSnapshot: () => ipcRenderer.invoke(IPC.envSnapshot),discoverModels: (settings) => ipcRenderer.invoke(IPC.agentDiscoverModels, settings),diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex a57df30c6..830128d6a 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -1,7 +1,7 @@import React from 'react'import ReactDOM from 'react-dom/client'import App from './App'-import { ensureClaudeCliCaps, ensureGrokCliCaps } from './state/permissionMode'+import { ensureClaudeCliCaps, ensureCursorCliCaps, ensureGrokCliCaps } from './state/permissionMode'import { ensureCodexIdentityCaps } from './state/codexIdentity'import { ensureCodexCliCaps } from './state/codexCli'import { initAgentResolver } from './state/agent-resolver'@@ -44,6 +44,8 @@ void ensureClaudeCliCaps()// Same, for grok: its own probe, kicked off at boot so a node created seconds later already has// the real answer instead of the fail-open one.void ensureGrokCliCaps()+// cursor's model list is network-backed: kick it off at boot so the menu is ready, never awaited.+void ensureCursorCliCaps()// Same shape, same reason: a Codex launch line names the managed shared-identity launcher only if// this machine has one installed and armed. Unprobed ⇒ plain `codex`, which is what every Codexdiff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex e8bf5a4f3..713a19808 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -17,6 +17,7 @@import {UNKNOWN_CLAUDE_CLI_CAPS,UNKNOWN_GROK_CLI_CAPS,+ UNKNOWN_CURSOR_CLI_CAPS,UNKNOWN_CODEX_IDENTITY_CAPS,UNKNOWN_CODEX_CLI_CAPS,type ClaudeUsage,@@ -417,6 +418,10 @@ export function buildStubApi(): Omit<// behaviour: mint freely. Overridden by the real WS-backed namespace in ws-bridge.takenSessionIds: () => Promise.resolve([])},+ cursor: {+ // Overridden by the real WS-backed namespace in ws-bridge. Never rejects: empty = no picker.+ cliCaps: () => Promise.resolve(UNKNOWN_CURSOR_CLI_CAPS)+ },agent: {// No env snapshot outside the desktop window: the stub (and ws-bridge, identically) answers// an empty env, so `${env:VAR}` expansion reports every referenced var as missing and thediff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 51f4019cf..494de01a7 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -32,6 +32,9 @@ import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issuimport {UNKNOWN_CLAUDE_CLI_CAPS,UNKNOWN_GROK_CLI_CAPS,+ UNKNOWN_CURSOR_CLI_CAPS,+ type CursorApi,+ type CursorCliCaps,type BoardLogApi,type LogApi,type LogRecord,@@ -1200,6 +1203,16 @@ export function buildGrokApi(client: RpcClient): GrokApi {}}+/** cursor's model catalogue over WS-RPC: a REAL handler server-side (`registerCursorCliIpc`). */+export function buildCursorApi(client: RpcClient): CursorApi {+ return {+ cliCaps: () =>+ (client.request(IPC.cursorCliCaps) as Promise<CursorCliCaps>).catch(+ () => UNKNOWN_CURSOR_CLI_CAPS+ )+ }+}+/*** The two transcript READ channels, now that `registerTranscriptIpc` serves them in the server* shell too. Before this the browser had no handler at all: the stub rejected, the ⌘M panel never@@ -1448,7 +1461,8 @@ export async function installWsBridge(): Promise<boolean> {return {chat: t.chat,claude: { ...buildClaudeApi(client, stubApi.claude), readTranscript: t.claudeReadTranscript },- grok: buildGrokApi(client)+ grok: buildGrokApi(client),+ cursor: buildCursorApi(client)}})(),// Web replacement for the Electron native dialog: an in-app server-directory browser overdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex ca90c049e..869247831 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -575,6 +575,7 @@ import {canRename,canContextLink,canSwitchModel,+ hasGatewayModels,capabilityAgentId,createdAgentId,resumeCommand,@@ -759,7 +760,7 @@ import {} from '@shared/node-colors'import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'import { useSettings } from '../state/settings'-import { activePermissionMode, grokCliCapsNow, projectPermissionMode } from '../state/permissionMode'+import { activePermissionMode, cursorCliCapsNow, grokCliCapsNow, projectPermissionMode } from '../state/permissionMode'import { useContextWindow } from '../state/contextWindow'import { useSessionNaming } from '../state/sessionNaming'import { useSshServers } from '../state/sshServers'@@ -1887,6 +1888,7 @@ export function Canvas() {// through the same probe memo the launch path uses; `modelsForAgent` decides who gets it, so no// model id and no agent id is spelled here.const grokModelList = (): GatewayModel[] => grokCliCapsNow().models.map((id) => ({ id }))+ const cursorModelList = (): GatewayModel[] => cursorCliCapsNow().modelsconst gatewayStatus = useModelGateway((s) => s.status)const gatewayError = useModelGateway((s) => s.error)const discoverModels = useModelGateway((s) => s.discover)@@ -6680,12 +6682,13 @@ export function Canvas() {// The default gateway model applies ONLY when the launch mode asks for it// (`agentLaunchMode === 'gateway-model'`). 'gateway' launches with the CLI's own default// model, and 'subscription' strips the gateway entirely so its model is moot. Gated on- // `canSwitchModel` (base-resolved) so a non-capable agent is left model-less.+ // `hasGatewayModels` (base-resolved) so a non-capable agent is left model-less, and so is one+ // whose models are its own CLI's (grok, cursor): a gateway id is not in their catalogue.const settings = useSettings.getState().settingsconst model =settings.agentLaunchMode === 'gateway-model' &&settings.modelGatewayDefaultModel &&- canSwitchModel(agentId)+ hasGatewayModels(agentId)? settings.modelGatewayDefaultModel: undefined// Built OUTSIDE the setNodes updater so the caller gets the node back (the board assigns the@@ -10587,6 +10590,7 @@ export function Canvas() {'node.newAgent.grok': () => { addAgentNode('grok'); return true },'node.newAgent.copilot': () => { addAgentNode('copilot'); return true },'node.newAgent.antigravity': () => { addAgentNode('antigravity'); return true },+ 'node.newAgent.cursor': () => { addAgentNode('cursor'); return true },'node.newSticky': () => { addSticky(); return true },'node.newBrowser': () => { addBrowser(); return true },// Opening the URL prompt IS claiming the chord — a cancelled prompt creates nothing, but the@@ -10854,6 +10858,7 @@ export function Canvas() {gatewayStatus,gatewayError,grokModels: () => grokModelList(),+ cursorModels: () => cursorModelList(),addToExistingGroup,groupSelection,removeFromGroup,@@ -10939,6 +10944,7 @@ export function Canvas() {gatewayStatus,gatewayError,grokModels: () => grokModelList(),+ cursorModels: () => cursorModelList(),writes,liveLinkMenuItems: liveLink,connectedProjectIdForHost,diff --git a/src/renderer/components/UsageIndicator.cursor.test.tsx b/src/renderer/components/UsageIndicator.cursor.test.tsxnew file mode 100644index 000000000..42664e521--- /dev/null+++ b/src/renderer/components/UsageIndicator.cursor.test.tsx@@ -0,0 +1,75 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DEFAULT_SETTINGS, type ClaudeUsage, type ProviderUsage, type UsageLimit } from '@shared/types'+import { useSettings } from '../state/settings'+import { UsageIndicator } from './UsageIndicator'++const limit = (over: Partial<UsageLimit>): UsageLimit => ({+ kind: 'session', group: 'session', usedPercent: 0, severity: null,+ resetsAt: null, windowMinutes: null, scopeLabel: null, isActive: false, ...over+})+const claude = (limits: UsageLimit[]): ClaudeUsage => ({+ status: limits.length ? 'ok' : 'unavailable', limits, session: null, weekly: null, email: null, updatedAt: 0+})+const row = (provider: string, limits: UsageLimit[]): ProviderUsage => ({+ provider, limits, account: null, updatedAt: 0, status: 'ok'+})+const cursor = row('cursor', [+ limit({ kind: 'monthly', usedPercent: 35 }),+ limit({ kind: 'monthly_scoped', scopeLabel: 'Auto', usedPercent: 33 }),+ limit({ kind: 'monthly_scoped', scopeLabel: 'API', usedPercent: 100 })+])++let host: HTMLDivElement+let root: Root++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, usagePercentMode: 'used' } })+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useSettings.setState({ settings: DEFAULT_SETTINGS })+ vi.unstubAllGlobals()+})++async function pill(system: ClaudeUsage, providers: ProviderUsage[]): Promise<string> {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ vi.stubGlobal('nodeTerminal', { usage: {+ fetch: async () => system,+ providers: async () => providers,+ onUpdate: () => () => {}+ } })+ await act(async () => root.render(<UsageIndicator />))+ // Providers load when the popover opens.+ await act(async () => host.querySelector('.usage-indicator')!.dispatchEvent(+ new MouseEvent('mouseover', { bubbles: true })+ ))+ return host.querySelector('.usage-pill__summary')?.textContent ?? ''+}++describe('usage pill: Cursor buckets', () => {+ it('shows all three Cursor numbers after the other segments', async () => {+ const text = await pill(claude([limit({ usedPercent: 92 })]),+ [row('grok', [limit({ usedPercent: 10 }), limit({ kind: 'weekly_all', usedPercent: 44 })]), cursor])+ expect(text).toBe('92% 5h·44% Grok·35% Cursor·33% auto·100% api')+ })++ it('leaves every other provider on its single worst limit, text unchanged', async () => {+ const text = await pill(claude([limit({ usedPercent: 92 }), limit({ kind: 'weekly_all', usedPercent: 44 })]), [+ row('grok', [limit({ usedPercent: 10 }), limit({ kind: 'weekly_all', usedPercent: 61 })]),+ row('kimi', [limit({ usedPercent: 7 })])+ ])+ expect(text).toBe('92% 5h·44% wk·61% Grok·7% Kimi')+ })++ it('leads with Cursor when it is the only provider, with no stray separator', async () => {+ expect(await pill(claude([]), [cursor])).toBe('35% Cursor·33% auto·100% api')+ })+})diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex bea7f03a8..240ffa96e 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -32,7 +32,8 @@ import {limitLabel,limitShortLabel,primaryLimit,- providerLabel+ providerLabel,+ providerPillSegments} from '@shared/usage-limits'import { systemAccountDisplay } from '../state/workspace'@@ -746,15 +747,20 @@ export function UsageIndicator({))}{/* One segment per enabled provider, carrying only its worst limit — a provider's fullbreakdown belongs in the popover, not in a pill that has to fit beside the canvas. */}+ {/* Cursor is the exception: all three buckets (providerPillSegments). */}{enabled.map((p, i) => {- const worst = primaryLimit(p.limits)- if (!worst) return null+ const segments = providerPillSegments(p, labelFor(p.provider))+ if (segments.length === 0) return nullreturn (<span key={providerRowKey(p)} className="usage-pill__provider">- {(limits.length > 0 || i > 0) && <span className="usage-pill__sep">·</span>}- <span className="usage-pill__num">- {percentNumber(worst.usedPercent, percentMode)}% {labelFor(p.provider)}- </span>+ {segments.map(({ limit: l, label }, j) => (+ <span key={limitKey(l)}>+ {(limits.length > 0 || i > 0 || j > 0) && <span className="usage-pill__sep">·</span>}+ <span className="usage-pill__num">+ {percentNumber(l.usedPercent, percentMode)}% {label}+ </span>+ </span>+ ))}</span>)})}diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex 918c2cf6d..bbe8027ac 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -68,7 +68,7 @@ const ROWS = {},agents: {title: 'Show in Add menus',- keywords: ['agent', 'claude', 'codex', 'gemini', 'enable', 'disable', 'show', 'hide', 'menu', 'default']+ keywords: ['agent', 'claude', 'codex', 'gemini', 'cursor', 'enable', 'disable', 'show', 'hide', 'menu', 'default']},launchCommands: {title: 'Launch commands',@@ -86,7 +86,8 @@ const ROWS = {'codex','gemini','grok',- 'opencode'+ 'opencode',+ 'cursor']},vanillaLaunch: {@@ -128,6 +129,7 @@ const ROWS = {'grok','gemini','codex',+ 'cursor','approval','shift tab']diff --git a/src/renderer/components/settings/sections/UsageSection.tsx b/src/renderer/components/settings/sections/UsageSection.tsxindex c9da30f8a..6e07f81c5 100644--- a/src/renderer/components/settings/sections/UsageSection.tsx+++ b/src/renderer/components/settings/sections/UsageSection.tsx@@ -27,6 +27,7 @@ const ROWS = {'ssh','host','codex',+ 'cursor','gemini','grok','kimi',@@ -54,6 +55,7 @@ const PROVIDER_BLURBS: Record<string, string> = {'claude-remote':"Limits for the Claude accounts on your connected SSH projects' hosts. Each read runs on the host itself over the existing connection — the credential never leaves it.",codex: 'Session and weekly limits from your ChatGPT (Codex) subscription.',+ cursor: 'Monthly included usage (total, Auto and API) from the Cursor Agent CLI sign-in.',gemini: 'Per-model hourly quota from the Gemini CLI sign-in.',grok: 'Weekly credits and monthly budget from the Grok CLI sign-in.',kimi: 'Session and weekly quota from the Kimi Code sign-in.',diff --git a/src/renderer/hud/main.ts b/src/renderer/hud/main.tsindex eb0af244c..0aefc2430 100644--- a/src/renderer/hud/main.ts+++ b/src/renderer/hud/main.ts@@ -8,6 +8,7 @@ import { CLAUDE_MASCOT, CODEX_MASCOT, DONE_BLOB } from '../lib/mascot'import { HUD_BRAND_PULSE_CLASS, brandPulseBackground, brandPulsePlan } from '../lib/brandPulse'import { createGrokMarkSvg } from '../lib/grokMark'import { createCopilotMarkSvg } from '../lib/copilotMark'+import { createCursorMarkSvg } from '../lib/cursorMark'import { buildIndicator, orderIndicatorAgents } from './indicator'import { HUD_ROW_CAP, overflowLabel, splitPanelRows } from './panel-rows'import { percentText } from '../lib/usageFormat'@@ -212,7 +213,9 @@ function workingMascot(agentId?: string): Element {return plan.kind === 'inline'? plan.mark === 'copilot'? createCopilotMarkSvg(plan.size, HUD_BRAND_PULSE_CLASS)- : createGrokMarkSvg(plan.size, HUD_BRAND_PULSE_CLASS)+ : plan.mark === 'cursor'+ ? createCursorMarkSvg(plan.size, HUD_BRAND_PULSE_CLASS)+ : createGrokMarkSvg(plan.size, HUD_BRAND_PULSE_CLASS): brandPulseMascot(plan.src, plan.size)}const dot = document.createElement('span')diff --git a/src/renderer/lib/agentIcons.tsx b/src/renderer/lib/agentIcons.tsxindex ebbfb7d06..2f99f5659 100644--- a/src/renderer/lib/agentIcons.tsx+++ b/src/renderer/lib/agentIcons.tsx@@ -3,6 +3,7 @@ import { IconTerminal } from '../components/icons'import { BRAND_PULSE_CLASS, brandLogoSrc, brandPulsePlan } from './brandPulse'import { GROK_MARK_PATH, GROK_MARK_VIEWBOX } from './grokMark'import { COPILOT_MARK_PATHS, COPILOT_MARK_VIEWBOX } from './copilotMark'+import { CURSOR_MARK_PATH, CURSOR_MARK_VIEWBOX } from './cursorMark'// The logo map itself lives in the REACT-FREE lib/brandPulse.ts, because the notch HUD needs the// same assets and must not import React. Re-exported here so React callers have one import for@@ -76,6 +77,30 @@ export function CopilotMark({)}+/** The Cursor mark, inlined like `CopilotMark`, geometry from `lib/cursorMark.ts`. */+export function CursorMark({+ size,+ className+}: {+ size: number+ className?: string+}): React.JSX.Element {+ return (+ <svg+ width={size}+ height={size}+ viewBox={CURSOR_MARK_VIEWBOX}+ fill="currentColor"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden+ className={className}+ style={{ display: 'block' }}+ >+ <path fillRule="evenodd" d={CURSOR_MARK_PATH} />+ </svg>+ )+}+export function BrandPulse({ agentId, size }: { agentId?: AgentId; size: number }): React.JSX.Element | null {const plan = brandPulsePlan(agentId, size)if (!plan) return null@@ -84,6 +109,8 @@ export function BrandPulse({ agentId, size }: { agentId?: AgentId; size: numberif (plan.kind === 'inline')return plan.mark === 'copilot' ? (<CopilotMark size={plan.size} className={BRAND_PULSE_CLASS} />+ ) : plan.mark === 'cursor' ? (+ <CursorMark size={plan.size} className={BRAND_PULSE_CLASS} />) : (<GrokMark size={plan.size} className={BRAND_PULSE_CLASS} />)@@ -101,6 +128,7 @@ export function AgentIcon({ agentId, size = 16 }: { agentId: AgentId; size?: numconst iconAgentId = capabilityAgentId(agentId)if (iconAgentId === 'grok') return <GrokMark size={size} />if (iconAgentId === 'copilot') return <CopilotMark size={size} />+ if (iconAgentId === 'cursor') return <CursorMark size={size} />// `brandLogoSrc`, not `AGENT_LOGO[iconAgentId]`: the id can be anything a hand-edited// project.json says, and a prototype key ('constructor') would hand back a Function as the image// source.diff --git a/src/renderer/lib/brandPulse.test.tsx b/src/renderer/lib/brandPulse.test.tsxindex 2df7ddfea..7d8da9a6f 100644--- a/src/renderer/lib/brandPulse.test.tsx+++ b/src/renderer/lib/brandPulse.test.tsx@@ -42,6 +42,7 @@ describe('brandPulsePlan', () => {// The generalized inline plan carries WHICH mark so each surface draws the right geometry.expect(brandPulsePlan('grok', 16)).toEqual({ kind: 'inline', mark: 'grok', size: 16 })expect(brandPulsePlan('copilot', 16)).toEqual({ kind: 'inline', mark: 'copilot', size: 16 })+ expect(brandPulsePlan('cursor', 16)).toEqual({ kind: 'inline', mark: 'cursor', size: 16 })})it('answers nothing for an agent with no mark, so the caller falls back to the dot', () => {diff --git a/src/renderer/lib/brandPulse.ts b/src/renderer/lib/brandPulse.tsindex 56a56a1d2..e98bc53e5 100644--- a/src/renderer/lib/brandPulse.ts+++ b/src/renderer/lib/brandPulse.ts@@ -44,7 +44,7 @@ export const brandLogoSrc = (agentId: AgentId): string | undefined =>/** Does this agent have a brand mark to draw? grok is inlined rather than an asset, so it is not in* AGENT_LOGO — ask through here rather than testing that map directly. */-export const INLINE_MARK_AGENTS = ['grok', 'copilot'] as const+export const INLINE_MARK_AGENTS = ['grok', 'copilot', 'cursor'] as constexport type InlineMark = (typeof INLINE_MARK_AGENTS)[number]export const inlineMarkFor = (agentId: AgentId): InlineMark | null =>(INLINE_MARK_AGENTS as readonly string[]).includes(agentId) ? (agentId as InlineMark) : nulldiff --git a/src/renderer/lib/chatSendGate.test.ts b/src/renderer/lib/chatSendGate.test.tsindex 039c1fd0f..ac0d982f3 100644--- a/src/renderer/lib/chatSendGate.test.ts+++ b/src/renderer/lib/chatSendGate.test.ts@@ -31,6 +31,11 @@ describe('chatSendRefusal / canSendFromChat', () => {expect(chatSendRefusal('claude', { state: 'blocked' })).toBe('dialog')})+ it('refuses a cursor node blocked on its approval dialog (core/agents/cursor-approval.ts)', () => {+ // Enter would pick "Run (once) (y)", the highlighted option.+ expect(chatSendRefusal('cursor', { state: 'blocked' })).toBe('dialog')+ })+it('refuses a hibernated node even though its state still reads done: a SHELL owns the pane', () => {expect(chatSendRefusal('claude', { state: 'done', hibernated: true })).toBe('asleep')expect(canSendFromChat('claude', { state: 'done', hibernated: true })).toBe(false)diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.tsindex 8e0196136..ca2745b45 100644--- a/src/renderer/lib/controlRouting.test.ts+++ b/src/renderer/lib/controlRouting.test.ts@@ -239,13 +239,13 @@ describe('sourceIsControlCapable', () => {})it('accepts every canvas-control-capable agent', () => {- for (const id of ['claude', 'codex', 'gemini', 'opencode', 'grok']) {+ for (const id of ['claude', 'codex', 'gemini', 'opencode', 'grok', 'cursor']) {expect(sourceIsControlCapable(id)).toBe(true)}})it('rejects an agent that never gets NODETERM_CANVAS_CONTROL', () => {- expect(sourceIsControlCapable('cursor')).toBe(false)+ expect(sourceIsControlCapable('antigravity')).toBe(false)})})@@ -322,7 +322,7 @@ describe('answerBrowserResolve — the renderer answers ONLY what it alone knows})it('a non-control-capable source is reported as such (main turns it into the refusal)', () => {- const p = proj({ nodes: [{ id: 'x-1', agentId: 'cursor' }], agentBrowserControl: true, capabilityAck: { agentBrowserControl: 'kept' } })+ const p = proj({ nodes: [{ id: 'x-1', agentId: 'antigravity' }], agentBrowserControl: true, capabilityAck: { agentBrowserControl: 'kept' } })expect(answerBrowserResolve(p, 'x-1')).toMatchObject({ ok: true, sourceControlCapable: false })})})diff --git a/src/renderer/lib/cursorMark.ts b/src/renderer/lib/cursorMark.tsnew file mode 100644index 000000000..bf728570b--- /dev/null+++ b/src/renderer/lib/cursorMark.ts@@ -0,0 +1,30 @@+// The Cursor mark, as raw geometry so BOTH renderers can draw it: the React `AgentIcon` /+// `BrandPulse` in the canvas, and the plain-DOM notch HUD, which builds its nodes imperatively and+// cannot use JSX.+//+// Geometry from `@lobehub/icons-static-svg` 1.95.1 `icons/cursor.svg` (MIT). MONOCHROME like grok's+// and copilot's, so it is inlined with `fill="currentColor"` and follows the theme.++/** The mark's own aspect box (24×24). */+export const CURSOR_MARK_VIEWBOX = '0 0 24 24'++/** One evenodd path: the hexagonal cube with its cut-out face. */+export const CURSOR_MARK_PATH =+ 'M22.106 5.68L12.5.135a.998.998 0 00-.998 0L1.893 5.68a.84.84 0 00-.419.726v11.186c0 .3.16.577.42.727l9.607 5.547a.999.999 0 00.998 0l9.608-5.547a.84.84 0 00.42-.727V6.407a.84.84 0 00-.42-.726zm-.603 1.176L12.228 22.92c-.063.108-.228.064-.228-.061V12.34a.59.59 0 00-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264 0 .428.286.296.514z'++/** Build the mark as a real SVG element, for the imperative renderer (the notch HUD). */+export function createCursorMarkSvg(size: number, className: string): SVGSVGElement {+ const NS = 'http://www.w3.org/2000/svg'+ const svg = document.createElementNS(NS, 'svg')+ svg.setAttribute('width', String(size))+ svg.setAttribute('height', String(size))+ svg.setAttribute('viewBox', CURSOR_MARK_VIEWBOX)+ svg.setAttribute('fill', 'currentColor')+ svg.setAttribute('aria-hidden', 'true')+ svg.setAttribute('class', className)+ const path = document.createElementNS(NS, 'path')+ path.setAttribute('fill-rule', 'evenodd')+ path.setAttribute('d', CURSOR_MARK_PATH)+ svg.appendChild(path)+ return svg+}diff --git a/src/renderer/lib/kanbanStatusChips.test.ts b/src/renderer/lib/kanbanStatusChips.test.tsindex ff6112585..30a4501a1 100644--- a/src/renderer/lib/kanbanStatusChips.test.ts+++ b/src/renderer/lib/kanbanStatusChips.test.ts@@ -18,6 +18,9 @@ describe('cardBadge — the ONE badge rule the card and the chips share', () =>expect(cardBadge('terminal', st({ state: 'working' }))).toBe('running')expect(cardBadge('terminal', st({ state: 'waiting' }))).toBe('needs')expect(cardBadge('terminal', st({ state: 'blocked' }))).toBe('needs')+ // A cursor node's pane-read `blocked` (core/agents/cursor-approval.ts) reads the same rule:+ // the card, the chips and the card modal share it.+ expect(cardBadge('cursor', st({ state: 'blocked' }))).toBe('needs')expect(cardBadge('terminal', st({ paused: true }))).toBe('paused')expect(cardBadge('terminal', st({ hibernated: true }))).toBe('sleeping')expect(cardBadge('terminal', st({ state: 'done' }))).toBeNull()diff --git a/src/renderer/lib/nodeActionItems.offCanvas.test.tsx b/src/renderer/lib/nodeActionItems.offCanvas.test.tsxindex c584aec7e..d80fa3e90 100644--- a/src/renderer/lib/nodeActionItems.offCanvas.test.tsx+++ b/src/renderer/lib/nodeActionItems.offCanvas.test.tsx@@ -36,6 +36,7 @@ function input(nodes: CanvasNodeState[], over: Partial<OffCanvasCtxInput> = {}):gatewayStatus: 'idle',gatewayError: '',grokModels: () => [],+ cursorModels: () => [],writes: { setColor: vi.fn(), pickIcon: vi.fn() },liveLinkMenuItems: () => [],connectedProjectIdForHost: () => undefined,diff --git a/src/renderer/lib/nodeActionItems.test.tsx b/src/renderer/lib/nodeActionItems.test.tsxindex 77f259ddf..e8e5d0eb7 100644--- a/src/renderer/lib/nodeActionItems.test.tsx+++ b/src/renderer/lib/nodeActionItems.test.tsx@@ -30,6 +30,7 @@ function fakeCtx(nodes: CanvasNode[], over: Partial<NodeActionCtx> = {}): NodeAcgatewayStatus: 'idle',gatewayError: '',grokModels: () => [],+ cursorModels: () => [],addToExistingGroup: noop,groupSelection: noop,removeFromGroup: noop,diff --git a/src/renderer/lib/nodeActionItems.tsx b/src/renderer/lib/nodeActionItems.tsxindex 4788fb394..35b726d3e 100644--- a/src/renderer/lib/nodeActionItems.tsx+++ b/src/renderer/lib/nodeActionItems.tsx@@ -196,6 +196,8 @@ export interface NodeActionCtx {gatewayStatus: ModelDiscoveryStatusgatewayError: stringgrokModels: () => GatewayModel[]+ /** Only called for a cursor node: an empty memo spawns `cursor-agent models`. */+ cursorModels: () => GatewayModel[]addToExistingGroup: (ids: string[], groupId: string) => voidgroupSelection: (ids: string[]) => voidremoveFromGroup: (ids: string[]) => void@@ -568,7 +570,12 @@ function sessionRows(nodeId: string, ctx: NodeActionCtx, hidden: readonly stringconst switchCapable = !!sourceAgentId && canSwitchModel(sourceAgentId)const compatibleModels =sourceAgentId && ctx.sessionSource !== 'relay'- ? modelsForAgent(ctx.gatewayModels, sourceAgentId, ctx.grokModels())+ ? modelsForAgent(+ ctx.gatewayModels,+ sourceAgentId,+ ctx.grokModels(),+ capabilityAgentId(sourceAgentId) === 'cursor' ? ctx.cursorModels() : []+ ): []const currentModel = typeof n?.data.agentModel === 'string' ? n.data.agentModel : undefined// 'not-resumable' is permanent (a plain shell, opencode, a custom CLI with no exit@@ -921,6 +928,8 @@ export interface OffCanvasCtxInput {gatewayStatus: ModelDiscoveryStatusgatewayError: stringgrokModels: () => GatewayModel[]+ /** Only called for a cursor node: an empty memo spawns `cursor-agent models`. */+ cursorModels: () => GatewayModel[]/** The project's write router (Canvas `nodeWritesFor(projectId)`). */writes: Pick<NodeWrites, 'setColor' | 'pickIcon'>liveLinkMenuItems: (nodeId: string) => MenuItem[]@@ -958,6 +967,7 @@ export function offCanvasNodeActionCtx(o: OffCanvasCtxInput): NodeActionCtx {gatewayStatus: o.gatewayStatus,gatewayError: o.gatewayError,grokModels: o.grokModels,+ cursorModels: o.cursorModels,addToExistingGroup: refuse,groupSelection: refuse,removeFromGroup: refuse,diff --git a/src/renderer/lib/noteLink.test.ts b/src/renderer/lib/noteLink.test.tsindex 034bab609..6e11d2c3c 100644--- a/src/renderer/lib/noteLink.test.ts+++ b/src/renderer/lib/noteLink.test.ts@@ -14,8 +14,10 @@ import {contextLinkForEdge,edgeToBridge,linkReadPairs,- isCurrentLinkDirection+ isCurrentLinkDirection,+ usesLinkedContextSkill} from './noteLink'+import { setCustomAgentBaseResolver } from '@shared/agents/config'import type { CanvasNodeState } from '@shared/types'const term = (contextCapable = false) => ({ kind: 'terminal', contextCapable })@@ -225,6 +227,23 @@ describe('buildContextLinkNote', () => {expect(msg).toContain('[nodeterm] You are now linked to "Builder"')expect(msg).toContain('get-linked-context skill')})+ it('cursor (reads ~/.claude/skills) gets the skill wording; grok, unverified, keeps the CLI', () => {+ expect(buildContextLinkNote('cursor', 'Builder', '/x/context.sh')).toContain('get-linked-context skill')+ expect(buildNotePushMessage('N', 'x'.repeat(3000), 'cursor')).toContain('get-linked-context skill')+ expect(buildContextLinkNote('grok', 'Builder', '/x/context.sh')).toContain('sh "/x/context.sh"')+ })+ it('a custom agent words it as its base does: claude-base and cursor-base alike (LINKED_CONTEXT_SKILL_AGENTS)', () => {+ setCustomAgentBaseResolver((id) => (id === 'my-claude' ? 'claude' : id === 'my-cursor' ? 'cursor' : id === 'my-grok' ? 'grok' : undefined))+ try {+ for (const id of ['my-claude', 'my-cursor']) {+ expect(usesLinkedContextSkill(id), id).toBe(true)+ expect(buildContextLinkNote(id, 'Builder', '/x/context.sh'), id).toContain('get-linked-context skill')+ }+ expect(usesLinkedContextSkill('my-grok')).toBe(false)+ } finally {+ setCustomAgentBaseResolver(null)+ }+ })it('codex/gemini get the inline CLI command, single line', () => {const msg = buildContextLinkNote('codex', 'Builder', '/x/context.sh')expect(msg).toContain('sh "/x/context.sh"')diff --git a/src/renderer/lib/noteLink.ts b/src/renderer/lib/noteLink.tsindex 29174cb17..c52210e18 100644--- a/src/renderer/lib/noteLink.ts+++ b/src/renderer/lib/noteLink.ts@@ -4,6 +4,7 @@// Kept free of React/store imports so the connection matrix is unit-testable.import type { Edge } from '@xyflow/react'import { oneLine } from '@shared/one-line'+import { readsLinkedContextSkill } from '@shared/agents/config'import type { BridgeLink } from '@shared/types'import { shimCommand, shimDialectFor } from '@shared/agents/shim-invocation'import { capabilityAgentId, readsScreenDialogs } from '@shared/agents/config'@@ -130,6 +131,12 @@ export function linkIdsCoveredByRopes(return links.filter((l) => pairs.has(pairKey(l.source, l.target))).map((l) => l.id)}+/** Does this agent load nodeterm's `get-linked-context` skill? See LINKED_CONTEXT_SKILL_AGENTS; an+ * unknown agent gets the skill wording, as it always did. */+export function usesLinkedContextSkill(agentId: string | undefined): boolean {+ return !agentId || readsLinkedContextSkill(agentId)+}+/** Longest note text pushed inline; longer notes are truncated with a pointer to the skill. */const NOTE_PUSH_MAX = 2000@@ -147,7 +154,7 @@ export function buildNotePushMessage(title: string, text: string, agentId?: striif (!text.trim()) return nullconst flat = oneLine(text.replace(/\s*\r?\n\s*/g, ' ⏎ '))const pointer =- !agentId || agentId === 'claude'+ usesLinkedContextSkill(agentId)? 'read the full note with the get-linked-context skill': 'read the full note with the nodeterm linked-context CLI — see the get-linked-context section in your global agent instructions'const body =@@ -178,7 +185,7 @@ export function buildContextLinkNote(// Both variants must self-defuse: the note is injected + submitted as a prompt, and an// agent that reads it as a task launches an unsolicited investigation of the linked node// (observed with gemini). "No action needed" keeps it a notification.- if (!agentId || agentId === 'claude') {+ if (usesLinkedContextSkill(agentId)) {return `[nodeterm] You are now linked to "${other}". Use the get-linked-context skill to read its context when you need it. No action needed now — just acknowledge briefly.`}return `[nodeterm] You are now linked to "${other}". When you need its context (and only then) run: ${shimCommand(shimPath, shimDialectFor(agentId, hostPlatform))} list — then summary | transcript | terminal --node <id>. Details are in the get-linked-context section of your global agent instructions. No action needed now — acknowledge briefly and do not run these commands yet.`diff --git a/src/renderer/lib/sessionRename.test.ts b/src/renderer/lib/sessionRename.test.tsindex fb44d6f22..80d971c6b 100644--- a/src/renderer/lib/sessionRename.test.ts+++ b/src/renderer/lib/sessionRename.test.ts@@ -225,3 +225,19 @@ describe('renameCommand: a title cannot splice a second command', () => {})})})++describe('pushSessionRename: a separate-submit agent (cursor)', () => {+ it('sends ONE line with the default Enter; PtyManager.sendText splits it, nothing here does', async () => {+ const calls: unknown[][] = []+ const x = {+ paneCommand: async () => 'cursor-agent',+ sendText: async (...args: unknown[]) => {+ calls.push(args.slice(1))+ return true as const+ },+ sleep: async () => {}+ }+ await expect(pushSessionRename(x, 'n1', 'Probe', 'Old')).resolves.toBe(true)+ expect(calls).toEqual([['/rename Probe']])+ })+})diff --git a/src/renderer/lib/transferItems.tsx b/src/renderer/lib/transferItems.tsxindex 973f49eca..e931543ac 100644--- a/src/renderer/lib/transferItems.tsx+++ b/src/renderer/lib/transferItems.tsx@@ -17,7 +17,8 @@ import {AGENT_CONFIG,BUILTIN_AGENT_IDS,canTransferFrom,- MODEL_SWITCH_CAPABLE+ MODEL_SWITCH_CAPABLE,+ OWN_MODEL_CATALOGUE} from '@shared/agents/config'import type { GatewayModel } from '@shared/agents/model-gateway'import type { CustomAgent } from '@shared/types'@@ -120,11 +121,15 @@ export function transferConversationItems(// A model submenu only for a switch-capable target with discovered models, and never for a// relay source (its gateway is on another machine). Capability is resolved from the passed-in// `customAgents` (base-resolved, so a claude-base custom agent qualifies) rather than the- // runtime's injected resolver, so this stays pure and testable. gemini/grok and baseless- // customs stay flat — no model grammar. The gateway is shared across harnesses, so the full- // model list applies to any capable target.+ // runtime's injected resolver, so this stays pure and testable. gemini and baseless customs+ // stay flat (no model grammar). The gateway is shared across harnesses, so the full model list+ // applies to any capable target, except one with its own catalogue (grok, cursor), which+ // stays flat: a gateway id is not one of its models.const base = baseOf(tg.id, customAgents)- const capable = !!base && (MODEL_SWITCH_CAPABLE as readonly string[]).includes(base)+ const capable =+ !!base &&+ (MODEL_SWITCH_CAPABLE as readonly string[]).includes(base) &&+ !(OWN_MODEL_CATALOGUE as readonly string[]).includes(base)const models = capable && !relaySession ? (gatewayModels as GatewayModel[]) : []if (models.length === 0) {return {diff --git a/src/renderer/lib/verifyPanel.test.ts b/src/renderer/lib/verifyPanel.test.tsindex 6d21ed152..949d9b815 100644--- a/src/renderer/lib/verifyPanel.test.ts+++ b/src/renderer/lib/verifyPanel.test.ts@@ -45,6 +45,7 @@ describe('verifyLensPrompt', () => {const codex = verifyLensPrompt({ ...base, lens: 'tests', agentId: 'codex' })expect(codex).toContain('/x/nodeterm.sh')expect(codex).not.toContain('get-linked-context skill')+ expect(verifyLensPrompt({ ...base, lens: 'tests', agentId: 'cursor' })).toContain('get-linked-context skill')})it('on a Windows core, a non-claude reviewer is told to run the .cmd launcher', () => {diff --git a/src/renderer/lib/verifyPanel.ts b/src/renderer/lib/verifyPanel.tsindex 4db73069a..db7d83c52 100644--- a/src/renderer/lib/verifyPanel.ts+++ b/src/renderer/lib/verifyPanel.ts@@ -4,6 +4,7 @@// agree with each other, which reads as confirmation while adding no evidence.//// Kept free of React/store imports so the lens table and the prompt wording are unit-testable.+import { usesLinkedContextSkill } from './noteLink'import { shimCommand, shimDialectFor } from '@shared/agents/shim-invocation'/** Lens id → what that reviewer is told to hunt for. */@@ -52,7 +53,7 @@ export function parseLenses(raw: string | undefined): string[] {/** How a given agent is told to read a linked node's work. */function readInstruction(agentId: string | undefined, shimPath: string, hostPlatform?: string): string {- return !agentId || agentId === 'claude'+ return usesLinkedContextSkill(agentId)? 'read its work with the get-linked-context skill (summary first, then transcript if you need detail)': `read its work by running: ${shimCommand(shimPath, shimDialectFor(agentId, hostPlatform))} summary --node <id> (then transcript --node <id> for detail) — see the get-linked-context section of your global agent instructions`}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex b263797be..302a2dbc8 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -3489,6 +3489,13 @@ export function TerminalNode({// to the still-live session on first mount); everything below that pushes here is gated on// `!parked` so nothing is wired twice.const cleanups: Array<() => void> = parked ? parked.cleanups : []+ // nodeterm itself just delivered this node's resume/relaunch line (in-place restart, wake from+ // Pause/Eco, and the cold-restore relaunch a model switch or "restart agent and shell" recycles+ // into). The exit our own quit recorded (`sessionEnded`) no longer describes the pane. Claude+ // would clear it on its SessionStart anyway; cursor fires none on `--resume`, so without this the+ // chat composer and the phone keep refusing a running CLI as "exited" until its next turn.+ // note: a sessionEnd POST that lands after the relaunch re-sets it; none has been observed.+ const markRelaunched = (): void => useAgentStatus.getState().setSessionEnded(id, false)// Copy-on-select (issue #759). REGISTERED ONCE, at construction, and disposed WITH THE TERMINAL// — the OSC 52 handler's lifecycle, not a per-mount one: its only persistent listener lives on@@ -4053,6 +4060,7 @@ export function TerminalNode({if (outcome === 'line-too-long') {setCo(termKey, { launchTooLongBytes: lineBytes(cmd) })}+ if (outcome === 'submitted') markRelaunched()},{ killLine: getTerminalKillLine() })@@ -4617,7 +4625,8 @@ export function TerminalNode({onDelivery: (cancel) => {if (life.dead) cancel()else cleanups.push(cancel)- }+ },+ onResumed: markRelaunched})}))@@ -4803,7 +4812,8 @@ export function TerminalNode({onDelivery: (cancel) => {if (life.dead) cancel()else cleanups.push(cancel)- }+ },+ onResumed: markRelaunched})})})diff --git a/src/renderer/state/permissionMode.cursor-caps.test.ts b/src/renderer/state/permissionMode.cursor-caps.test.tsnew file mode 100644index 000000000..5e49f4857--- /dev/null+++ b/src/renderer/state/permissionMode.cursor-caps.test.ts@@ -0,0 +1,32 @@+import { afterEach, describe, expect, it } from 'vitest'+import { cursorCliCapsNow, ensureCursorCliCaps, resetCursorCliCapsForTests } from './permissionMode'++// Review 2026-10-02: a failed or empty first probe (offline, signed out) was memoized forever, so+// the model menu stayed empty until an app reload even though core retries.+function stub(answers: { models: { id: string }[] }[]): { calls: number } {+ const seen = { calls: 0 }+ ;(globalThis as { window?: unknown }).window = {+ nodeTerminal: { cursor: { cliCaps: async () => answers[Math.min(seen.calls++, answers.length - 1)] } }+ }+ return seen+}++afterEach(() => resetCursorCliCapsForTests())++describe('cursor model catalogue memo', () => {+ it('retries after an empty answer and keeps the first real catalogue', async () => {+ const seen = stub([{ models: [] }, { models: [{ id: 'composer-2.5' }] }])+ expect((await ensureCursorCliCaps()).models).toEqual([])+ expect((await ensureCursorCliCaps()).models).toEqual([{ id: 'composer-2.5' }])+ await ensureCursorCliCaps()+ expect(seen.calls).toBe(2) // memoized once real+ })++ it('a synchronous read with nothing known starts the retry for the next menu open', async () => {+ const seen = stub([{ models: [{ id: 'composer-2.5' }] }])+ expect(cursorCliCapsNow().models).toEqual([])+ await new Promise((r) => setTimeout(r, 0))+ expect(seen.calls).toBe(1)+ expect(cursorCliCapsNow().models).toEqual([{ id: 'composer-2.5' }])+ })+})diff --git a/src/renderer/state/permissionMode.ts b/src/renderer/state/permissionMode.tsindex 86ac791df..2faec3b3f 100644--- a/src/renderer/state/permissionMode.ts+++ b/src/renderer/state/permissionMode.ts@@ -8,6 +8,8 @@ import {import {UNKNOWN_CLAUDE_CLI_CAPS,UNKNOWN_GROK_CLI_CAPS,+ UNKNOWN_CURSOR_CLI_CAPS,+ type CursorCliCaps,type ClaudeCliCaps,type GrokCliCaps,type Project@@ -99,6 +101,44 @@ export function grokCliCapsNow(): GrokCliCaps {return grokCaps}+/** cursor's catalogue, same shape: fail-open [] until `cursor.cliCaps()` answers. Own memo (rule 9). */+let cursorCaps: CursorCliCaps = UNKNOWN_CURSOR_CLI_CAPS+let cursorCapsPromise: Promise<CursorCliCaps> | null = null++export function ensureCursorCliCaps(): Promise<CursorCliCaps> {+ if (!cursorCapsPromise) {+ const probe = Promise.resolve()+ .then(() => window.nodeTerminal.cursor.cliCaps())+ .then((c) => (cursorCaps = c ?? UNKNOWN_CURSOR_CLI_CAPS))+ .catch(() => UNKNOWN_CURSOR_CLI_CAPS)+ .then((c) => {+ // An empty catalogue (offline, signed out, CLI missing) is not remembered: core does not+ // cache it either (core/cursor-cli.ts), so the next ask retries instead of hiding the model+ // menu until an app reload (review 2026-10-02). A real catalogue stays memoized.+ if (c.models.length === 0) cursorCapsPromise = null+ return c+ })+ const timeout = new Promise<CursorCliCaps>((resolve) =>+ setTimeout(() => resolve(cursorCaps), CAPS_WAIT_MS)+ )+ cursorCapsPromise = Promise.race([probe, timeout])+ }+ return cursorCapsPromise+}++/** Last-known cursor caps, synchronously. With nothing known yet it starts a retry in the+ * background, so the menu that asked finds the catalogue the next time it opens. */+export function cursorCliCapsNow(): CursorCliCaps {+ if (cursorCaps.models.length === 0) void ensureCursorCliCaps()+ return cursorCaps+}++/** Test seam for the cursor memo. */+export function resetCursorCliCapsForTests(): void {+ cursorCaps = UNKNOWN_CURSOR_CLI_CAPS+ cursorCapsPromise = null+}+/** Test seam for the grok memo. */export function resetGrokCliCapsForTests(next?: GrokCliCaps): void {grokCaps = next ?? UNKNOWN_GROK_CLI_CAPSdiff --git a/src/renderer/terminal/agent-liveness.test.ts b/src/renderer/terminal/agent-liveness.test.tsindex e2e39dd6d..80a960ce5 100644--- a/src/renderer/terminal/agent-liveness.test.ts+++ b/src/renderer/terminal/agent-liveness.test.ts@@ -47,6 +47,8 @@ describe('looksDropped', () => {expect(looksDropped({ ...base, agentId: 'opencode' })).toBe(false)expect(looksDropped({ ...base, agentId: 'gemini' })).toBe(true)expect(looksDropped({ ...base, agentId: 'grok' })).toBe(true)+ // cursor: normalizeCursor maps `sessionEnd` (subscribed in CURSOR_HOOK_EVENTS), so it is judged.+ expect(looksDropped({ ...base, agentId: 'cursor' })).toBe(true)})// A plain terminal is a shell in a pane by definition — the whole canvas would light up.diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 3411504c2..b72e50ca3 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { readFileSync } from 'node:fs'import { resumeCommand, setCustomAgentBaseResolver } from '../../shared/agents/config'import { withPermissionMode } from '../../shared/agents/approval-mode'+import { createAgentStatusSession } from '../state/agentStatus'+import { chatSendRefusal } from '../lib/chatSendGate'import {__resetAgentRestartForTests,agentHibernateFns,@@ -15,6 +17,7 @@ import {performRestartResume,performResumePhase,planBulkRestart,+ EXIT_KEY_GAP_MS,RESTART_EXIT_TIMEOUT_MS,RESTART_LATE_EXIT_MS,RESTART_MIN_EXIT_SAMPLES,@@ -47,6 +50,8 @@ describe('exitSequence', () => {expect(exitSequence('gemini')).not.toContain('--delete')expect(exitSequence('copilot')).toBe('/exit')expect(exitSequence('opencode')).toBe('/exit')+ // cursor: bare `/quit`, measured in its TUI (exits clean, fires sessionEnd).+ expect(exitSequence('cursor')).toBe('/quit')expect(exitSequence('my-custom')).toBeNull()})})@@ -773,6 +778,31 @@ describe('performExitPhase', () => {}})+ it('cursor (separate submit) gets Ctrl-U, a gap, `/quit`, a gap, then Enter', async () => {+ // Measured 2026.10.01 in tmux: Ctrl-U and `/quit` in one burst, Enter 150 ms later, left the+ // CLI running 10 of 10 (`/quit` dropped); with a gap after the Ctrl-U too it exited 10 of 10.+ // A custom agent based on cursor gets the same sequence.+ setCustomAgentBaseResolver((id) => (id === 'my-cursor' ? 'cursor' : undefined))+ try {+ for (const agentId of ['cursor', 'my-cursor']) {+ const { written, io } = fakeIo()+ let pane = 'cursor-agent'+ const p = performExitPhase({ agentId, sessionId: 'sid-1', io, paneCommand: async () => pane, timeoutMs: 6000, pollMs: 100 })+ await vi.advanceTimersByTimeAsync(0)+ expect(written).toEqual(['\x15'])+ await vi.advanceTimersByTimeAsync(EXIT_KEY_GAP_MS)+ expect(written).toEqual(['\x15', '/quit'])+ await vi.advanceTimersByTimeAsync(EXIT_KEY_GAP_MS)+ expect(written).toEqual(['\x15', '/quit', '\r'])+ pane = 'zsh'+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('exited')+ }+ } finally {+ setCustomAgentBaseResolver(null)+ }+ })+it('keeps gemini on its typed exit: line-clear, then a bare `/quit` in one burst', async () => {// gemini is the one agent not measured (its composer is only reachable after a login), so it// keeps the historical path byte-identical.@@ -916,6 +946,26 @@ describe('performExitPhase', () => {expect(await p).toBe('not-eligible')expect(written).toEqual(['\x03'])})++ it('abandons the split CR when the pane dies mid-delay (cursor)', async () => {+ const { written, io } = fakeIo()+ let live = true+ const p = performExitPhase({+ agentId: 'cursor',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'cursor-agent',+ timeoutMs: 6000,+ pollMs: 100,+ isLive: () => live+ })+ await vi.advanceTimersByTimeAsync(EXIT_KEY_GAP_MS)+ expect(written).toEqual(['\x15', '/quit'])+ live = false+ await vi.advanceTimersByTimeAsync(200)+ expect(await p).toBe('not-eligible')+ expect(written).toEqual(['\x15', '/quit']) // CR never sent into a dead pane+ })})describe('performResumePhase', () => {@@ -1092,6 +1142,68 @@ describe('performRestartResume — grok', () => {})})+/**+ * Review 2026-10-03 (F1): our own `/quit` fires cursor's `sessionEnd` (Canvas records+ * `sessionEnded`), and cursor fires no `sessionStart` on `--resume`. So after nodeterm relaunched+ * the CLI itself, the chat composer and the phone refused a running node as "exited". The resume+ * phase now reports its delivery through `onResumed`, which the node wires to clear the flag.+ */+describe('a delivered relaunch withdraws the recorded exit (cursor)', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())+ const SID = '11111111-1111-4111-8111-111111111111'+ const exitedNode = () => {+ const store = createAgentStatusSession().store+ // Canvas's sessionPhase 'end' branch: clear the state, then record the exit.+ store.getState().setState('n1', undefined, 'cursor')+ store.getState().setSessionEnded('n1', true)+ expect(chatSendRefusal('cursor', store.getState().byId.n1)).toBe('exited')+ return { store, onResumed: () => store.getState().setSessionEnded('n1', false) }+ }++ it('in-place restart (and a model switch on a builtin, which shares it)', async () => {+ const { store, onResumed } = exitedNode()+ const { written, io } = fakeIo()+ let pane = 'cursor-agent'+ const p = performRestartResume({ agentId: 'cursor', sessionId: SID, io, paneCommand: async () => pane, timeoutMs: 6000, pollMs: 100, onResumed })+ await vi.advanceTimersByTimeAsync(400)+ pane = 'zsh'+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('restarted')+ expect(written.join('')).toContain(`cursor-agent --resume ${SID}`)+ expect(chatSendRefusal('cursor', store.getState().byId.n1)).toBeNull()+ })++ it('wake from Pause / Eco (the resume half alone)', async () => {+ const { store, onResumed } = exitedNode()+ const { io } = fakeIo()+ const p = performResumePhase({ agentId: 'cursor', sessionId: SID, io, onResumed })+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('resumed')+ expect(chatSendRefusal('cursor', store.getState().byId.n1)).toBeNull()+ })++ it('keeps the exit when nothing was relaunched', async () => {+ const onResumed = vi.fn()+ const timedOut = performRestartResume({ agentId: 'cursor', sessionId: SID, io: fakeIo().io, paneCommand: async () => 'cursor-agent', timeoutMs: 1000, pollMs: 100, onResumed })+ await vi.advanceTimersByTimeAsync(62_000)+ expect(await timedOut).toBe('exit-timeout')+ const died = performResumePhase({ agentId: 'cursor', sessionId: SID, io: fakeIo().io, isLive: () => false, onResumed })+ await vi.advanceTimersByTimeAsync(5000)+ expect(await died).toBe('not-eligible')+ expect(onResumed).not.toHaveBeenCalled()+ })++ it('TerminalNode wires restart, wake and the cold-restore relaunch (model switch) to it', () => {+ const src = readFileSync(new URL('../nodes/TerminalNode.tsx', import.meta.url), 'utf8')+ expect(src).toContain('const markRelaunched = (): void => useAgentStatus.getState().setSessionEnded(id, false)')+ // restart + wake: both resume calls hand it over.+ expect(src.match(/onResumed: markRelaunched/g)?.length).toBe(2)+ // cold restore (also what a model switch and "restart agent and shell" recycle into).+ expect(src).toContain("if (outcome === 'submitted') markRelaunched()")+ })+})+describe('restartEligibility — grok', () => {it('is a target once it has a session id and is not busy', () => {expect(restartEligibility('grok', 'done', 'abc-1')).toEqual({ ok: true })diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex e7a1f093f..f393013a6 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -9,6 +9,7 @@ import {canResumeWith,capabilityAgentId,resumeCommand,+ submitsSeparately,type AgentId} from '../../shared/agents/config'import { isShellCommand } from '@shared/agents/pane'@@ -30,6 +31,7 @@ import {* Each value is the CLI's own DOCUMENTED PRIMARY, and is sent BARE:* - grok: `/quit` (its `/exit` is an alias).* - gemini: `/quit` (alias `/exit`), measured in its bundled `docs/reference/commands.md:325`.+ * - cursor: `/quit`, measured in its TUI.** Bare is a safety rule, not a style: gemini's `/quit` also takes a `--delete` flag that exits AND* *permanently deletes* the session's history and temporary files — the very conversation the@@ -39,6 +41,9 @@ const EXIT_SEQUENCES: Record<string, string> = {codex: '/quit',grok: '/quit',gemini: '/quit',+ // cursor: `/quit` (measured 2026.09.28: exits clean, fires sessionEnd). Its TUI, like opencode's,+ // leaves text+Enter from ONE write unsubmitted, so the Enter is a separate write below.+ cursor: '/quit',copilot: '/exit',opencode: '/exit'}@@ -149,6 +154,8 @@ export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible' | 'hoexport const RESTART_EXIT_TIMEOUT_MS = 6000export const RESTART_POLL_MS = 250+/** Gap between the split exit writes (Ctrl-U, exit text, Enter) for a TUI that batches input. */+export const EXIT_KEY_GAP_MS = 150/*** The fewest READABLE post-exit samples the exit phase takes before it may report `'exit-timeout'`.@@ -300,7 +307,7 @@ export async function performExitPhase(d: {// would then be reported as an exit timeout.//// ASSUMPTION, unverified on a real build: Ctrl-U is "clear line" inside every TUI that still- // gets a typed exit (today only gemini) — it is in every readline/ZLE prompt, and it is+ // gets a typed exit (today gemini and cursor) — it is in every readline/ZLE prompt, and it is// what command-delivery.ts already relies on for its rewrites. Each agent added to that table// inherits this assumption; only a device check retires it, per agent. If a TUI binds Ctrl-U to// something else this becomes one stray keystroke before the exit command — no worse than@@ -322,6 +329,11 @@ export async function performExitPhase(d: {// does nothing.const ctrlCs = CTRL_C_QUITS[capabilityAgentId(d.agentId)] ?? 0if (!ctrlCs) d.io.write(KILL_LINE)+ // A separate-submit TUI (cursor) still gets a typed exit, and DROPS the exit line when it lands in+ // the same input burst as the Ctrl-U: measured on 2026.10.01 in tmux, Ctrl-U+`/quit` then Enter+ // 150 ms later left an empty composer and a running CLI, 10 of 10; a gap after the Ctrl-U too+ // exited 10 of 10. Its TUI also leaves text+CR from one burst unsubmitted, so the CR is split off.+ const separate = !ctrlCs && submitsSeparately(d.agentId)if (ctrlCs) {for (let i = 0; i < ctrlCs; i++) {if (i > 0) {@@ -330,6 +342,13 @@ export async function performExitPhase(d: {}d.io.write(CTRL_C)}+ } else if (separate) {+ await new Promise((r) => setTimeout(r, EXIT_KEY_GAP_MS))+ if (gone()) return 'not-eligible'+ d.io.write(exit)+ await new Promise((r) => setTimeout(r, EXIT_KEY_GAP_MS))+ if (gone()) return 'not-eligible'+ d.io.write('\r')} else {d.io.write(exit + '\r')}@@ -422,6 +441,13 @@ export async function performResumePhase(d: {* would put a phantom in the bulk summary.*/isLive?: () => boolean+ /**+ * Called once the resume line has been delivered, right before `'resumed'` is reported. The node+ * uses it to withdraw its recorded exit (`sessionEnded`): our own exit fired that `sessionEnd`,+ * and cursor fires no `sessionStart` on `--resume`, so nothing else would clear it before the+ * next turn and the chat composer and phone would keep refusing the live CLI as "exited".+ */+ onResumed?: () => void}): Promise<ResumePhaseOutcome> {// The eligibility GATE (see performExitPhase): `canResumeWith` validates the session id without// building the command. The typed line is the caller's `d.command`; for a builtin with no@@ -475,7 +501,9 @@ export async function performResumePhase(d: {})// The session can have died while the line was being verified — the delivery is then cancelled by// the teardown and nothing reached the pane, so don't claim a resume.- return gone() ? 'not-eligible' : 'resumed'+ if (gone()) return 'not-eligible'+ d.onResumed?.()+ return 'resumed'}/**@@ -513,6 +541,8 @@ export async function performRestartResume(d: {* io then silently no-ops and reporting `'restarted'` would put a phantom in the bulk summary.*/isLive?: () => boolean+ /** See `performResumePhase`. */+ onResumed?: () => void}): Promise<RestartOutcome> {const exited = await performExitPhase({agentId: d.agentId,@@ -535,7 +565,8 @@ export async function performRestartResume(d: {deliveryTimeoutMs: d.deliveryTimeoutMs,killLine: d.killLine,onDelivery: d.onDelivery,- isLive: d.isLive+ isLive: d.isLive,+ onResumed: d.onResumed})return resumed === 'resumed' ? 'restarted' : resumed}diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.tsindex 76677fbe3..170670ee6 100644--- a/src/server/agent-status.test.ts+++ b/src/server/agent-status.test.ts@@ -496,6 +496,94 @@ it('passes observed session capacity through the Server Edition transcript jail'expect(ctx.calls).toHaveLength(before)})+/**+ * The cursor branch of the raw listener: the store is found by conversation_id under CURSOR_CONFIG_DIR+ * and the REAL tail pushes its numbers (used/max from root field 5) to the renderer channel; the+ * payload's transcript_path is never followed. The desktop copy in src/main/index.ts is the same call+ * (`trackCursorContext`), which the core tests pin.+ */+describe('wireAgentStatus: the cursor raw-listener branch', () => {+ let cfg: string, prev: string | undefined+ beforeEach(() => {+ cfg = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-cursor-'))+ prev = process.env.CURSOR_CONFIG_DIR+ process.env.CURSOR_CONFIG_DIR = cfg+ })+ afterEach(() => {+ if (prev === undefined) delete process.env.CURSOR_CONFIG_DIR+ else process.env.CURSOR_CONFIG_DIR = prev+ fs.rmSync(cfg, { recursive: true, force: true })+ })++ it('meters a cursor node from its store, and ptyDestroy releases the tail', async () => {+ const { DatabaseSync } = await import('node:sqlite')+ const id = '5667590a-e4c7-4f28-9d99-027f84c10837'+ const d = path.join(cfg, 'chats', 'b', id)+ fs.mkdirSync(d, { recursive: true })+ const db = new DatabaseSync(path.join(d, 'store.db'))+ db.exec('CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB); CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT);')+ // root: field 5 = {1: 40000, 2: 200000}+ const root = Buffer.from([0x2a, 0x08, 0x08, 0xc0, 0xb8, 0x02, 0x10, 0xc0, 0x9a, 0x0c])+ db.prepare('INSERT INTO blobs (id, data) VALUES (?, ?)').run('r00t', root)+ db.prepare("INSERT INTO meta (key, value) VALUES ('0', ?)").run(Buffer.from(JSON.stringify({ latestRootBlobId: 'r00t', name: 'New Agent' })).toString('hex'))+ db.close()++ const fh = fakeHooks()+ wireAgentStatus(platform, { hooks: fh.hooks as never })+ fh.fireRaw('cursor', 'c1', { hook_event_name: 'stop', conversation_id: id, transcript_path: '/etc/passwd' })+ const deadline = Date.now() + 3000+ const update = () => sent.find((s) => s.channel === IPC.contextUpdate)+ while (!update() && Date.now() < deadline) await new Promise((r) => setTimeout(r, 25))+ expect(update()?.args[0]).toMatchObject({ sessionId: id, usedTokens: 40000, windowTokens: 200000, windowSource: 'transcript' })+ platform.cast(platform.attach({ sendText: () => {}, sendBinary: () => {} }), IPC.ptyDestroy, ['c1'])+ })++ it("claude.sh firing with Cursor's (child) payload does not re-point the node: destroy releases the parent tail", async () => {+ // Cursor runs nodeterm's claude.sh too (Claude settings import), with its own envelope and often a+ // CHILD's chat id. The claude branch used to record that id as the node's session, so ptyDestroy+ // untracked the child and the parent's 1 Hz store tail leaked.+ const { DatabaseSync } = await import('node:sqlite')+ const parent = '5667590a-e4c7-4f28-9d99-027f84c10838'+ const child = '5667590a-e4c7-4f28-9d99-027f84c10839'+ const d = path.join(cfg, 'chats', 'b', parent)+ fs.mkdirSync(d, { recursive: true })+ const db = new DatabaseSync(path.join(d, 'store.db'))+ db.exec('CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB); CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT);')+ db.close()++ const fh = fakeHooks()+ const { cursorContextTail } = wireAgentStatus(platform, { hooks: fh.hooks as never })+ fh.fireRaw('cursor', 'c3', { hook_event_name: 'stop', conversation_id: parent, generation_id: 'g1', cursor_version: 'v' })+ const deadline = Date.now() + 3000+ while (!cursorContextTail.pathFor(parent) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 25))+ expect(cursorContextTail.pathFor(parent)).toBeTruthy()+ await new Promise((r) => setTimeout(r, 25)) // the async association lands after the track+ const childPayload = { hook_event_name: 'preToolUse', conversation_id: child, generation_id: child, session_id: child,+ cursor_version: 'v', tool_name: 'Read', transcript_path: path.join(os.homedir(), '.claude', 'projects', 'x.jsonl') }+ fh.fireRaw('claude', 'c3', childPayload)+ fh.fireRaw('cursor', 'c3', childPayload)+ await new Promise((r) => setTimeout(r, 50))+ platform.cast(platform.attach({ sendText: () => {}, sendBinary: () => {} }), IPC.ptyDestroy, ['c3'])+ expect(cursorContextTail.pathFor(parent)).toBeUndefined()+ })++ it("ptyDestroy releases the node's cursor approval watch (no read may resurrect it)", () => {+ const fh = fakeHooks()+ const released: string[] = []+ wireAgentStatus(platform, { hooks: { ...fh.hooks, releaseCursorNode: (id: string) => void released.push(id) } as never })+ platform.cast(platform.attach({ sendText: () => {}, sendBinary: () => {} }), IPC.ptyDestroy, ['c4'])+ expect(released).toEqual(['c4'])+ })++ it('an unknown chat id produces no meter and no throw', async () => {+ const fh = fakeHooks()+ wireAgentStatus(platform, { hooks: fh.hooks as never })+ fh.fireRaw('cursor', 'c2', { hook_event_name: 'stop', conversation_id: '5667590a-e4c7-4f28-9d99-027f84c10999' })+ await new Promise((r) => setTimeout(r, 100))+ expect(sent.find((s) => s.channel === IPC.contextUpdate)).toBeUndefined()+ })+})+// Claude's native SubagentStart/SubagentStop (core/claude-subagent-lifecycle.ts), replayed from the// REAL 2.1.284 capture (src/shared/agents/__fixtures__/claude/subagent-hook-payloads.json) through// this shell exactly as the hook server drives it: raw listener first, then the normalized one.diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex 53c93dcf8..67d13e3a6 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -15,12 +15,14 @@ import { recordAgentEvent, recordRawToolEvent, recordContextUsage,recordQuestionResult, turnInterruptEvent, ignoreQuestionHook} from '../core/agent-status-mirror'import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'+import { createCursorSubagentTracker } from '../core/cursor-subagents'import { ClaudeSubagentLifecycle } from '../core/claude-subagent-lifecycle'import { claudeSubagentTranscriptPath, isClaudeAgentId } from '../shared/agents/claude-subagents'import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'import { geminiContextParse } from '../core/gemini-session'import { codexContextParse } from '../core/codex-session'import { grokContextParse, GROK_SIGNALS_FILE } from '../core/grok-signals'+import { applyCursorRaw, cursorContextParse, readCursorContextSource, releaseCursorRaw } from '../core/cursor-chat'import { GROK_CHAT_HISTORY_FILE } from '../core/agents/grok-paths'import { createGrokSubagentFormatter } from '../core/grok-subagent-format'import { createCodexSubagentFormatter } from '../core/codex-subagent-format'@@ -28,7 +30,7 @@ import { codexHome } from '../core/usage/codex-usage'import { setNodeTranscript } from '../core/context-link'import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'import { linkedClaudeConfigDirs } from '../core/claude-config-dir'-import { isAsyncSubagentLaunch, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'+import { isAsyncSubagentLaunch, isCursorPayload, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'import { applyGrokHookSession } from '../core/grok-hook-session'import { IPC } from '../shared/ipc'import { subagentReplay } from '../core/subagent-replay'@@ -37,6 +39,8 @@ import type { ServerPlatform } from './platform-server'/** The narrow surface of the hook server this module needs — injectable for tests. */export interface HookLike {setListener(cb: (e: NormalizedAgentEvent) => void): void+ /** Optional so test fakes need not implement it; the real hook server does. */+ releaseCursorNode?(nodeId: string): voidsetRawListener(cb: (agentId: string,@@ -71,7 +75,7 @@ export interface WireAgentStatusOptions {export function wireAgentStatus(platform: ServerPlatform,opts: WireAgentStatusOptions = {}-): { contextTail: ContextTail; geminiContextTail: ContextTail; codexContextTail: ContextTail } {+): { contextTail: ContextTail; geminiContextTail: ContextTail; codexContextTail: ContextTail; cursorContextTail: ContextTail } {const hooks = opts.hooks ?? hookServer// nodeId → the agent session id of whichever hook-capable CLI runs in that node (claude's, and// since the grok branch below, grok's)@@ -116,6 +120,14 @@ export function wireAgentStatus(subagentTail.finish(n.toolUseId)nodeSubagents.get(nodeId)?.delete(n.toolUseId)}+ // Cursor's subagent END (its hooks never send one) and child tail; same tracker in the desktop.+ const cursorSubagents = createCursorSubagentTracker({+ tail: subagentTail,+ emit: (ev) => {+ platform.broadcast(IPC.agentStatus, ev)+ recordAgentEvent(ev)+ }+ })/** See the identical handler in src/main/index.ts: a tool RESULT settles an ask that ended with* no hook (Esc on an AskUserQuestion), which otherwise left the node stuck on needs-you. */@@ -172,6 +184,12 @@ export function wireAgentStatus(parse: grokContextParse,wholeFile: true})+ // cursor's fourth tail. Its numbers are in a SQLite store, not a text file, so `readSource` replaces+ // the byte read (stat-gated on the db + WAL). Same construction in both shells (invariant 11).+ const cursorContextTail = createContextTail(pushContextUpdate, {+ parse: cursorContextParse,+ readSource: readCursorContextSource+ })const emit = (e: NormalizedAgentEvent): void => {// Claude subagent events first become one card per child (claudeSubagents above); every other@@ -220,6 +238,16 @@ export function wireAgentStatus(const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])// Hook server validates session-env capacity and caller identity once for both shells.hooks.setRawListener((agentId, nodeId, payload, _meta) => {+ if (agentId === 'cursor') {+ // Same shared step as the desktop (core/cursor-chat.ts `applyCursorRaw`). The server has no+ // SSH projects, so nothing here is remote.+ applyCursorRaw(+ { tail: cursorContextTail, subagents: cursorSubagents, nodeSession: nodeContextSession, isRemote: () => false },+ nodeId,+ payload+ )+ return+ }if (agentId === 'grok') {// This branch records two associations, neither of which grok's envelope states outright.// Everything the claude path does below hangs off `transcript_path`. Grok DOES send one --@@ -374,6 +402,9 @@ export function wireAgentStatus(// Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).// Independent of the transcript-tailing below (no path needed), so it runs first.recordRawToolEvent(nodeId, payload)+ // Cursor runs claude.sh too (Claude settings import), often with a CHILD's chat id: recording it+ // here re-pointed the node's session, so the parent's cursor tail leaked past pty:destroy.+ if (isCursorPayload(payload)) return// Claude's native subagent hooks, BEFORE the child-event gate below: that gate ignores every// agent_id-tagged payload, and these carry the CHILD's agent_id with the PARENT's// transcript_path. All they drive here is the child's own transcript tail, started at@@ -445,6 +476,9 @@ export function wireAgentStatus(// the old session's tails are dead either way (the respawned agent re-registers its own).const releaseNodeTails = (nodeId: string): void => {claudeSubagents.forgetNode(nodeId)+ cursorSubagents.release(nodeId)+ releaseCursorRaw(nodeId)+ hooks.releaseCursorNode?.(nodeId)const sessionId = nodeContextSession.get(nodeId)if (sessionId) {// Every agent's tail, not just claude's: `nodeContextSession` now holds gemini and codex@@ -454,6 +488,7 @@ export function wireAgentStatus(geminiContextTail.untrack(sessionId)codexContextTail.untrack(sessionId)grokContextTail.untrack(sessionId)+ cursorContextTail.untrack(sessionId)nodeContextSession.delete(nodeId)}const subs = nodeSubagents.get(nodeId)@@ -468,5 +503,5 @@ export function wireAgentStatus(// `codexContextTail` joins the two already returned so `src/server/index.ts` can register the// context-meter rehydration over all three. Keeping a tail private here would mean a second// instance somewhere else metering the same sessions twice.- return { contextTail, geminiContextTail, codexContextTail }+ return { contextTail, geminiContextTail, codexContextTail, cursorContextTail }}diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex 60d358154..d1009a254 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -8,6 +8,7 @@ import { generateCommitMessage } from '../../core/commit-message'import { registerFsHandlers } from '../../core/fs-handlers'import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'import { registerGrokCliIpc } from '../../core/grok-cli'+import { registerCursorCliIpc } from '../../core/cursor-cli'import { registerCodexIdentityIpc } from '../../core/codex-identity-caps'import { registerCodexCliIpc } from '../../core/codex-cli'import { registerWallpaperIpc } from '../../core/wallpaper'@@ -79,6 +80,7 @@ export function registerCoreHandlers(// Invariant 11 for probes: registered in BOTH shells, or session-id minting silently works on// the desktop and not in the browser, with nothing to say which.registerGrokCliIpc()+ registerCursorCliIpc()// The codex CLI's own approval vocabulary, and this one is registered FOR REAL rather than// stubbed. `registerCodexIdentityIpc` below declines a shared app-server on purpose; this is the// opposite case, and the distinction matters — the Server Edition's Codex sessions run on THISdiff --git a/src/server/index.ts b/src/server/index.tsindex dada1c2fc..8124d26cb 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -560,9 +560,11 @@ export async function startServer(// rather than an unknown channel when canvas control is off.registerStationOutcomeIpc(platform, () => canvasControl?.stationOutcomes ?? null)registerStationHandoverIpc(platform, () => canvasControl?.stationHandovers ?? null)- const { contextTail, geminiContextTail, codexContextTail } = wireAgentStatus(platform, {+ const { contextTail, geminiContextTail, codexContextTail, cursorContextTail } = wireAgentStatus(platform, {onEvent: (event) => canvasControl?.onAgentEvent(event)})+ // Cursor NEEDS YOU, same seam as the desktop (core/agents/cursor-approval.ts).+ hookServer.setPaneReader((nodeId) => ptyManager.captureSession(nodeId))// Which claude may speak for a node (#1112, #1153): the pane tty from THIS shell's PtyManager.// Same call as the desktop's (hook-verified-parity.test.ts).wireClaudePaneOrigin({@@ -606,6 +608,8 @@ export async function startServer(return codexContextTailcase 'gemini':return geminiContextTail+ case 'cursor':+ return cursorContextTaildefault:return undefined}diff --git a/src/shared/agents/__fixtures__/cursor/ask-question.json b/src/shared/agents/__fixtures__/cursor/ask-question.jsonnew file mode 100644index 000000000..b942b1c31--- /dev/null+++ b/src/shared/agents/__fixtures__/cursor/ask-question.json@@ -0,0 +1,217 @@+{+ "_provenance": "Captured live from cursor-agent 2026.10.01-e373342 (macOS), 2026-10-04, INTERACTIVE TUI (--model composer-2.5 --trust) in a private tmux server (120x40, and 60x40 for the wrapped footer), scratch workspace with a logging hook for 15 events in <workspace>/.cursor/hooks.json. Prompt: ask red or blue with the question tool, then stop. Panes are capture-pane -p with trailing spaces and blank lines dropped. Hooks keep only the events nodeterm subscribes; email and workspace path redacted. Between beforeSubmitPrompt and stop only afterAgentThought fired (not subscribed): AskQuestion fires NO tool hook on show, answer (Enter) or skip (Esc). Every run's stop came 20 to 40 s after the answer with status error (the pane printed 'WritableIterable is closed').",+ "panes": {+ "shownDefaultTitle": [+ " Cursor Agent",+ " v2026.10.01-e373342",+ " Tip: Try Cursor Grok 4.6 via /model, frontier intelligence at a fraction of the cost.",+ " Before doing anything, ask me with your question tool whether I prefer red or blue, then stop.",+ " I'll ask your color preference with the question tool, then stop.",+ " ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐",+ " │ Clarifying Questions │",+ " │ │",+ " │ Question 1 of 1 │",+ " │ │",+ " │ 1. Do you prefer red or blue? │",+ " │ │",+ " │ › [ ] Red │",+ " │ [ ] Blue │",+ " │ [ ] Other: (type to answer) │",+ " │ │",+ " │ ↑/↓ option · ←/→ question · Space select · Enter next/submit · Esc to skip │",+ " └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘"+ ],+ "shownWrappedFooter": [+ " Cursor Agent",+ " v2026.10.01-e373342",+ " Tip: Use /run-everything to skip all approvals.",+ " Before doing anything, ask me two questions in one",+ " call of your question tool: red or blue, and cats",+ " or dogs (multi-select). Then stop.",+ " ┌────────────────────────────────────────────────────────┐",+ " │ Quick preferences │",+ " │ │",+ " │ Question 1 of 2 │",+ " │ │",+ " │ 1. Red or blue? │",+ " │ │",+ " │ › [ ] Red │",+ " │ [ ] Blue │",+ " │ [ ] Other: (type to answer) │",+ " │ │",+ " │ ↑/↓ option · ←/→ question · Space select · Enter │",+ " │ next/submit · Esc to skip │",+ " └────────────────────────────────────────────────────────┘"+ ],+ "shownSecondOfTwoSelected": [+ " Cursor Agent",+ " v2026.10.01-e373342",+ " Tip: Use /run-everything to skip all approvals.",+ " Before doing anything, ask me two questions in one",+ " call of your question tool: red or blue, and cats",+ " or dogs (multi-select). Then stop.",+ " ┌────────────────────────────────────────────────────────┐",+ " │ Quick preferences │",+ " │ │",+ " │ Question 2 of 2 │",+ " │ │",+ " │ 2. Cats or dogs? (multi-select) │",+ " │ │",+ " │ › [x] Cats │",+ " │ [ ] Dogs │",+ " │ [ ] Other: (type to answer) │",+ " │ │",+ " │ ↑/↓ option · ←/→ question · Space select · Enter │",+ " │ next/submit · Esc to skip │",+ " └────────────────────────────────────────────────────────┘"+ ],+ "answered": [+ " Cursor Agent",+ " v2026.10.01-e373342",+ " Tip: Use /run-everything to skip all approvals.",+ " Before doing anything, ask me two questions in one",+ " call of your question tool: red or blue, and cats",+ " or dogs (multi-select). Then stop.",+ " AskQuestion Quick preferences (2)",+ " 1. Red or blue?",+ " [x] Red",+ " [ ] Blue",+ " 2. Cats or dogs? (multi-select)",+ " [x] Cats",+ " [ ] Dogs",+ " ⠘⠆ Composing 128 tokens",+ " → Add a follow-up ctrl+c to stop",+ " Composer 2.5 · 8.8%",+ " /private/tmp/ntq-ask"+ ],+ "answeredReconnecting": [+ " Cursor Agent",+ " v2026.10.01-e373342",+ " Tip: Try Cursor Grok 4.6 via /model, frontier intelligence at a fraction of the cost.",+ " Before doing anything, ask me with your question tool whether I prefer red or blue, then stop.",+ " I'll ask your color preference with the question tool, then stop.",+ " AskQuestion Clarifying Questions (1)",+ " 1. Do you prefer red or blue?",+ " [ ] Red",+ " [x] Blue",+ " You chose blue. Stopping here as requested.",+ " ⠠⠜ Reconnecting to agentn.global.api5.cursor.sh (attempt 3, 2s)",+ " → Add a follow-up",+ " Composer 2.5 · 10.2%",+ " /private/tmp/ntq-ask"+ ],+ "skipped": [+ " Cursor Agent",+ " v2026.10.01-e373342",+ " Tip: Type ? in the prompt bar to show in-app hints.",+ " Before doing anything, ask me with your question tool whether I prefer red or blue, then stop.",+ " AskQuestion Color preference (1) Questions skipped by user",+ " 1. Do you prefer red or blue?",+ " [ ] Red",+ " [ ] Blue",+ " Question asked: Do you prefer red or blue?",+ " You skipped it, so I’m stopping here as requested. If you want to answer, just reply with red or blue.",+ " → Add a follow-up",+ " Composer 2.5 · 10.6%",+ " /private/tmp/ntq-ask",+ " Error: Something went wrong. Please try again.",+ " WritableIterable is closed"+ ]+ },+ "hooks": {+ "answeredEnter": [+ {+ "conversation_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "generation_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "model": "composer-2.5",+ "is_background_agent": false,+ "session_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "hook_event_name": "sessionStart",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "transcript_path": null+ },+ {+ "conversation_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "generation_id": "6f6ddc3e-a2c1-4911-8985-490c5c92e713",+ "model": "composer-2.5",+ "prompt": "Before doing anything, ask me with your question tool whether I prefer red or blue, then stop.",+ "attachments": [],+ "session_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "hook_event_name": "beforeSubmitPrompt",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "transcript_path": null+ },+ {+ "conversation_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "generation_id": "6f6ddc3e-a2c1-4911-8985-490c5c92e713",+ "model": "composer-2.5",+ "status": "error",+ "loop_count": 0,+ "input_tokens": 20400,+ "output_tokens": 7,+ "cache_read_tokens": 20384,+ "cache_write_tokens": 0,+ "session_id": "e030ef45-48c7-4a68-ac3d-acecbe9b3648",+ "hook_event_name": "stop",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "transcript_path": "<home>/.cursor/projects/private-tmp-ntq-ask/agent-transcripts/e030ef45-48c7-4a68-ac3d-acecbe9b3648/e030ef45-48c7-4a68-ac3d-acecbe9b3648.jsonl"+ }+ ],+ "skippedEsc": [+ {+ "conversation_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "generation_id": "a85821b1-e822-4f13-a9d0-99d4f56c114f",+ "model": "composer-2.5",+ "prompt": "Before doing anything, ask me with your question tool whether I prefer red or blue, then stop.",+ "attachments": [],+ "session_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "hook_event_name": "beforeSubmitPrompt",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "transcript_path": null+ },+ {+ "conversation_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "generation_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "model": "composer-2.5",+ "is_background_agent": false,+ "session_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "hook_event_name": "sessionStart",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "transcript_path": null+ },+ {+ "conversation_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "generation_id": "a85821b1-e822-4f13-a9d0-99d4f56c114f",+ "model": "composer-2.5",+ "status": "error",+ "loop_count": 0,+ "input_tokens": 21083,+ "output_tokens": 163,+ "cache_read_tokens": 20590,+ "cache_write_tokens": 0,+ "session_id": "6c1609ff-93f4-45ec-8f9b-ff19b5212399",+ "hook_event_name": "stop",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "transcript_path": "<home>/.cursor/projects/private-tmp-ntq-ask/agent-transcripts/6c1609ff-93f4-45ec-8f9b-ff19b5212399/6c1609ff-93f4-45ec-8f9b-ff19b5212399.jsonl"+ }+ ]+ }+}diff --git a/src/shared/agents/__fixtures__/cursor/hook-payloads.json b/src/shared/agents/__fixtures__/cursor/hook-payloads.jsonnew file mode 100644index 000000000..96593716d--- /dev/null+++ b/src/shared/agents/__fixtures__/cursor/hook-payloads.json@@ -0,0 +1,152 @@+{+ "_provenance": "Captured live from cursor-agent 2026.09.28-64d2043 (macOS), 2026-09-28, headless (-p) runs in a scratch workspace with a logging hook in <workspace>/.cursor/hooks.json. Email, workspace path, home path and thought text are redacted; keys, value shapes and ids are as measured. beforeSubmitPrompt, stop and postToolUseFailure are ABSENT: headless runs never fired the first two and no tool failed.",+ "events": [+ {+ "conversation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "generation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "model": "composer-2.5",+ "is_background_agent": false,+ "session_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "hook_event_name": "sessionStart",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": null+ },+ {+ "conversation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "generation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "model": "composer-2.5",+ "tool_name": "Shell",+ "tool_input": {+ "command": "echo hi",+ "cwd": "",+ "timeout": 30000+ },+ "tool_use_id": "5e1eb2b6-0a8b-449c-8810-bd94cd3d73ee",+ "cwd": "",+ "session_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "hook_event_name": "preToolUse",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": null+ },+ {+ "conversation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "generation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "model": "composer-2.5",+ "tool_name": "Shell",+ "tool_input": {+ "command": "echo hi",+ "cwd": "",+ "timeout": 30000+ },+ "tool_output": "{\"output\":\"hi\\n\",\"exitCode\":0}",+ "duration": 1752.623,+ "tool_use_id": "5e1eb2b6-0a8b-449c-8810-bd94cd3d73ee",+ "cwd": "",+ "session_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "hook_event_name": "postToolUse",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": "/redacted/.cursor/projects/workspace/agent-transcripts/5a27c746-14a7-472d-8e3f-7f335a9df0db/5a27c746-14a7-472d-8e3f-7f335a9df0db.jsonl"+ },+ {+ "conversation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "generation_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "model": "composer-2.5",+ "reason": "completed",+ "duration_ms": 18067,+ "is_background_agent": false,+ "final_status": "completed",+ "session_id": "5a27c746-14a7-472d-8e3f-7f335a9df0db",+ "hook_event_name": "sessionEnd",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": "/redacted/.cursor/projects/workspace/agent-transcripts/5a27c746-14a7-472d-8e3f-7f335a9df0db/5a27c746-14a7-472d-8e3f-7f335a9df0db.jsonl"+ },+ {+ "conversation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "generation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "model": "composer-2.5",+ "reason": "error",+ "duration_ms": 44527,+ "is_background_agent": false,+ "final_status": "error",+ "session_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "hook_event_name": "sessionEnd",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": "/redacted/.cursor/projects/workspace/agent-transcripts/22bc77d0-3f77-4629-af8d-f31330036c61/22bc77d0-3f77-4629-af8d-f31330036c61.jsonl"+ },+ {+ "conversation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "generation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "model": "composer-2.5",+ "command": "echo hi",+ "cwd": "",+ "sandbox": false,+ "session_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "hook_event_name": "beforeShellExecution",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": "/redacted/.cursor/projects/workspace/agent-transcripts/22bc77d0-3f77-4629-af8d-f31330036c61/22bc77d0-3f77-4629-af8d-f31330036c61.jsonl"+ },+ {+ "conversation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "generation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "model": "composer-2.5",+ "command": "echo hi",+ "output": "hi\n",+ "duration": 1737.509,+ "sandbox": false,+ "session_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "hook_event_name": "afterShellExecution",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": "/redacted/.cursor/projects/workspace/agent-transcripts/22bc77d0-3f77-4629-af8d-f31330036c61/22bc77d0-3f77-4629-af8d-f31330036c61.jsonl"+ },+ {+ "conversation_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "generation_id": "877b955c-3031-4f36-a6ac-8f9351e7cbc9-0-x2z7",+ "model": "composer-2.5",+ "model_id": "composer-2.5",+ "model_params": [+ {+ "id": "speed",+ "value": "default"+ }+ ],+ "text": "redacted",+ "duration_ms": 1,+ "session_id": "22bc77d0-3f77-4629-af8d-f31330036c61",+ "hook_event_name": "afterAgentThought",+ "cursor_version": "2026.09.28-64d2043",+ "workspace_roots": [+ "/redacted/workspace"+ ],+ "user_email": "[email protected]",+ "transcript_path": null+ }+ ]+}diff --git a/src/shared/agents/__fixtures__/cursor/subagent-payloads.json b/src/shared/agents/__fixtures__/cursor/subagent-payloads.jsonnew file mode 100644index 000000000..6f0e0bb99--- /dev/null+++ b/src/shared/agents/__fixtures__/cursor/subagent-payloads.json@@ -0,0 +1,110 @@+{+ "_provenance": "Captured live from cursor-agent 2026.10.01-e373342 (macOS), 2026-10-02, INTERACTIVE TUI in a private tmux server, scratch workspace with a logging hook for 10 events (incl. subagentStart/subagentStop) in <workspace>/.cursor/hooks.json. Turn: \"Use the probe-reader subagent to read config.txt\" (a custom .cursor/agents subagent). Email and home/workspace paths redacted; ids, keys and shapes as measured. subagentStart/subagentStop NEVER fired (3 subagent runs: explore x2, custom x1), and the parent Task got preToolUse but no postToolUse. childStoreSubagentInfo is the child chat store.db meta field; childTranscript is the child agent-transcripts JSONL, verbatim.",+ "events": [+ {+ "conversation_id": "13993e38-911a-4558-8af0-73729368b113",+ "generation_id": "405aea4a-6015-4ab7-9086-3ed421b1f8b8",+ "model": "composer-2.5",+ "prompt": "Use the probe-reader subagent to read config.txt and tell me what it returned. Do not read the file yourself.",+ "attachments": [],+ "session_id": "13993e38-911a-4558-8af0-73729368b113",+ "hook_event_name": "beforeSubmitPrompt",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "user_email": "<redacted>",+ "transcript_path": "<home>/.cursor/projects/private-tmp-ntc-f1-proj/agent-transcripts/13993e38-911a-4558-8af0-73729368b113/13993e38-911a-4558-8af0-73729368b113.jsonl"+ },+ {+ "conversation_id": "13993e38-911a-4558-8af0-73729368b113",+ "generation_id": "405aea4a-6015-4ab7-9086-3ed421b1f8b8",+ "model": "",+ "tool_name": "Task",+ "tool_input": {+ "description": "probe-reader read config.txt",+ "prompt": "You are the probe-reader agent defined at <workspace>/.cursor/agents/probe-reader.md.\n\nYour only job: read the single file config.txt in the workspace <workspace> and return its exact contents verbatim. Nothing else \u2014 no summary, no commentary, no preamble.",+ "model": "fast",+ "subagent_type": "explore"+ },+ "tool_use_id": "tool_0bcae8bf-7874-44ec-85f1-2de6e08f84d",+ "session_id": "13993e38-911a-4558-8af0-73729368b113",+ "hook_event_name": "preToolUse",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "user_email": "<redacted>",+ "transcript_path": "<home>/.cursor/projects/private-tmp-ntc-f1-proj/agent-transcripts/13993e38-911a-4558-8af0-73729368b113/13993e38-911a-4558-8af0-73729368b113.jsonl"+ },+ {+ "conversation_id": "d7074c73-aa64-42cb-80d0-fe56cdfb6082",+ "generation_id": "d7074c73-aa64-42cb-80d0-fe56cdfb6082",+ "model": "composer-2.5",+ "tool_name": "Read",+ "tool_input": {+ "file_path": "<workspace>/config.txt"+ },+ "tool_use_id": "tool_c6b40a00-f2e9-4464-a0cd-ea43fb7cdec",+ "session_id": "d7074c73-aa64-42cb-80d0-fe56cdfb6082",+ "hook_event_name": "preToolUse",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "user_email": "<redacted>",+ "transcript_path": null+ },+ {+ "conversation_id": "d7074c73-aa64-42cb-80d0-fe56cdfb6082",+ "generation_id": "d7074c73-aa64-42cb-80d0-fe56cdfb6082",+ "model": "composer-2.5",+ "tool_name": "Read",+ "tool_input": {+ "file_path": "<workspace>/config.txt"+ },+ "tool_output": "{\"file_path\":\"<workspace>/config.txt\",\"content_length\":4}",+ "duration": 0.826,+ "tool_use_id": "tool_c6b40a00-f2e9-4464-a0cd-ea43fb7cdec",+ "session_id": "d7074c73-aa64-42cb-80d0-fe56cdfb6082",+ "hook_event_name": "postToolUse",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "user_email": "<redacted>",+ "transcript_path": "<home>/.cursor/projects/private-tmp-ntc-f1-proj/agent-transcripts/d7074c73-aa64-42cb-80d0-fe56cdfb6082/d7074c73-aa64-42cb-80d0-fe56cdfb6082.jsonl"+ },+ {+ "conversation_id": "13993e38-911a-4558-8af0-73729368b113",+ "generation_id": "405aea4a-6015-4ab7-9086-3ed421b1f8b8",+ "model": "composer-2.5",+ "status": "completed",+ "loop_count": 0,+ "input_tokens": 156902,+ "output_tokens": 1469,+ "cache_read_tokens": 150502,+ "cache_write_tokens": 0,+ "session_id": "13993e38-911a-4558-8af0-73729368b113",+ "hook_event_name": "stop",+ "cursor_version": "2026.10.01-e373342",+ "workspace_roots": [+ "<workspace>"+ ],+ "user_email": "<redacted>",+ "transcript_path": "<home>/.cursor/projects/private-tmp-ntc-f1-proj/agent-transcripts/13993e38-911a-4558-8af0-73729368b113/13993e38-911a-4558-8af0-73729368b113.jsonl"+ }+ ],+ "childStoreSubagentInfo": {+ "parentAgentId": "13993e38-911a-4558-8af0-73729368b113",+ "rootParentAgentId": "13993e38-911a-4558-8af0-73729368b113",+ "toolCallId": "tool_0bcae8bf-7874-44ec-85f1-2de6e08f84d",+ "typeName": "explore"+ },+ "childTranscript": [+ "{\"role\":\"user\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"<timestamp>Friday, Oct 2, 2026, 12:21 PM (UTC-4)</timestamp>\\n<user_query>\\nYou are the probe-reader agent defined at <workspace>/.cursor/agents/probe-reader.md.\\n\\nYour only job: read the single file config.txt in the workspace <workspace> and return its exact contents verbatim. Nothing else \u2014 no summary, no commentary, no preamble.\\n</user_query>\"}]}}",+ "{\"role\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"[REDACTED]\"},{\"type\":\"tool_use\",\"name\":\"Read\",\"input\":{\"path\":\"<workspace>/config.txt\"}}]}}",+ "{\"role\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"a=1\\n\\n[REDACTED]\"}]}}",+ "{\"type\":\"turn_ended\",\"status\":\"success\"}"+ ]+}\ No newline at end of filediff --git a/src/shared/agents/approval-mode.test.ts b/src/shared/agents/approval-mode.test.tsindex 2cdc29804..acc31822e 100644--- a/src/shared/agents/approval-mode.test.ts+++ b/src/shared/agents/approval-mode.test.ts@@ -10,6 +10,7 @@ import {} from './approval-mode'import {ALL_PERMISSION_MODES,+ DEFAULT_PERMISSION_MODE,PERMISSION_MODE_LABELS,type AgentPermissionMode} from './config'@@ -206,6 +207,59 @@ describe('approvalFlags — codex REFUSES what it cannot express', () => {})+/**+ * cursor-agent 2026.09.28-64d2043. Its modes are different FLAGS, not values of one+ * (`--mode plan`, bare `--force`), and its bare launch is `approvalMode: allowlist`, which prompts.+ * Measured in a real run, see CURSOR_MODES.+ */+describe('approvalFlags: cursor', () => {+ it('maps auto to --auto-review, plan to --mode plan and bypass to --force, and nothing else', () => {+ expect(approvalFlags('cursor', 'auto')).toEqual(['--auto-review'])+ expect(approvalFlags('cursor', 'plan')).toEqual(['--mode', 'plan'])+ expect(approvalFlags('cursor', 'bypassPermissions')).toEqual(['--force'])+ for (const m of ['manual', 'acceptEdits'] as const)+ expect(approvalFlags('cursor', m), m).toEqual([])+ })++ it('launches the DEFAULT mode in Auto-review, never in Run Everything', () => {+ // `auto` is DEFAULT_PERMISSION_MODE. Measured: `--auto-review` auto-runs safe calls through a+ // classifier and still prompts for the rest; a bare cursor asks for every command.+ expect(approvalFlags('cursor', DEFAULT_PERMISSION_MODE)).toEqual(['--auto-review'])+ expect(withPermissionMode('cursor-agent', 'cursor', DEFAULT_PERMISSION_MODE)).toBe(+ 'cursor-agent --auto-review'+ )+ for (const m of ALL_PERMISSION_MODES)+ expect(approvalFlags('cursor', m).join(' '), m).not.toMatch(/yolo|sandbox|ask/)+ expect(approvalFlags('cursor', DEFAULT_PERMISSION_MODE)).not.toContain('--force')+ })++ it('admits exactly the modes it cannot express', () => {+ expect(modeSupported('cursor', 'manual')).toBe(true) // its own default already prompts+ expect(modeSupported('cursor', 'auto')).toBe(true)+ expect(modeSupported('cursor', 'plan')).toBe(true)+ expect(modeSupported('cursor', 'bypassPermissions')).toBe(true)+ expect(modeSupported('cursor', 'acceptEdits')).toBe(false)+ expect(unsupportedModesNote()).not.toMatch(/Auto and Accept edits have no Cursor/)+ expect(unsupportedModesNote()).toMatch(/Accept edits has no Cursor equivalent/)+ })++ it('lets a wrapper that already spells the flag win, per flag', () => {+ expect(withPermissionMode('cursor-agent --force', 'cursor', 'bypassPermissions')).toBe(+ 'cursor-agent --force'+ )+ expect(withPermissionMode('cursor-agent --mode ask', 'cursor', 'plan')).toBe(+ 'cursor-agent --mode ask'+ )+ })++ it('names cursor in the Bypass warning list but not in the sandbox caveat', () => {+ expect(permissionModeAgentsLabel({ mode: 'bypassPermissions' })).toContain('Cursor')+ // cursor's sandbox is off by default (`sandbox.mode: disabled`), so "still runs in its own+ // sandbox" would be false for it.+ expect(bypassSandboxCaveat()).not.toContain('Cursor')+ })+})+describe('approvalFlags — an agent with no permission mode', () => {it('emits nothing for opencode and for a custom agent', () => {for (const id of ['opencode', 'custom:abc']) {@@ -222,7 +276,8 @@ describe('approvalFlags — an agent with no permission mode', () => {describe('UI copy derived from the mapping', () => {it('names every agent whose start-up mode we can set', () => {const label = permissionModeAgentsLabel()- for (const name of ['Claude Code', 'Grok', 'Gemini', 'Codex']) expect(label).toContain(name)+ for (const name of ['Claude Code', 'Grok', 'Gemini', 'Codex', 'Cursor'])+ expect(label).toContain(name)expect(label).not.toContain('opencode')})@@ -231,9 +286,9 @@ describe('UI copy derived from the mapping', () => {// the same drift the label helper exists to prevent, one level down. The ids are exported so the// caller can agree with them; this pins that they describe the SAME set the label does.const ids = permissionModeAgentIds({ exclude: ['claude'] })- expect(ids).toEqual(['grok', 'gemini', 'codex'])+ expect(ids).toEqual(['grok', 'gemini', 'codex', 'cursor'])const label = permissionModeAgentsLabel({ exclude: ['claude'] })- for (const id of ids) expect(label.toLowerCase()).toContain(id === 'codex' ? 'codex' : id)+ for (const id of ids) expect(label.toLowerCase()).toContain(id)expect(label).not.toContain('Claude')})diff --git a/src/shared/agents/approval-mode.ts b/src/shared/agents/approval-mode.tsindex 19719a0e0..7defb13c6 100644--- a/src/shared/agents/approval-mode.ts+++ b/src/shared/agents/approval-mode.ts@@ -99,6 +99,9 @@ interface ApprovalDialect {/** What this CLI actually does when `manual` turns out to be inexpressible, for the UI note.* Lives beside the table so the sentence cannot drift from it. */manualGapNote?: string+ /** argv for a table value. Default `[flag, value]`. Only for a CLI whose modes are DIFFERENT+ * flags rather than values of one (cursor: `--mode plan` but a bare `--force`). */+ spell?: (value: string) => string[]}const GEMINI_MODES: Partial<Record<AgentPermissionMode, string>> = {@@ -150,6 +153,36 @@ const CODEX_MODES: Partial<Record<AgentPermissionMode, string>> = {// `plan` and `acceptEdits` are absent ON PURPOSE — see modeSupported.}+const CURSOR_MODES: Partial<Record<AgentPermissionMode, string>> = {+ auto: 'auto-review',+ plan: 'plan',+ bypassPermissions: 'force'+ // MEASURED on cursor-agent 2026.09.28-64d2043: the flags reach the session from BEFORE the `agent`+ // subcommand (see AGENT_CONFIG.cursor), and the effect is real, not just a footer label. With+ // `--model composer-2.5 --force agent '<touch a file>'` the shell command ran with no approval+ // prompt and the footer read "Run Everything"; the same command with no mode flag stopped at+ // "Run this command? Not in allowlist: touch"; `--mode plan` answered a "create a file" prompt+ // with a written plan ("Ready to build?") and created nothing.+ //+ // `manual` → cursor's own default, NO flag, and that default really prompts: `approvalMode:+ // "allowlist"` in ~/.cursor/cli-config.json, shell commands off the allowlist stop at a dialog.+ //+ // `auto` → `--auto-review` ("Auto-review (Smart Auto): a server classifier auto-runs safe tool+ // calls and prompts for the rest"). That is the same shape as claude's `--permission-mode auto`+ // (a classifier decides), so it is the honest equivalent, not a nearest match. MEASURED on+ // 2026.10.01-e373342: `--auto-review agent '<touch a file>'` ran `touch` with no prompt and the+ // footer read "Auto-review". `auto` is DEFAULT_PERMISSION_MODE, so this IS what an untouched cursor+ // node launches with. It was first left bare to avoid widening existing nodes at upgrade (the+ // gemini `auto_edit` trap), but cursor ships in this same change, so there are no existing nodes,+ // and the bare allowlist default asked for every command (the user's own report, 2026-10-02).+ // No flag means "auto-approve edits, prompt for shell", so `acceptEdits` has no candidate and+ // `unsupportedModesNote` admits it. `--mode ask` (read-only Q&A) and `--sandbox` (a separate+ // axis, like codex's) are deliberately not touched.+ //+ // `--force` over its alias `--yolo`: same code path ("Run Everything"), and `--force` is the name+ // `--help` gives first.+}+/*** The agents that need a translation, flag and vocabulary together.*@@ -172,6 +205,13 @@ const APPROVAL_DIALECTS: Partial<Record<AgentId, ApprovalDialect>> = {manualGapNote:'That default asks only when the model chooses to: `untrusted`, the policy that meant ' +'ask-every-time, was removed in codex-cli 0.149.0 and has no replacement.'+ },+ cursor: {+ flag: '--mode',+ modes: CURSOR_MODES,+ manualIsDefault: true,+ spell: (value) =>+ value === 'force' ? ['--force'] : value === 'auto-review' ? ['--auto-review'] : ['--mode', value]}}@@ -238,7 +278,7 @@ export function approvalFlags(const dialect = dialectFor(agentId)if (dialect) {const value = emittableValue(dialect, mode, caps)- return value ? [dialect.flag, value] : []+ return value ? (dialect.spell?.(value) ?? [dialect.flag, value]) : []}// claude + grok keep their exact historical spelling, validated at the interpolation site.return hasPermissionMode(agentId) ? permissionModeFlag(mode) : []@@ -250,7 +290,8 @@ export function approvalFlags(** WHERE the flag lands is decided one layer up, by `createAgentNode`: with no `argvPromptSeparator`* (claude, gemini, codex) it goes LAST, keeping those command lines byte-identical; with one- * (grok's `--`) it must go BEFORE the separator, because `--` is end-of-options.+ * (grok's `--`, cursor's `agent`) it must go BEFORE the separator: `--` is end-of-options, and+ * cursor's flags are root options that the `agent` subcommand reads (measured, see CURSOR_MODES).** **A flag the command already carries is left alone (issue #601).** `cmd` is not always ours:* `settings.agentLaunchCommands` lets the user replace the program part with a wrapper, and adiff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex 901354930..96181d196 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -1,9 +1,11 @@import { describe, it, expect } from 'vitest'+import { normalizeFor } from './normalize'import {AGENT_CONFIG,BUILTIN_AGENT_IDS,canBranch,canChat,+ chatReadsLocalOnly,mintsSessionId,supportsSessionIdFlag,readsClaudeShapedTranscript,@@ -18,8 +20,11 @@ import {canSwitchModel,createdAgentId,hasHooks,+ hasGatewayModels,hasPermissionMode,hasUsage,+ MODEL_SWITCH_CAPABLE,+ OWN_MODEL_CATALOGUE,reportsOwnCopy,RENAME_CAPABLE,hasSharedIdentity,@@ -32,8 +37,11 @@ import {readsScreenDialogs,queuesInputWhileWorking,LOCAL_ONLY_HOOK_AGENTS,- reportsSessionEnd+ reportsSessionEnd,+ resumeCommandWith,+ submitsSeparately} from './config'+import { CURSOR_HOOK_EVENTS } from './hook-events'describe('CONTEXT_LINK_CAPABLE', () => {it('all three builtin agents can context-link', () => {@@ -54,10 +62,23 @@ describe('MODEL_SWITCH_CAPABLE', () => {// grok joined once its leaf existed: `-m/--model` in the launch grammar plus `grok models` for// discovery. It is NOT in this list as an example of a non-capable agent any more.expect(canSwitchModel('grok')).toBe(true)+ // cursor: `--model <id>` (a root option, measured before and after `agent`). Its models are its+ // own catalogue, so it joins the list WITHOUT the gateway's models (OWN_MODEL_CATALOGUE).+ expect(canSwitchModel('cursor')).toBe(true)+ expect(hasGatewayModels('cursor')).toBe(false)+ expect(hasGatewayModels('grok')).toBe(false)+ for (const id of ['claude', 'codex', 'copilot'] as const)+ expect(hasGatewayModels(id), id).toBe(true)for (const id of ['gemini', 'opencode', 'custom:plain'] as const) {expect(canSwitchModel(id), id).toBe(false)+ expect(hasGatewayModels(id), id).toBe(false)}})++ it('OWN_MODEL_CATALOGUE is a subset of the switch-capable list', () => {+ for (const id of OWN_MODEL_CATALOGUE)+ expect(MODEL_SWITCH_CAPABLE as readonly string[]).toContain(id)+ })})describe('copilot capabilities', () => {@@ -177,10 +198,11 @@ describe('grok capabilities', () => {expect(AGENT_CONFIG.grok.argvPromptSeparator).toBe('--')})- it('is the ONLY agent that asks for a separator', () => {+ it('is the only agent besides cursor that asks for a separator', () => {// claude takes a positional too, but has no subcommand a one-word prompt could shadow — and- // adding `--` there would change a command line that works today.- for (const id of BUILTIN_AGENT_IDS.filter((a) => a !== 'grok')) {+ // adding `--` there would change a command line that works today. cursor needs one for the+ // same reason as grok, but its CLI ignores `--` (see the cursor block below).+ for (const id of BUILTIN_AGENT_IDS.filter((a) => a !== 'grok' && a !== 'cursor')) {expect(AGENT_CONFIG[id].argvPromptSeparator, id).toBeUndefined()}})@@ -382,6 +404,31 @@ describe('antigravity capabilities', () => {})})+/**+ * Cursor's lists so far: AGENT_HOOK_TARGETS (badge, unread dot, completion notification, `--after`+ * dependency and trigger target; leaves `normalizeCursor` + the `~/.cursor/hooks.json` installer),+ * PERMISSION_MODE_CAPABLE and MODEL_SWITCH_CAPABLE (leaf: CURSOR_MODES in approval-mode.ts).+ * Everything else is a separate leaf that does not exist yet; docs/cursor-agent.md says which.+ */+describe('cursor capabilities', () => {+ it('reports status through its own hooks, locally and on an SSH host (RemoteHooks.installCursorRemote)', () => {+ expect(hasHooks('cursor')).toBe(true)+ expect(hasHooksOverSsh('cursor')).toBe(true)+ })++ it('takes a permission mode and a model on its launch line', () => {+ expect(hasPermissionMode('cursor')).toBe(true)+ expect(canSwitchModel('cursor')).toBe(true)+ })++ it('does not claim the capabilities whose per-agent leaf is unwritten', () => {+ for (const can of [canRecur, canBranch]) {+ expect(can('cursor')).toBe(false)+ }+ expect(readsClaudeShapedTranscript('cursor')).toBe(false)+ })+})+describe('copy feedback', () => {it('stays quiet for claude, whose CLI announces its own copies', () => {// Claude Code captures the mouse and prints "copied N chars to tmux buffer · paste with@@ -461,6 +508,92 @@ describe('title read vs rename write', () => {})})+describe('cursor capabilities (transcript leaf)', () => {+ it("shows its conversation in ⌘M from its own SQLite store, never through claude's resolver", () => {+ expect(canChat('cursor')).toBe(true)+ expect(readsClaudeShapedTranscript('cursor')).toBe(false)+ })+ it('is local-only for the chat view: a remote node says "not supported yet"', () => {+ expect(chatReadsLocalOnly('cursor')).toBe(true)+ })+ it('joins context link, transfer-from and the title READ leg', () => {+ expect(canContextLink('cursor')).toBe(true)+ expect(canTransferFrom('cursor')).toBe(true)+ expect(canReadTitle('cursor')).toBe(true)+ })+})++/**+ * Cursor orchestration parity (docs/cursor-agent.md "Orchestration parity"), MEASURED on+ * cursor-agent 2026.10.01 in the interactive TUI.+ */+describe('cursor capabilities (orchestration)', () => {+ it('drives the canvas: ~/.claude/skills is listed by cursor, so membership is the whole wiring', () => {+ expect(canControlCanvas('cursor')).toBe(true)+ })+ it('shows subagent cards (start: parent Task preToolUse, end: parent stop)', () => {+ expect(canSubagent('cursor')).toBe(true)+ })+ it('renames: /rename lands in the store meta the READ leg reads, so read ⊇ write holds', () => {+ expect(canRename('cursor')).toBe(true)+ expect(canReadTitle('cursor')).toBe(true)+ })+ it('submits a one-way line with a SEPARATE Enter; claude and grok keep the one-shot paste', () => {+ expect(submitsSeparately('cursor')).toBe(true)+ for (const id of ['claude', 'grok', 'codex', 'gemini']) expect(submitsSeparately(id), id).toBe(false)+ })+ it('does NOT join RECURRING_CAPABLE: the loop skill was seen arming, its ticks were never measured', () => {+ expect(canRecur('cursor')).toBe(false)+ })+})++describe('cursor capabilities (context meter)', () => {+ it('joins USAGE_CAPABLE with the agent’s own store numbers', () => {+ expect(hasUsage('cursor')).toBe(true)+ })+ it('stays off claude’s transcript resolver: no find-bar index, no cold-resume, no cwd fallback', () => {+ // hasUsage also gates context.ensure and the find bar's index in older code; the split is+ // readsClaudeShapedTranscript, which must stay false or a cursor node is handed a stranger's claude session.+ expect(readsClaudeShapedTranscript('cursor')).toBe(false)+ expect(readsClaudeShapedTranscript('claude')).toBe(true)+ })+})++describe('cursor capabilities (session continuity)', () => {+ it('resumes with `--resume <id>` before the `agent` subcommand', () => {+ expect(canResume('cursor')).toBe(true)+ expect(resumeCommandWith('cursor-agent', 'cursor', 'abc-123')).toBe('cursor-agent --resume abc-123')+ expect(resumeCommandWith('cursor-agent', 'cursor', 'x; rm -rf ~')).toBeNull()+ })+ it('mints with no probe of its own (the flag is resume, a fresh uuid is adopted)', () => {+ expect(mintsSessionId('cursor')).toBe(true)+ expect(supportsSessionIdFlag('cursor', false, false)).toBe(true)+ })+ it('reports a session end (normalizeCursor maps sessionEnd, CURSOR_HOOK_EVENTS subscribes it)', () => {+ expect(reportsSessionEnd('cursor')).toBe(true)+ expect(CURSOR_HOOK_EVENTS).toContain('sessionEnd')+ })+})++/**+ * Cursor wave 2 (F2): NEEDS YOU from a pane read, the SSH hook installer, the lost-stop net.+ * No capability list gates the approval watch: it is the hook server's own seam+ * (core/agents/cursor-approval.ts) and only `agentId === 'cursor'` posts reach it.+ */+describe('cursor NEEDS YOU, SSH hooks and lost stop', () => {+ it('is no longer local-only: RemoteHooks installs into the host ~/.cursor/hooks.json', () => {+ expect(LOCAL_ONLY_HOOK_AGENTS as readonly string[]).not.toContain('cursor')+ expect(hasHooksOverSsh('cursor')).toBe(true)+ })++ it('the normalizer itself still never says blocked (the pane read adds it, not a hook)', () => {+ for (const hook_event_name of ['preToolUse', 'beforeShellExecution', 'beforeMCPExecution', 'notification']) {+ const ev = normalizeFor('cursor', { nodeId: 'n', agentId: 'cursor', payload: { hook_event_name, tool_use_id: 't' } })+ expect(ev?.state === 'blocked', hook_event_name).toBe(false)+ }+ })+})+describe('typed chat input (TYPED_INPUT_CAPABLE)', () => {it('types only for claude — M-Enter is a measured newline there and unmeasured anywhere else', () => {expect(typesChatInput('claude')).toBe(true)diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex b6327d351..79f54d3ab 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -12,6 +12,7 @@ export type BuiltinAgentId =| 'grok'| 'copilot'| 'antigravity'+ | 'cursor'// Open type — custom agents are any string ('custom:<uuid>'). Never restrict the set.export type AgentId = BuiltinAgentId | (string & {})@@ -89,7 +90,8 @@ export const BUILTIN_AGENT_IDS: readonly BuiltinAgentId[] = ['gemini','opencode','grok',- 'copilot'+ 'copilot',+ 'cursor']export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {@@ -171,6 +173,36 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {promptInjectionMode: 'flag-interactive',promptFlag: '--prompt-interactive',expectedProcess: 'agy'+ },+ cursor: {+ // Cursor Agent CLI. Measured on `cursor-agent` 2026.09.23-86fc751 (macOS).+ label: 'Cursor',+ // Cursor's own mark is monochrome, so there is no brand hue to borrow. The first pick, a neutral+ // grey (#6b7280), was OKLab 0.018 from Grok's #64748b: the two swatches looked identical in the+ // picker, sidebar, kanban and minimap (review 2026-10-03). This magenta is at least 0.12 OKLab+ // from every palette swatch (system, agent and FALLBACK_AGENT_COLOR; nearest: system red), and+ // about 4:1 against both the dark (#1e1e1e) and light (#fff) canvas as a dot or border. It is an+ // agent colour, so it never carries text (SYSTEM_NODE_COLORS owns those surfaces).+ // `node-colors.test.ts` pins the distance.+ color: '#d9468f',+ // Not `agent`: the CLI installs that alias too, and grok ships a binary of the same name.+ launchCmd: 'cursor-agent',+ // Usage is `agent [options] [command] [prompt...]`, so a one-word prompt collides with a+ // subcommand (`login`, `update`, `ls`, ...). Unlike grok, `--` does NOT help: measured,+ // `cursor-agent -- whoami` still runs `whoami`. The `agent` subcommand ("Start the Cursor+ // Agent") takes the prompt with no subcommands of its own: `cursor-agent agent whoami` opens+ // the TUI with "whoami" as the prompt. `stdin-after-start` is out: a first launch in a folder+ // shows a workspace-trust dialog that a typed prompt + Enter would answer.+ // MEASURED (2026.09.28): flags BEFORE `agent` reach the session. `agent` is a commander+ // subcommand with no options of its own; its action reads the ROOT program's options, and root+ // parses `--model` / `--force` / `--mode` wherever they sit (before or after `agent`, both+ // measured in the TUI). So the composers' flags-before-separator placement is correct.+ promptInjectionMode: 'argv',+ argvPromptSeparator: 'agent',+ // The wrapper script runs `exec -a "$0" node index.js`, so ps shows argv0 `cursor-agent`.+ expectedProcess: 'cursor-agent',+ // The two env overrides `cursor-agent --help` names for auth and endpoint.+ vanillaEnvPattern: '^CURSOR_API_(KEY|ENDPOINT)$'}}@@ -180,6 +212,7 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {// antigravity joined with ONLY this list: its normalizer (normalizeAntigravity) and its// installer are the leaves that exist. Every other list below is a separate leaf it does not have// yet — see the `antigravity capabilities` block in config.capabilities.test.ts for each reason.+// cursor joined the same way (normalizeCursor + hooks/cursor.ts); see docs/cursor-agent.md.export const AGENT_HOOK_TARGETS = ['claude','codex',@@ -187,7 +220,8 @@ export const AGENT_HOOK_TARGETS = ['opencode','grok','copilot',- 'antigravity'+ 'antigravity',+ 'cursor'] as const// antigravity: `agy --conversation=<id>` — the `=` spelling agy prints in its own exit hint// (`agy --conversation=%s`, 1.2.12 binary). The id is the hook payload's `conversationId`, recorded@@ -196,6 +230,11 @@ export const AGENT_HOOK_TARGETS = [// the history, never the launch. Without membership a cold restore (machine reboot) brought an agy// node back as a bare shell under an Antigravity badge (`canColdRestore` needs `canResume`).// UNVERIFIED on a device: that the hook's conversationId is the id `--conversation` accepts.+//+// cursor: `cursor-agent --resume <conversation_id>` (measured 2026.09.28, docs/cursor-agent.md). The+// flag is a root option with an OPTIONAL value, so it goes BEFORE the `agent` subcommand and its id+// must directly follow it. A dead id is the SAFE failure: cursor opens an EMPTY chat that ADOPTS the+// requested id (exit 0, no error), so a wrong id costs the history, never the launch.export const RESUMABLE_AGENTS = ['claude','codex',@@ -203,7 +242,8 @@ export const RESUMABLE_AGENTS = ['opencode','grok','copilot',- 'antigravity'+ 'antigravity',+ 'cursor'] as const// Agents whose session id we MINT at launch (`--session-id <uuid>`) instead of learning it only// from hook events. Each member must have a measured caller-chosen-id grammar below.@@ -221,7 +261,7 @@ export const RESUMABLE_AGENTS = [// clear/fork/compact), so hooks remain the only way to TRACK an id after launch. What minting// guarantees is that a node always has SOME resumable id, so the worst case degrades from "the// conversation is gone" to "continuity since the last /clear is gone".-export const SESSION_ID_CAPABLE = ['claude', 'copilot', 'grok'] as const+export const SESSION_ID_CAPABLE = ['claude', 'copilot', 'grok', 'cursor'] as const// Claude's flag is version-gated and comes from the Claude CLI probe. Copilot's installed 1.0.80// binary and current official reference accept `--session-id=<uuid>`, so it does not borrow an// unrelated Claude probe result. Custom agents resolve through their declared base harness.@@ -234,7 +274,15 @@ export const SESSION_ID_CAPABLE = ['claude', 'copilot', 'grok'] as const// LAUNCH ERROR and never a resume; `--session-id` combines with `--resume`/`--continue` only// alongside `--fork-session`; and `--resume` accepts a TITLE as well as an id, failing as ambiguous// on duplicates — which is why nothing in this codebase resumes grok by title.-export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot'] as const+//+// cursor mints with `--resume <uuid>` and NO probe of its own, unlike grok: the flag is the same one+// resume already depends on (a CLI without it could not resume either), and the behavior is not a+// flag a help probe could see. Measured 2026.09.28 with a paid TUI run: `cursor-agent --resume+// <fresh uuid> --model composer-2.5 --force agent '<prompt>'` answered, and every hook payload's+// `conversation_id` was that uuid; with no prompt the same line opens an empty chat under that id+// (no model call). An id that already exists simply resumes, so a taken id is never a launch error+// (grok's is). If an older CLI ignored the unknown id, the node degrades to hook-learned ids.+export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot', 'cursor'] as const// claude: Task/Agent tool via hooks (tool_use_id-keyed). codex: spawn_agent collaboration via its// native SubagentStart/SubagentStop hooks (agent_id-keyed), measured on codex-cli 0.146.0.// grok: its own native SubagentStart/SubagentStop, keyed by `subagentId` — measured on 1.0.13 by@@ -242,7 +290,10 @@ export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot'] as const// id from a type. It was assumed to key by `subagentType` (a type, so two children of one type// would collide); the payloads say otherwise, and `subagentId` is also the ONLY id the start and// the stop share — on the start `sessionId` is the PARENT's.-export const SUBAGENT_CAPABLE = ['claude', 'codex', 'grok'] as const+// cursor: its `subagentStart`/`subagentStop` hooks never fired (three measured runs, 2026.10.01),+// so the start is the parent's `Task` preToolUse (keyed by `tool_use_id`) and the end is the+// parent's `stop` (core/cursor-subagents.ts). docs/cursor-agent.md "Orchestration parity".+export const SUBAGENT_CAPABLE = ['claude', 'codex', 'grok', 'cursor'] as constexport const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cronexport const BRANCH_CAPABLE = ['claude'] as const// grok joins with NO installer of its own: it scans `~/.claude/skills` for Claude Code@@ -255,7 +306,11 @@ export const BRANCH_CAPABLE = ['claude'] as const// `~/.grok/config.toml`, and `GROK_CLAUDE_SKILLS_ENABLED=false`. Then the skill is undiscoverable// however this list reads, and the same `inspect` cell is what says so (`enabled:false`, a// non-default `source`) rather than leaving support to guess.-export const CONTEXT_LINK_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const+// cursor joins with NO installer: cursor-agent 2026.09.28 lists `~/.claude/skills/get-linked-context`+// in the `<agent_skills>` block of a real chat's own context (measured in its store.db), i.e. it reads+// `~/.claude/skills` like grok. Its transcript is a SQLite store read by `core/cursor-chat.ts`.+// UNVERIFIED: a user setting that switches that Claude-compat scan off.+export const CONTEXT_LINK_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'cursor'] as const// Agents whose per-node context meter we can fill. Each needs BOTH numbers: a used count and a// TRUSTWORTHY window.// - claude: used from its transcript's assistant usage, window INFERRED from the model family@@ -283,7 +338,13 @@ export const CONTEXT_LINK_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'g// `core/grok-signals.ts` reads exactly three of them and nothing else. If a future grok drops// `contextWindowTokens`, that reader returns null and the meter disappears — no inferred// denominator, because a percentage over a guessed window is a wrong number presented as a fact.-export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const+//+// Cursor joined in 2026-09 with the agent's own numbers, like grok: the store's root protobuf field 5+// (`token_details`: used_tokens, max_tokens), which matches the TUI's `/context` (`core/cursor-chat.ts`).+// It joins the meter ONLY: its ids are not in CLAUDE_TRANSCRIPT_READABLE, so the find bar's index and+// cold-resume stay off claude's cwd-fallback resolver, and `context.ensure` locates a cursor chat by id.+// Account plan limits (CLI `/usage`) are a different, credentialed number and are not read.+export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok', 'cursor'] as const// Agents whose structured transcript we can render as a chat panel (Cmd+M chat mode).//// SPLIT from CLAUDE_TRANSCRIPT_READABLE below on 2026-09-02, when grok joined. Until then this one@@ -306,7 +367,9 @@ export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const// (`readChatTranscript`). Like the others it is NOT in CLAUDE_TRANSCRIPT_READABLE below.// opencode joined 2026-09-28: it has no transcript file at all (SQLite since 1.18), so its chat is// read through `opencode export <id>` (core/opencode-chat.ts) and it stays out of the list below.-export const CHAT_CAPABLE = ['claude', 'grok', 'gemini', 'codex', 'copilot', 'opencode'] as const+// cursor joined with `core/cursor-chat.ts`: a read-only `node:sqlite` read of its chat store, located+// strictly by the whole-UUID chat id and routed before anything claude-shaped. Not in the list below.+export const CHAT_CAPABLE = ['claude', 'grok', 'gemini', 'codex', 'copilot', 'opencode', 'cursor'] as const// CHAT_CAPABLE agents whose reader has NO remote leg: a remote (SSH) node's session lives on its// host, so core answers `unreadable` before touching anything — and the local reader never sets that// flag (copilot maps a failed local read to not-found for exactly this reason). So an unreadable read@@ -315,7 +378,7 @@ export const CHAT_CAPABLE = ['claude', 'grok', 'gemini', 'codex', 'copilot', 'op// remote nodes are read on the host (`core/remote-grok-chat.ts`, `main/remote-codex-chat-page.ts`).// opencode has no remote leg either but is NOT here: its `unreadable` also means a failed LOCAL// `opencode export`, which Retry heals — the panel gives it its own copy (`exportError`) instead.-export const CHAT_LOCAL_ONLY = ['gemini', 'copilot'] as const+export const CHAT_LOCAL_ONLY = ['gemini', 'copilot', 'cursor'] as const// CHAT_CAPABLE agents whose chat-view prompts are TYPED as keystrokes instead of pasted// (core/typed-input.ts): a multi-line paste is recorded by Claude Code as <pasted_content>, content// its model is told may not be the user's own words. The typed path puts a line break in as tmux's@@ -347,7 +410,7 @@ export const SCREEN_DIALOG_READABLE = ['claude'] as const// a new user turn). Every other chat-capable agent is unmeasured and keeps "wait for the reply".export const INPUT_QUEUE_CAPABLE = ['claude'] as const// Agents whose native transcript we can read + render for cross-agent transfer.-export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const+export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini', 'grok', 'cursor'] as const// Agents whose hooks announce that a session ENDED — i.e. whose orderly `/exit` we will hear about.//// Derived by reading `normalize.ts`, not by intent: exactly four normalizers map an event to@@ -362,14 +425,31 @@ export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as//// Before adding an id: find its normalizer's `sessionPhase: 'end'` branch. If there isn't one, the// branch is the change — this list is a consequence of it, never a substitute for it.-export const SESSION_END_CAPABLE = ['claude', 'gemini', 'copilot', 'grok'] as const+//+// cursor: `sessionEnd` fires on an orderly `/quit` (measured 2026.09.28, `reason: "completed"`), and+// `CURSOR_HOOK_EVENTS` subscribes to it; both halves are needed, the list is inert without the event.+export const SESSION_END_CAPABLE = ['claude', 'gemini', 'copilot', 'grok', 'cursor'] as const// Agents that accept a node title being PUSHED back into the session — the write leg only. The// write is the same literal `/rename <name>` for both, which grok also accepts as `/title`.// The READ leg is TITLE_READ_CAPABLE below, which is a superset: an agent can name its own session// without offering any way to rename it (gemini). Read legs are per-agent (claude: the transcript// .jsonl; grok: its session summary.json; gemini: its update_topic tool call), routed once in// core/agent-session-name.ts.-export const RENAME_CAPABLE = ['claude', 'grok'] as const+// cursor: `/rename <name>` is a local TUI command (`agentStore.setMetadata("name")`) that lands in+// the store meta TITLE_READ_CAPABLE reads, MEASURED on 2026.10.01. It needs its Enter as a SEPARATE+// write (SEPARATE_SUBMIT_AGENTS), or the line sits unsubmitted in the composer.+export const RENAME_CAPABLE = ['claude', 'grok', 'cursor'] as const+// Agents whose TUI ignores an Enter that arrives in the SAME write as a bracketed paste: the text+// lands in the composer and is never submitted. MEASURED for cursor (2026.10.01): nodeterm's one-shot+// paste+Enter left `/rename x` unsubmitted; the same paste followed by a bare Enter, as a second+// tmux invocation, renamed the chat. `submitsSeparately` is asked by `PtyManager.sendText`, the one+// funnel every one-way write reaches.+export const SEPARATE_SUBMIT_AGENTS = ['cursor'] as const+// Agents that load nodeterm's `get-linked-context` skill from `~/.claude/skills`, so a context link,+// a note push or a verify brief can name the skill instead of spelling out the CLI. claude, and+// cursor (measured: it lists that skill in its own `<agent_skills>`, docs/cursor-agent.md). grok+// reads that root too, but its pickup of this skill is unverified, so it keeps the CLI wording.+export const LINKED_CONTEXT_SKILL_AGENTS = ['claude', 'cursor'] as const// Agents whose OWN session name we can READ and adopt into the node title.//// Separate from RENAME_CAPABLE because the two directions are separate facts, and gemini has only@@ -386,7 +466,9 @@ export const RENAME_CAPABLE = ['claude', 'grok'] as const// (SHARED_IDENTITY_CAPABLE below) a node owns a THREAD, and that thread carries a `Thread.name` we// can read over the server's own socket (core/codex-session-name.ts). There is still no measured// rename command, so it stays out of RENAME_CAPABLE — the read⊇write invariant holds either way.-export const TITLE_READ_CAPABLE = ['claude', 'codex', 'grok', 'gemini'] as const+// cursor: its `name` (AI-generated, or `/rename`) is in the chat store meta; the write leg joined+// RENAME_CAPABLE once `/rename` was measured to land there.+export const TITLE_READ_CAPABLE = ['claude', 'codex', 'grok', 'gemini', 'cursor'] as const// Agents whose canvas nodes share ONE managed CLI server per machine and keep a stable per-node// identity inside it, instead of each node owning a whole process tree.//@@ -410,7 +492,12 @@ export const SHARED_IDENTITY_CAPABLE = ['codex'] as const// RemoteHooks.installCanvasControl. Membership here is what sets NODETERM_CANVAS_CONTROL in the// session env (hook-server's buildPtyEnv, remoteHookEnvArgs), i.e. what makes the shim anything// other than a no-op.-export const CANVAS_CONTROL_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot'] as const+//+// cursor needs no installer either, by the same route: cursor-agent loads `~/.claude/skills` as+// third-party skills (gated by its `thirdPartyExtensibility` setting, default on in the CLI), and+// MEASURED on 2026.10.01 its interactive session listed `~/.claude/skills/manage-nodeterm-canvas`+// right after its own built-ins, ahead of the tail it truncates when the skill list is long.+export const CANVAS_CONTROL_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot', 'cursor'] as const// Agents whose TOOL shell on Windows is POSIX: Claude Code runs its Bash tool (and its hooks)// through Git Bash, so `sh "<shim>.sh"` works there exactly as on macOS/Linux. Every other agent// runs tools in PowerShell (codex, gemini, copilot — measured in their sources) or cmd.exe, where@@ -436,11 +523,23 @@ export const POSIX_TOOL_SHELL_ON_WINDOWS = ['claude'] as const// renderer/state/permissionMode.ts. grok has accepted every mode we emit since 1.0.0, its first// release, and gemini/codex accept theirs on the versions we measured, so none of them may inherit// a gate fed by a `claude --version` probe.-export const PERMISSION_MODE_CAPABLE = ['claude', 'grok', 'gemini', 'codex'] as const+//+// cursor emits `--auto-review` for `auto` (a server classifier auto-runs safe calls, claude's `auto`+// shape), `--mode plan` and `--force`; `manual` and `acceptEdits` emit no flag (its bare launch is+// `approvalMode: allowlist`). See CURSOR_MODES in approval-mode.ts. `auto` is the DEFAULT mode, which+// widened no existing node only because cursor shipped in the same change.+export const PERMISSION_MODE_CAPABLE = ['claude', 'grok', 'gemini', 'codex', 'cursor'] as const// Agents whose harness accepts a per-launch model override and whose gateway protocol we know how// to configure. Custom agents inherit this through `capabilityAgentId`, like every other harness// capability — the renderer never maintains its own Claude/Codex/Copilot allowlist.-export const MODEL_SWITCH_CAPABLE = ['claude', 'codex', 'copilot', 'grok'] as const+export const MODEL_SWITCH_CAPABLE = ['claude', 'codex', 'copilot', 'grok', 'cursor'] as const+// Members of MODEL_SWITCH_CAPABLE whose models are their OWN CLI's catalogue and can never be+// routed through the model gateway: grok (custom models live in ~/.grok/config.toml) and cursor+// (`cursor-agent models` lists ~250 account-scoped ids; the gateway's ids are not among them).+// Offering or defaulting a gateway id to one of these puts a `--model` on the line that names a+// model outside its own catalogue (what cursor does with an unknown id is UNMEASURED), so every place+// that hands out GATEWAY models asks `hasGatewayModels`, not `canSwitchModel`.+export const OWN_MODEL_CATALOGUE = ['grok', 'cursor'] as const// Agents whose own CLI already tells the user when it copies, so nodeterm must not say it again.// Claude Code captures the mouse itself and prints its own line — "copied N chars to tmux buffer ·// paste with prefix + ]" — which makes our copy pill a second message for one gesture. Membership@@ -576,11 +675,17 @@ export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURC* answer for codex and opencode is no, and callers must degrade rather than assume a crash. */export const reportsSessionEnd = (id: AgentId): boolean => includes(SESSION_END_CAPABLE, id)export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)+export const submitsSeparately = (id: AgentId): boolean => includes(SEPARATE_SUBMIT_AGENTS, id)+export const readsLinkedContextSkill = (id: AgentId): boolean => includes(LINKED_CONTEXT_SKILL_AGENTS, id)export const canReadTitle = (id: AgentId): boolean => includes(TITLE_READ_CAPABLE, id)export const canControlCanvas = (id: AgentId): boolean => includes(CANVAS_CONTROL_CAPABLE, id)export const usesPosixToolShellOnWindows = (id: AgentId): boolean => includes(POSIX_TOOL_SHELL_ON_WINDOWS, id)export const hasPermissionMode = (id: AgentId): boolean => includes(PERMISSION_MODE_CAPABLE, id)export const canSwitchModel = (id: AgentId): boolean => includes(MODEL_SWITCH_CAPABLE, id)+/** Can the model GATEWAY's catalogue (its discovered ids, its default model) apply to this agent?+ * `canSwitchModel` minus the agents that carry their own catalogue (OWN_MODEL_CATALOGUE). */+export const hasGatewayModels = (id: AgentId): boolean =>+ canSwitchModel(id) && !includes(OWN_MODEL_CATALOGUE, id)export const hasSharedIdentity = (id: AgentId): boolean => includes(SHARED_IDENTITY_CAPABLE, id)/**@@ -656,9 +761,12 @@ export function withSessionId(cmd: string, id: AgentId, sessionId: string): striif (!mintsSessionId(id)) return cmdconst sid = sessionId.trim()if (!sid || !SAFE_SESSION_ID.test(sid)) return cmd- return capabilityAgentId(id) === 'copilot'- ? `${cmd} --session-id=${sid}`- : `${cmd} --session-id ${sid}`+ const base = capabilityAgentId(id)+ if (base === 'copilot') return `${cmd} --session-id=${sid}`+ // cursor has no session-id flag: `--resume <unknown uuid>` opens an empty chat that adopts the id+ // (measured, docs/cursor-agent.md). A root option with an optional value, so it sits before `agent`.+ if (base === 'cursor') return `${cmd} --resume ${sid}`+ return `${cmd} --session-id ${sid}`}/**@@ -739,6 +847,7 @@ export function resumeCommandWith(case 'claude':case 'gemini':case 'grok':+ case 'cursor':return `${launchCmd} --resume ${sid}`default:return nulldiff --git a/src/shared/agents/cursor-launch.test.ts b/src/shared/agents/cursor-launch.test.tsnew file mode 100644index 000000000..5b30a1df6--- /dev/null+++ b/src/shared/agents/cursor-launch.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest'+import { AGENT_BINARIES } from './pane-owner-predicate'+import { AGENT_CONFIG, BUILTIN_AGENT_IDS } from './config'+import { assembleLaunchCommand, assembleResumeCommand } from './launch'++// cursor-agent's usage is `agent [options] [command] [prompt...]`, and measured on 2026.09.23 its+// parser ignores `--` for subcommand dispatch (`cursor-agent -- whoami` still runs whoami). The+// prompt therefore rides behind the `agent` subcommand, which has no subcommands of its own.+describe('cursor launch line', () => {+ const launch = (initialPrompt?: string) =>+ assembleLaunchCommand({ agentId: 'cursor', initialPrompt }, {}).command++ it('is offered as a builtin that runs cursor-agent, never the ambiguous `agent` alias', () => {+ expect(BUILTIN_AGENT_IDS).toContain('cursor')+ expect(AGENT_CONFIG.cursor.launchCmd).toBe('cursor-agent')+ expect(AGENT_BINARIES.cursor).toEqual(['cursor-agent'])+ })++ it('puts a one-word prompt that names a subcommand behind `agent`', () => {+ expect(launch('login')).toBe("cursor-agent agent 'login'")+ expect(launch('update')).toBe("cursor-agent agent 'update'")+ })++ it('launches bare with no prompt', () => {+ expect(launch()).toBe('cursor-agent')+ })++ // MEASURED (cursor-agent 2026.09.28): root flags reach the session from BEFORE `agent` (real run:+ // `--model composer-2.5 --force agent '<prompt>'` ran the shell command unprompted, footer "Run+ // Everything"). So the composed line is `cursor-agent [flags] agent '<prompt>'`, never flags last.+ it('puts model and permission flags BEFORE the `agent` separator', () => {+ const line = (inputs: object): string =>+ assembleLaunchCommand({ agentId: 'cursor', initialPrompt: 'hi', ...inputs }, {}).command+ expect(line({ permissionMode: 'bypassPermissions' })).toBe("cursor-agent --force agent 'hi'")+ expect(line({ permissionMode: 'plan', model: 'composer-2.5' })).toBe(+ "cursor-agent --mode plan --model 'composer-2.5' agent 'hi'"+ )+ // The default mode is Auto-review (a classifier), never Run Everything.+ expect(line({ permissionMode: 'auto' })).toBe("cursor-agent --auto-review agent 'hi'")+ expect(line({ permissionMode: 'manual' })).toBe("cursor-agent agent 'hi'")+ expect(+ assembleLaunchCommand({ agentId: 'cursor', permissionMode: 'plan', model: 'composer-2.5' }, {})+ .command+ ).toBe("cursor-agent --mode plan --model 'composer-2.5'")+ })++ it('relaunches bare, flagged, when there is no session id', () => {+ expect(+ assembleResumeCommand({ agentId: 'cursor', permissionMode: 'bypassPermissions' }, {}).command+ ).toBe('cursor-agent --force')+ })++ // MEASURED (2026.09.28): `--resume [chatId]` has an OPTIONAL value, so the id must follow it+ // directly and `agent` (the prompt subcommand) comes after; flags may sit on either side.+ const ID = '11111111-2222-4333-8444-555555555555'+ it('resumes by id, flags after it, with the model switch on the same line', () => {+ expect(assembleResumeCommand({ agentId: 'cursor', sessionId: ID }, {}).command).toBe(+ `cursor-agent --resume ${ID}`+ )+ expect(+ assembleResumeCommand(+ { agentId: 'cursor', sessionId: ID, permissionMode: 'plan', model: 'composer-2.5' },+ {}+ ).command+ ).toBe(`cursor-agent --resume ${ID} --mode plan --model 'composer-2.5'`)+ expect(assembleResumeCommand({ agentId: 'cursor', sessionId: 'a;b' }, {}).command).toBe('cursor-agent')+ })++ it('mints a first launch as `--resume <fresh uuid>` BEFORE `agent`, prompt last', () => {+ const line = (inputs: object): string =>+ assembleLaunchCommand({ agentId: 'cursor', sessionId: ID, sessionIdFlagSupported: true, ...inputs }, {}).command+ // The callers' gate is `supportsSessionIdFlag('cursor', ...)`, which is true with no probe (config test).+ expect(line({ initialPrompt: 'hi' })).toBe(`cursor-agent --resume ${ID} agent 'hi'`)+ expect(line({})).toBe(`cursor-agent --resume ${ID}`)+ expect(line({ initialPrompt: 'hi', permissionMode: 'bypassPermissions' })).toBe(+ `cursor-agent --force --resume ${ID} agent 'hi'`+ )+ })+})diff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.tsindex c74a0b6f4..c3fdc9d31 100644--- a/src/shared/agents/hook-events.ts+++ b/src/shared/agents/hook-events.ts@@ -116,6 +116,37 @@ export const COPILOT_HOOK_EVENTS = ['SessionEnd'] as const+/**+ * Cursor Agent CLI hook events (→ normalizeCursor), written into `~/.cursor/hooks.json` as flat+ * `{command}` entries. Cursor's names are camelCase, and it publishes 21 of them+ * (`cursor-agent` 2026.09.28 bundle); these are the five that move the badge, plus `sessionEnd`.+ *+ * Left out on purpose:+ * - `sessionStart`: does not fire on `--resume` (measured), so it cannot be relied on. Measured+ * again on 2026.10.01: a plain `cursor-agent` fires it before any prompt (with+ * `conversation_id`), but nodeterm launches every node as `--resume <minted id>`, which fired+ * nothing until `/quit` (two runs). Subscribing it would not give a fresh node a status.+ * (`sessionEnd` IS subscribed: interactive `/quit` fires it, measured; it puts cursor in+ * `SESSION_END_CAPABLE`. Dropping it here would make every quit read as a DROPPED crash.)+ * - `afterAgentResponse`, `afterAgentThought`, `beforeShellExecution`, `afterShellExecution`,+ * `afterFileEdit`, `beforeReadFile`, `beforeMCPExecution`, `afterMCPExecution`: three headless+ * runs with all of these subscribed (and a claude-format project file beside them) lost the+ * agent stream after the first reply ("Connection lost… WritableIterable is closed"), while a+ * run with only the five below plus sessionStart/sessionEnd finished clean. Which of the+ * differences broke it is unknown (docs/cursor-agent.md §3), so none is added without a run+ * that isolates it.+ * - `preToolUse` is a GATE (Cursor reads its stdout as a permission decision), so our command must+ * stay silent with exit 0, see `buildManagedHookCommand`'s `silent`.+ */+export const CURSOR_HOOK_EVENTS = [+ 'beforeSubmitPrompt',+ 'preToolUse',+ 'postToolUse',+ 'postToolUseFailure',+ 'stop',+ 'sessionEnd'+] as const+/*** Antigravity CLI (`agy`) hook events (→ normalizeAntigravity), subscribed in* `~/.gemini/config/hooks.json` under our own bundle key (core/agents/hooks/antigravity.ts).diff --git a/src/shared/agents/model-gateway.test.ts b/src/shared/agents/model-gateway.test.tsindex d32f6405d..dd4d43c81 100644--- a/src/shared/agents/model-gateway.test.ts+++ b/src/shared/agents/model-gateway.test.ts@@ -3,6 +3,7 @@ import { readFileSync } from 'fs'import path from 'path'import {grokModelsFrom,+ cursorModelsFrom,normalizedAgentModel,MODEL_GATEWAY_ENV_KEYS,MODEL_GATEWAY_SECRET_REF,@@ -347,6 +348,26 @@ describe('modelsForAgent — grok is offered its OWN models, never the gateway c})})+describe('modelsForAgent: cursor never gets the gateway catalogue either', () => {+ it('returns nothing for cursor, whatever else is passed', () => {+ const GATEWAY = [{ id: 'anthropic/claude-x' }]+ expect(modelsForAgent(GATEWAY, 'cursor')).toEqual([])+ // A grok catalogue is never handed over either; only cursor's own list is.+ expect(modelsForAgent(GATEWAY, 'cursor', [{ id: 'grok-4.6' }])).toEqual([])+ expect(modelsForAgent(GATEWAY, 'cursor', [], [{ id: 'auto', name: 'Auto' }])).toEqual([+ { id: 'auto', name: 'Auto' }+ ])+ })++ it('still emits a flag for an explicit model (canvas-control --model), and no gateway env', () => {+ expect(withAgentModel('cursor-agent', 'cursor', 'composer-2.5')).toBe(+ "cursor-agent --model 'composer-2.5'"+ )+ const settings = { baseUrl: 'https://gw.example', apiKey: 'k' }+ expect(modelGatewayEnv(settings as never, 'cursor', 'composer-2.5', {}, 'secret')).toEqual({})+ })+})+describe('grok takes its model as a FLAG, and needs no gateway environment', () => {it('appends --model before anything else touches the line', () => {expect(withAgentModel('grok', 'grok', 'grok-4.5')).toBe("grok --model 'grok-4.5'")@@ -367,3 +388,27 @@ describe('grok takes its model as a FLAG, and needs no gateway environment', ())})})++describe('cursorModelsFrom', () => {+ // Shape measured on cursor-agent 2026.09.28; the zero-width spaces are in the real output.+ const OUT =+ 'Available models\n\nauto - Auto (default)\ngpt-5.3-codex-low - Codex 5.3 Low\n' ++ 'grok-4.7-low-fast - Grok 4.7 Low Fast\u200b\u200b\n\n' ++ "Tip: use --model <id> (or /model <id> in interactive mode) to switch. e.g. --model 'claude-opus-4-8[context=1m]'.\n"++ it('reads ids and labels only, stripping zero-width spaces and the header/tip prose', () => {+ expect(cursorModelsFrom(OUT)).toEqual([+ { id: 'auto', name: 'Auto (default)' },+ { id: 'gpt-5.3-codex-low', name: 'Codex 5.3 Low' },+ { id: 'grok-4.7-low-fast', name: 'Grok 4.7 Low Fast' }+ ])+ })+ it('fails open to [] on nothing, junk, or an unsafe id', () => {+ expect(cursorModelsFrom(null)).toEqual([])+ expect(cursorModelsFrom('Error: not logged in')).toEqual([])+ expect(cursorModelsFrom('x;rm - evil')).toEqual([])+ })+ it('keeps the first of a duplicated id', () => {+ expect(cursorModelsFrom('a - One\na - Two')).toEqual([{ id: 'a', name: 'One' }])+ })+})diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.tsindex 76d01dcf2..ce66f2c4f 100644--- a/src/shared/agents/model-gateway.ts+++ b/src/shared/agents/model-gateway.ts@@ -1,4 +1,4 @@-import { canSwitchModel, capabilityAgentId, type AgentId } from './config'+import { canSwitchModel, capabilityAgentId, hasGatewayModels, type AgentId } from './config'import { shellSingleQuote } from '../shell-quote'import { expandEnvVars } from './expansion'@@ -190,7 +190,8 @@ export function parseGatewayModels(payload: unknown): GatewayModel[] {export function modelsForAgent(models: GatewayModel[],agentId: AgentId,- grokModels: readonly GatewayModel[] = []+ grokModels: readonly GatewayModel[] = [],+ cursorModels: readonly GatewayModel[] = []): GatewayModel[] {if (!canSwitchModel(agentId)) return []// grok is offered ITS OWN models, never the gateway's, and this is a correctness rule rather than@@ -199,6 +200,10 @@ export function modelsForAgent(// gateway catalogue would put ids on the menu that its CLI rejects at launch: a picker that looks// like it worked and kills the node.if (capabilityAgentId(agentId) === 'grok') return [...grokModels]+ // cursor: same rule. Its list is `cursor-agent models` (account-scoped, network-backed, ~250 ids);+ // the gateway's ids are not among them, so it is offered only its own, [] when the probe failed.+ if (capabilityAgentId(agentId) === 'cursor') return [...cursorModels]+ if (!hasGatewayModels(agentId)) return []return models}@@ -241,6 +246,33 @@ export function grokModelsFrom(stdout: string | null | undefined): GatewayModel[return [...byId.values()]}+/**+ * Parse `cursor-agent models`. MEASURED (2026.09.28, 246 lines, all matching):+ *+ * Available models+ *+ * auto - Auto (default)+ * gpt-5.3-codex-low - Codex 5.3 Low+ * grok-4.7-low-fast - Grok 4.7 Low Fast<U+200B><U+200B>+ *+ * Tip: use --model <id> ...+ *+ * Only `<id> - <label>` lines are read: the id is a bare token from the charset every command-line+ * id already uses, the label is the rest with zero-width spaces stripped and whitespace collapsed.+ * The header and the trailing `Tip:` prose never match (`Tip:` has no ` - ` after its first word).+ * The list is network-backed and account-scoped, so anything unparseable is an EMPTY list, which+ * the UI reads as "no model switching".+ */+export function cursorModelsFrom(stdout: string | null | undefined): GatewayModel[] {+ const byId = new Map<string, GatewayModel>()+ for (const raw of (stdout ?? '').split('\n')) {+ const m = /^([A-Za-z0-9][A-Za-z0-9._/-]*) - (\S.*)$/.exec(raw.replace(/[\u200b-\u200d\ufeff]/g, '').trimEnd())+ if (!m || byId.has(m[1])) continue+ byId.set(m[1], { id: m[1], name: m[2].replace(/\s+/g, ' ').trim() })+ }+ return [...byId.values()]+}+/*** Environment applied to a terminal session before custom-agent env (custom values still win).* Claude/Codex model selection stays a quoted CLI flag. Copilot's BYOK protocol instead carriesdiff --git a/src/shared/agents/normalize.cursor.test.ts b/src/shared/agents/normalize.cursor.test.tsnew file mode 100644index 000000000..dfbe76ea0--- /dev/null+++ b/src/shared/agents/normalize.cursor.test.ts@@ -0,0 +1,154 @@+// FIXTURE PROVENANCE: `__fixtures__/cursor/hook-payloads.json` was captured live from+// cursor-agent 2026.09.28-64d2043 (headless runs, macOS). It holds NO `beforeSubmitPrompt`, `stop`+// or `postToolUseFailure`: headless runs never fired the first two. Those three cases below use+// payloads built from the bundle's proto, and say so: they pin OUR reading, not Cursor's wire.+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import path from 'path'+import { normalizeClaude, normalizeCursor, normalizeFor, type RawHookEnvelope } from './normalize'++const fixture = JSON.parse(+ readFileSync(path.join(__dirname, '__fixtures__/cursor/hook-payloads.json'), 'utf8')+) as { events: Record<string, unknown>[] }++const pick = (name: string, ok?: (p: Record<string, unknown>) => boolean) => {+ const hit = fixture.events.filter((e) => e.hook_event_name === name && (ok ? ok(e) : true))+ if (hit.length !== 1) throw new Error(`fixture needs exactly one ${name}, got ${hit.length}`)+ return hit[0]+}+const env = (payload: Record<string, unknown>): RawHookEnvelope => ({ nodeId: 'n1', agentId: 'cursor', payload })+const CONV = '5a27c746-14a7-472d-8e3f-7f335a9df0db'++// Interactive TUI capture (2026.10.01): a parent turn with a Task, its child's tool events, stop.+const sub = JSON.parse(+ readFileSync(path.join(__dirname, '__fixtures__/cursor/subagent-payloads.json'), 'utf8')+) as { events: Record<string, unknown>[]; childStoreSubagentInfo: { toolCallId: string } }+const PARENT = '13993e38-911a-4558-8af0-73729368b113'+const subPick = (name: string, tool?: string) => {+ const hit = sub.events.filter((e) => e.hook_event_name === name && (tool ? e.tool_name === tool : true))+ if (hit.length !== 1) throw new Error(`subagent fixture needs exactly one ${name}/${tool}, got ${hit.length}`)+ return hit[0]+}++describe('normalizeCursor over captured cursor-agent payloads', () => {+ it('records conversation_id (== session_id on the wire) as the session id', () => {+ const e = subPick('beforeSubmitPrompt')+ expect(e.conversation_id).toBe(e.session_id)+ expect(normalizeCursor(env(e))?.sessionId).toBe(PARENT)+ // Either spelling alone is enough.+ expect(normalizeCursor(env({ hook_event_name: 'postToolUse', session_id: 's' }))?.sessionId).toBe('s')+ expect(normalizeCursor(env({ hook_event_name: 'postToolUse' }))?.sessionId).toBeUndefined()+ })++ it('maps a parent tool event to working (interactive: generation_id is the turn, not the chat)', () => {+ const e: Record<string, unknown> = { ...subPick('beforeSubmitPrompt'), hook_event_name: 'postToolUse', tool_name: 'Read' }+ expect(e.generation_id).not.toBe(e.conversation_id)+ expect(normalizeCursor(env(e))).toEqual({ nodeId: 'n1', agentId: 'cursor', sessionId: PARENT, kind: 'state', state: 'working' })+ })++ it('a HEADLESS (-p) capture has generation_id == conversation_id, so its tool events read as a child and drive nothing', () => {+ // Trade-off, documented in docs/cursor-agent.md: a headless run fires no beforeSubmitPrompt+ // or stop either, so its tool events only ever lit a RUNNING badge nothing could clear.+ const e = pick('preToolUse')+ expect(e.generation_id).toBe(e.conversation_id)+ expect(e.conversation_id).toBe(CONV)+ expect(normalizeCursor(env(e))).toBeNull()+ })++ it('ignores every captured event it does not subscribe to', () => {+ for (const n of ['sessionStart', 'beforeShellExecution', 'afterShellExecution', 'afterAgentThought'])+ for (const e of fixture.events.filter((x) => x.hook_event_name === n)) expect(normalizeCursor(env(e)), n).toBeNull()+ })++ it('maps sessionEnd to a session end, but not a background agent\'s', () => {+ for (const e of fixture.events.filter((x) => x.hook_event_name === 'sessionEnd')) {+ const n = normalizeCursor(env(e))+ expect(n?.kind).toBe('session')+ expect(n?.sessionPhase).toBe('end')+ expect(n?.sessionId).toBe(e.conversation_id)+ }+ expect(normalizeCursor(env({ hook_event_name: 'sessionEnd', conversation_id: 'c', is_background_agent: true }))).toBeNull()+ })++ it('matches the event name exactly, never as a substring', () => {+ for (const n of ['PreToolUse', 'pretooluse', 'preToolUseX', 'stopped', 'beforeSubmitPromptNow', '', 5])+ expect(normalizeCursor(env({ hook_event_name: n, conversation_id: 'c' })), String(n)).toBeNull()+ expect(normalizeCursor(env({}))).toBeNull()+ })++ it('a subagent tool call (parent_tool_call_id) drives nothing and records no session', () => {+ // UNMEASURED marker, from the bundle's PreToolUseRequestQuery field 10.+ const child = { hook_event_name: 'preToolUse', conversation_id: 'child', generation_id: 'turn', parent_tool_call_id: 't1' }+ expect(normalizeCursor(env(child))).toBeNull()+ expect(normalizeCursor(env({ ...child, parent_tool_call_id: undefined }))?.state).toBe('working')+ })++ it('MEASURED child tool events (own chat id as conversation AND generation id) drive nothing', () => {+ const pre = subPick('preToolUse', 'Read')+ const post = subPick('postToolUse', 'Read')+ for (const e of [pre, post]) {+ expect(e.conversation_id).not.toBe(PARENT)+ expect(e.parent_tool_call_id).toBeUndefined()+ expect(normalizeCursor(env(e))).toBeNull()+ }+ })++ it('the parent Task preToolUse starts a subagent card keyed by tool_use_id', () => {+ const task = subPick('preToolUse', 'Task')+ expect(normalizeCursor(env(task))).toEqual({+ nodeId: 'n1',+ agentId: 'cursor',+ sessionId: PARENT,+ kind: 'subagent-start',+ toolUseId: task.tool_use_id,+ subagentType: 'explore',+ taskLabel: (task.tool_input as { description: string }).description+ })+ // The child's store names the same id: the correlation exists on disk, never in a hook payload.+ expect(sub.childStoreSubagentInfo.toolCallId).toBe(task.tool_use_id)+ })++ it('a Task without a tool_use_id, or a postToolUse for Task, stays a plain working event', () => {+ const task = subPick('preToolUse', 'Task')+ expect(normalizeCursor(env({ ...task, tool_use_id: undefined }))?.kind).toBe('state')+ expect(normalizeCursor(env({ ...task, hook_event_name: 'postToolUse' }))?.state).toBe('working')+ })++ it('beforeSubmitPrompt starts a turn (built from the bundle schema, never captured)', () => {+ expect(normalizeCursor(env({ hook_event_name: 'beforeSubmitPrompt', conversation_id: 'c', prompt: 'x' }))).toEqual({+ nodeId: 'n1', agentId: 'cursor', sessionId: 'c', kind: 'state', state: 'working', newTurn: true+ })+ })++ it('stop ends the turn; aborted is interrupted, error is errored, anything else is plain done (never captured)', () => {+ const stop = (status?: unknown) => normalizeCursor(env({ hook_event_name: 'stop', conversation_id: 'c', status }))+ expect(stop('completed')).toEqual({ nodeId: 'n1', agentId: 'cursor', sessionId: 'c', kind: 'state', state: 'done' })+ expect(stop('aborted')?.interrupted).toBe(true)+ expect(stop('aborted')?.errored).toBeUndefined()+ expect(stop('error')?.errored).toBe(true)+ expect(stop('error')?.interrupted).toBeUndefined()+ expect(stop('surprise')).toMatchObject({ state: 'done' })+ expect(stop(undefined)).toMatchObject({ state: 'done' })+ })++ it('never claims NEEDS YOU (no measured signal exists)', () => {+ for (const e of fixture.events) {+ const r = normalizeCursor(env(e))+ expect(r?.state === 'waiting' || r?.state === 'blocked').toBe(false)+ }+ })++ it('is what the hook server dispatches for the cursor route', () => {+ expect(normalizeFor('cursor', env(subPick('stop')))?.state).toBe('done')+ })++ it('cross-fire is inert: nodeterm\'s claude hook also runs under cursor and finds nothing it knows', () => {+ // cursor-agent loads ~/.claude/settings.json hooks (measured: a matcher-bearing claude-format+ // project file fired on cursor's preToolUse/postToolUse/sessionStart), so /hook/claude receives+ // cursor's camelCase payloads for the same node. normalizeClaude compares exact PascalCase names.+ for (const e of fixture.events)+ expect(normalizeClaude({ nodeId: 'n1', agentId: 'claude', payload: e }), String(e.hook_event_name)).toBeNull()+ for (const n of ['beforeSubmitPrompt', 'stop', 'postToolUseFailure'])+ expect(normalizeClaude({ nodeId: 'n1', agentId: 'claude', payload: { hook_event_name: n, session_id: 'c' } }), n).toBeNull()+ })+})diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 2fc1b1632..aae47a11f 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -1094,6 +1094,128 @@ export function normalizeAntigravity(env: RawHookEnvelope): NormalizedAgentEventreturn null}+// Cursor Agent CLI payload. Every event carries the same envelope, MEASURED on cursor-agent+// 2026.09.28 (src/shared/agents/__fixtures__/cursor/hook-payloads.json): `conversation_id` (the+// chat id `cursor-agent --resume <id>` takes, verified), `session_id` (equal to it in every+// capture), `generation_id`, `model`, `hook_event_name` (camelCase, the ONLY spelling), `cursor_version`,+// `workspace_roots`, `user_email` and `transcript_path` (null until the first turn is written).+// `cwd` exists on tool events only and was "" for Shell, so nothing here reads it.+// `parent_tool_call_id` is the bundle's marker for a tool call made inside a subagent+// (hooks_pb PreToolUseRequestQuery field 10); never seen on the wire, see isCursorChildToolEvent.+// `status` on `stop`: `completed` was captured in the interactive TUI (subagent-payloads.json);+// `aborted` and `error` are from the bundle/docs, never captured.+interface CursorPayload {+ hook_event_name?: unknown+ conversation_id?: unknown+ session_id?: unknown+ generation_id?: unknown+ parent_tool_call_id?: unknown+ status?: unknown+ is_background_agent?: unknown+ tool_name?: unknown+ tool_use_id?: unknown+ tool_input?: unknown+}++/**+ * A cursor tool event made INSIDE a subagent. MEASURED on 2026.10.01 (interactive TUI, three+ * subagent runs, `__fixtures__/cursor/subagent-payloads.json`): a child's tool events carry the+ * CHILD's own chat id as `conversation_id` AND as `generation_id`, and no `parent_tool_call_id`.+ * A parent tool event carries its TURN's generation id, never the chat id (only `sessionStart`,+ * which is no tool event, has the two equal). `parent_tool_call_id` stays as the bundle's marker.+ * Wrong-guess cost: a parent tool event read as a child's is dropped; the badge still runs from+ * `beforeSubmitPrompt` and `stop`.+ */+export function isCursorChildToolEvent(payload: unknown): boolean {+ const p = (payload ?? {}) as CursorPayload+ if (typeof p.parent_tool_call_id === 'string' && p.parent_tool_call_id) return true+ return typeof p.conversation_id === 'string' && !!p.conversation_id && p.generation_id === p.conversation_id+}++/** A background agent's own lifecycle event (`is_background_agent: true`): never the node's. The+ * normalizer, the subagent tracker and the raw step all drop it with this one test. */+export function isCursorBackgroundEvent(payload: unknown): boolean {+ return ((payload ?? {}) as CursorPayload).is_background_agent === true+}++/**+ * A payload Cursor sent, whichever hook ran it. Cursor also runs nodeterm's `claude.sh` (Claude+ * settings import, docs/cursor-agent.md §5), so the claude raw listener sees Cursor's envelope too,+ * often a CHILD's. A real Claude payload carries neither key.+ */+export function isCursorPayload(payload: unknown): boolean {+ const p = (payload ?? {}) as Record<string, unknown>+ return p.cursor_version !== undefined || p.conversation_id !== undefined+}++/**+ * PURE. The event name is matched as a closed set of exact strings (rule 7); everything else,+ * including the ~16 events we do not subscribe, is null.+ *+ * - `beforeSubmitPrompt` → `working` + `newTurn` (`newTurn` retires `lastTurnError`, #521).+ * - `preToolUse` / `postToolUse` / `postToolUseFailure` → `working`. A subagent's tool call+ * (`isCursorChildToolEvent`) returns null: its `conversation_id` IS the child's (measured), and+ * child activity must not drive the parent or replace its recorded session id.+ * - the parent's `preToolUse` for tool `Task` → `subagent-start`, keyed by `tool_use_id`.+ * - `stop` → `done`; `interrupted` only for status `aborted`, `errored` only for `error`. Any+ * other status is a plain `done`, because `stop` ends the turn whatever it says.+ *+ * - `sessionEnd` → `session` phase `end` (SESSION_END_CAPABLE), unless `is_background_agent`.+ *+ * NEEDS YOU is deliberately absent HERE: the AskQuestion tool fires no tool hook and Cursor's own+ * approval prompt has none either (docs/cursor-agent.md §4). The hook server adds a `blocked` from+ * up to three pane reads of a still-pending tool call, and a `waiting` from the same reads of a quiet+ * turn that ends on the AskQuestion box, instead (core/agents/cursor-approval.ts).+ *+ * `sessionId` is `conversation_id`, falling back to `session_id`: the resume feature keys on it.+ */+export function normalizeCursor(env: RawHookEnvelope): NormalizedAgentEvent | null {+ const p = env.payload as CursorPayload+ const ev = typeof p.hook_event_name === 'string' ? p.hook_event_name : undefined+ const sessionId =+ typeof p.conversation_id === 'string' && p.conversation_id+ ? p.conversation_id+ : typeof p.session_id === 'string' && p.session_id+ ? p.session_id+ : undefined+ const base = { nodeId: env.nodeId, agentId: env.agentId, sessionId }++ if (ev === 'beforeSubmitPrompt') return { ...base, kind: 'state', state: 'working', newTurn: true }+ if (ev === 'preToolUse' || ev === 'postToolUse' || ev === 'postToolUseFailure') {+ if (isCursorChildToolEvent(p)) return null+ // The card's start. `subagentStart`/`subagentStop` never fired (three measured runs) and the+ // parent's `Task` gets a preToolUse but NO postToolUse, so the end is the parent's `stop`,+ // emitted by core/cursor-subagents.ts.+ if (ev === 'preToolUse' && p.tool_name === 'Task' && typeof p.tool_use_id === 'string' && p.tool_use_id) {+ const input = (p.tool_input ?? {}) as { subagent_type?: unknown; description?: unknown; prompt?: unknown }+ const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)+ return {+ ...base,+ kind: 'subagent-start',+ toolUseId: p.tool_use_id,+ subagentType: str(input.subagent_type),+ taskLabel: str(input.description) ?? str(input.prompt)+ }+ }+ return { ...base, kind: 'state', state: 'working' }+ }+ if (ev === 'stop') {+ return {+ ...base,+ kind: 'state',+ state: 'done',+ ...(p.status === 'aborted' ? { interrupted: true } : {}),+ ...(p.status === 'error' ? { errored: true } : {})+ }+ }+ // Orderly `/quit` (measured: reason "completed"). A background agent's own end is not this node's.+ if (ev === 'sessionEnd') {+ if (isCursorBackgroundEvent(p)) return null+ return { ...base, kind: 'session', sessionPhase: 'end' }+ }+ return null+}+export function normalizeFor(agentId: AgentId, env: RawHookEnvelope): NormalizedAgentEvent | null {if (agentId === 'claude') return normalizeClaude(env)if (agentId === 'codex') return normalizeCodex(env)@@ -1102,5 +1224,6 @@ export function normalizeFor(agentId: AgentId, env: RawHookEnvelope): Normalizedif (agentId === 'grok') return normalizeGrok(env)if (agentId === 'copilot') return normalizeCopilot(env)if (agentId === 'antigravity') return normalizeAntigravity(env)+ if (agentId === 'cursor') return normalizeCursor(env)return null}diff --git a/src/shared/agents/pane-owner-predicate.ts b/src/shared/agents/pane-owner-predicate.tsindex 28e0823f1..032e8f44a 100644--- a/src/shared/agents/pane-owner-predicate.ts+++ b/src/shared/agents/pane-owner-predicate.ts@@ -68,7 +68,8 @@ export const AGENT_BINARIES: Record<string, readonly string[]> = {gemini: ['gemini'],opencode: ['opencode'],grok: ['grok'],- antigravity: ['agy']+ antigravity: ['agy'],+ cursor: ['cursor-agent']}/**diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 68e9c93dd..86249e1a2 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -100,6 +100,7 @@ export const IPC = {claudeCliCaps: 'claude-cli:caps',grokCliCaps: 'grok-cli:caps',grokTakenSessionIds: 'grok-cli:taken-session-ids',+ cursorCliCaps: 'cursor-cli:caps',/** Can a node on this machine get a managed Codex identity? See core/codex-identity-caps.ts. */codexIdentityCaps: 'codex-identity:caps',codexCliCaps: 'codex-cli:caps',diff --git a/src/shared/keybindings.test.ts b/src/shared/keybindings.test.tsindex 075ddbcaa..96cdddbae 100644--- a/src/shared/keybindings.test.ts+++ b/src/shared/keybindings.test.ts@@ -131,6 +131,8 @@ describe('registry invariants', () => {scope: 'canvas', darwin: [], other: [] },{ id: 'node.newAgent.antigravity', title: 'New Antigravity node', group: 'Nodes',scope: 'canvas', darwin: [], other: [] },+ { id: 'node.newAgent.cursor', title: 'New Cursor node', group: 'Nodes', scope: 'canvas',+ darwin: [], other: [] },{ id: 'node.newSticky', title: 'New sticky note', group: 'Nodes', scope: 'canvas',darwin: [], other: [] },{ id: 'node.newBrowser', title: 'New browser node', group: 'Nodes', scope: 'canvas',@@ -235,7 +237,7 @@ describe('registry invariants', () => {'node.newDino','node.newFile']- expect(added).toHaveLength(12)+ expect(added).toHaveLength(13)for (const id of added) {const d = COMMANDS_BY_ID.get(id as CommandId)expect(d, id).toBeDefined()diff --git a/src/shared/keybindings.ts b/src/shared/keybindings.tsindex 94f030a5e..1f6110977 100644--- a/src/shared/keybindings.ts+++ b/src/shared/keybindings.ts@@ -80,6 +80,7 @@ export type CommandId =| 'node.newAgent.grok'| 'node.newAgent.copilot'| 'node.newAgent.antigravity'+ | 'node.newAgent.cursor'| 'node.newSticky'| 'node.newBrowser'| 'node.newWebView'@@ -207,6 +208,8 @@ export const COMMAND_DEFINITIONS: readonly CommandDefinition[] = [scope: 'canvas', defaultBindings: both() },{ id: 'node.newAgent.antigravity', title: `New ${AGENT_CONFIG.antigravity.label} node`,group: 'Nodes', scope: 'canvas', defaultBindings: both() },+ { id: 'node.newAgent.cursor', title: `New ${AGENT_CONFIG.cursor.label} node`, group: 'Nodes',+ scope: 'canvas', defaultBindings: both() },{ id: 'node.newSticky', title: 'New sticky note', group: 'Nodes', scope: 'canvas',defaultBindings: both() },{ id: 'node.newBrowser', title: 'New browser node', group: 'Nodes', scope: 'canvas',diff --git a/src/shared/node-colors.test.ts b/src/shared/node-colors.test.tsindex f7ec0e19a..0a4d17dbf 100644--- a/src/shared/node-colors.test.ts+++ b/src/shared/node-colors.test.ts@@ -190,3 +190,48 @@ describe('the narrower system boundary', () => {}})})++/**+ * A node's agent colour is its only identity on the dot, border, sidebar square and minimap, so two+ * agent swatches that look the same defeat it. Cursor shipped at OKLab 0.018 from Grok (review+ * 2026-10-03). 0.06 is about three just-noticeable differences.+ */+describe('agent swatches are told apart', () => {+ // Local copy of renderer/terminal/glass-cell-backgrounds.ts `oklab` (the shared tsconfig cannot+ // import renderer files). sRGB hex -> OKLab, Ottosson's matrices.+ const lab = (hex: string): number[] => {+ const [R, G, B] = [1, 3, 5].map((i) => {+ const c = parseInt(hex.slice(i, i + 2), 16) / 255+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)+ })+ const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B)+ const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B)+ const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B)+ return [+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s+ ]+ }+ const dist = (a: string, b: string) => Math.hypot(...lab(a).map((v, i) => v - lab(b)[i]))+ // Upstream pair that predates this pin (0.054): two teal-greens. Listed, not loosened, so a new+ // agent cannot hide behind it.+ const KNOWN_CLOSE = new Set(['#10a37f|#00a3a3'])++ it('every pair of agent swatches is at least 0.06 OKLab apart', () => {+ const colors = AGENT_NODE_COLOR_SWATCHES.map((s) => s.value)+ for (let i = 0; i < colors.length; i++)+ for (let j = i + 1; j < colors.length; j++) {+ const pair = `${colors[i]}|${colors[j]}`+ if (KNOWN_CLOSE.has(pair)) continue+ expect(dist(colors[i], colors[j]), pair).toBeGreaterThanOrEqual(0.06)+ }+ })++ it('cursor is at least 0.08 from every swatch in the palette, system ones included', () => {+ for (const c of NODE_COLORS) {+ if (c === AGENT_CONFIG.cursor.color) continue+ expect(dist(AGENT_CONFIG.cursor.color, c), c).toBeGreaterThanOrEqual(0.08)+ }+ })+})diff --git a/src/shared/types.ts b/src/shared/types.tsindex e7a440d1a..582f0e0f2 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3799,6 +3799,19 @@ export interface GrokCliCaps {/** Unprobed grok ⇒ omit the flag, offer no models ⇒ today's command line, byte-identical. */export const UNKNOWN_GROK_CLI_CAPS: GrokCliCaps = { sessionIdFlag: false, models: [] }+export interface CursorCliCaps {+ /** `cursor-agent models`: id + label, the account's own catalogue. [] when it cannot be read. */+ models: { id: string; name?: string }[]+}++/** Unprobed cursor ⇒ no models ⇒ no model switching (the pre-feature behaviour). */+export const UNKNOWN_CURSOR_CLI_CAPS: CursorCliCaps = { models: [] }++export interface CursorApi {+ /** Never rejects; an unprobed or offline CLI resolves to the empty catalogue. */+ cliCaps(): Promise<CursorCliCaps>+}+export interface GrokApi {/** Capabilities of the local grok CLI (memoized in the shell; safe to call repeatedly).* Never rejects — an unprobed CLI resolves to the fail-open caps. */@@ -4453,6 +4466,7 @@ export interface NodeTerminalApi {codex: CodexApiclaude: ClaudeApigrok: GrokApi+ cursor: CursorApi/** Custom-agent launch/preview (env-var expansion + command assembly). */agent: AgentApichat: ChatApidiff --git a/src/shared/usage-limits.test.ts b/src/shared/usage-limits.test.tsindex ba9d90cdc..2db0a3e6c 100644--- a/src/shared/usage-limits.test.ts+++ b/src/shared/usage-limits.test.ts@@ -7,7 +7,9 @@ import {limitKey,enabledProviders,hasAnyUsage,- providerLabel+ providerLabel,+ providerPillSegments,+ USAGE_PROVIDER_IDS} from './usage-limits'import type { ProviderUsage, RemoteAccountUsage, UsageLimit } from './types'@@ -186,3 +188,31 @@ describe('providerLabel', () => {expect(providerLabel('whatever-next')).toBe('whatever-next')})})++describe('USAGE_PROVIDER_IDS', () => {+ it('lists cursor, so it gets a Settings toggle and is shown by default', () => {+ expect(USAGE_PROVIDER_IDS).toContain('cursor')+ expect(providerLabel('cursor', 'Cursor')).toBe('Cursor')+ })+})++describe('providerPillSegments', () => {+ const row = (provider: string, limits: UsageLimit[]): ProviderUsage => ({+ provider, limits, account: null, updatedAt: 0, status: 'ok'+ })++ it('keeps every other provider on its single worst limit, named by the provider', () => {+ const p = row('grok', [limit({ usedPercent: 10 }), limit({ kind: 'weekly_all', usedPercent: 60 })])+ expect(providerPillSegments(p, 'Grok')).toEqual([{ limit: p.limits[1], label: 'Grok' }])+ expect(providerPillSegments(row('kimi', []), 'Kimi')).toEqual([])+ })++ it('shows all three Cursor buckets: total by provider name, the rest by lower-cased bucket', () => {+ const p = row('cursor', [+ limit({ kind: 'monthly', usedPercent: 35 }),+ limit({ kind: 'monthly_scoped', scopeLabel: 'Auto', usedPercent: 33 }),+ limit({ kind: 'monthly_scoped', scopeLabel: 'API', usedPercent: 100 })+ ])+ expect(providerPillSegments(p, 'Cursor').map((s) => s.label)).toEqual(['Cursor', 'auto', 'api'])+ })+})diff --git a/src/shared/usage-limits.ts b/src/shared/usage-limits.tsindex 0cbf2313e..e4469a6ce 100644--- a/src/shared/usage-limits.ts+++ b/src/shared/usage-limits.ts@@ -55,6 +55,27 @@ export function limitKey(limit: UsageLimit): string {return `${limit.kind}:${limit.scopeLabel ?? ''}`}+/**+ * What one provider puts in the collapsed pill: each limit to show and its pill label. Most+ * providers show only their worst limit, named by the provider ("37% Grok"). Cursor shows all+ * three buckets, because its API bucket can sit at 100% for most of a cycle while the plan is far+ * from spent: the total is named by the provider, the scoped buckets by their own lower-cased+ * name ("35% Cursor · 33% auto · 100% api").+ */+export function providerPillSegments(+ p: ProviderUsage,+ providerName: string+): { limit: UsageLimit; label: string }[] {+ if (p.provider === 'cursor') {+ return p.limits.map((limit) => ({+ limit,+ label: limit.scopeLabel ? limit.scopeLabel.toLowerCase() : providerName+ }))+ }+ const worst = primaryLimit(p.limits)+ return worst ? [{ limit: worst, label: providerName }] : []+}+/*** The providers the user has actually enabled: signed in AND with something to report. Anything* else is noise in the pill for someone who has never used that service.@@ -101,6 +122,7 @@ export const USAGE_PROVIDER_IDS = ['claude','claude-remote','codex',+ 'cursor','gemini','grok','kimi',