feat(cursor): first-class Cursor CLI agent status via hooks.json (#1108)
* feat(cursor): first-class Cursor CLI agent status via ~/.cursor/hooks.json Give cursor-agent the same hook-driven status pipeline Claude/Codex/Gemini/ OpenCode already use so working/done/permission transitions show the proper sidebar spinner instead of falling back to title heuristics — cursor-agent only sets its OSC title to the literal string "Cursor Agent" during a turn, so title-based detection cannot see working→done transitions on its own. - New CursorHookService installs a managed shell script and registers it under ~/.cursor/hooks.json for beforeSubmitPrompt, preToolUse, postToolUse, postToolUseFailure, beforeShellExecution, beforeMCPExecution, stop, and afterAgentResponse (the subset that marks turn boundaries and surfaces in-flight tool context). - AgentHookServer gains a /hook/cursor route and a normalizeCursorEvent mapping the camelCase cursor events to working/done/waiting, with tool previews for preToolUse/shell/MCP and lastAssistantMessage from afterAgentResponse. stop with status != "completed" surfaces as interrupted (matches Claude's is_interrupt behavior). - cursorHookService joins the startup install loop alongside Claude/Codex/ Gemini, and the IPC status handler is exposed via preload. - 'cursor' added to WellKnownAgentType and to the renderer's WELL_KNOWN_LABELS so the dashboard prints "Cursor" rather than the raw 'cursor' id. Verified end-to-end against a real cursor-agent 2026.04.17-787b533 binary: a mock hook receiver pointed at by ~/.cursor/hooks.json observes beforeSubmitPrompt → stop for a live turn. Co-authored-by: Orca <help@stably.ai> * feat(cursor): wire hook events into sidebar spinner + unread pipeline The initial hook wiring landed behind AGENT_DASHBOARD_ENABLED, which is still false. That meant cursor-agent panes lit up no spinner and no unread indicator — cursor's native OSC title stays literally "Cursor Agent" across a turn, so title-based detection cannot transition. Plumb cursor's hook stream into the existing, shipped title-tracker pipeline (the one Claude/Codex/Pi drive working/idle/unread off) by synthesizing OSC title sequences in the main-process hook listener: - `working` → `\x1b]0;⠋ Cursor Agent\x07` (braille prefix → working) - `waiting` → `\x1b]0;Cursor - action required\x07\x07` - `done` → `\x1b]0;Cursor ready\x07\x07` The two trailing BELs on done/waiting are load-bearing: the unread badge keys off BEL (0x07 outside any OSC), and cursor-agent emits none on its own. The first BEL is consumed as the OSC terminator; the second fires the bell detector. Also treats the bare native "Cursor Agent" title as a no-op in `detectAgentStatusFromTitle` so cursor's own per-turn re-emissions cannot stomp our synthesized working state back to idle. `isClaudeAgent` excludes cursor-bearing braille titles so the Claude prompt-cache timer doesn't fire for cursor panes. Scope: the hook server + cursor install run unconditionally now, but Claude/Codex/Gemini installs stay gated behind AGENT_DASHBOARD_ENABLED, so only cursor events flow through the pipeline. No dashboard surface is turned on. Verified end-to-end in Electron (dev build): launched cursor-agent via the Cursor menu item, submitted three prompts (including a tool-use turn reading package.json). Observed tab title flip to "Cursor ready" on done, and the tab + worktree both transitioned to unread (unreadTerminalTabs[tabId]=true, worktree.isUnread=true). Parallel Claude Code pane untouched. Co-authored-by: Orca <help@stably.ai> * fix(cursor): animate spinner frames + filter bare native title so the spinner doesn't go solid mid-turn cursor-agent re-emits its bare "Cursor Agent" OSC title on every internal redraw, which was stomping the single synthesized "⠋ Cursor Agent" frame in runtimePaneTitlesByTabId within milliseconds and flipping the sidebar dot back to solid. Two-part fix: - Main: drive an 80ms Pi-style braille spinner from the cursor hook channel, keyed by paneKey, torn down on pty exit via a new registerPaneKeyTeardownListener hook in ipc/pty. - Renderer: drop bare "Cursor Agent" titles in pty-transport so cursor's native re-emissions cannot overwrite the synthesized working/idle titles. Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -704,3 +704,128 @@ describe('OpenCode hook normalization', () => {
|
||||
expect(done?.payload.lastAssistantMessage).toBe('hello back')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cursor hook normalization', () => {
|
||||
it('beforeSubmitPrompt maps to working and captures the prompt', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'beforeSubmitPrompt', prompt: 'add a README' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('working')
|
||||
expect(result?.payload.agentType).toBe('cursor')
|
||||
expect(result?.payload.prompt).toBe('add a README')
|
||||
})
|
||||
|
||||
it('stop maps to done', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'stop', status: 'completed' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('done')
|
||||
expect(result?.payload.agentType).toBe('cursor')
|
||||
expect(result?.payload.interrupted).toBeUndefined()
|
||||
})
|
||||
|
||||
it('stop with non-completed status marks the turn interrupted', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'stop', status: 'cancelled' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('done')
|
||||
expect(result?.payload.interrupted).toBe(true)
|
||||
})
|
||||
|
||||
it('beforeShellExecution maps to waiting with the pending command as toolInput', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'beforeShellExecution', command: 'rm -rf /tmp/foo' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('waiting')
|
||||
expect(result?.payload.toolName).toBe('Shell')
|
||||
expect(result?.payload.toolInput).toBe('rm -rf /tmp/foo')
|
||||
})
|
||||
|
||||
it('beforeMCPExecution maps to waiting', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'beforeMCPExecution', tool_name: 'fetch', url: 'https://x' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('waiting')
|
||||
expect(result?.payload.toolName).toBe('fetch')
|
||||
})
|
||||
|
||||
it('preToolUse surfaces tool name + input preview and stays working', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({
|
||||
hook_event_name: 'preToolUse',
|
||||
tool_name: 'Read',
|
||||
tool_input: { file_path: '/repo/src/app.ts' }
|
||||
}),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('working')
|
||||
expect(result?.payload.toolName).toBe('Read')
|
||||
expect(result?.payload.toolInput).toBe('/repo/src/app.ts')
|
||||
})
|
||||
|
||||
it('afterAgentResponse carries text into lastAssistantMessage', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'afterAgentResponse', text: 'Done — wrote the README.' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('working')
|
||||
expect(result?.payload.lastAssistantMessage).toBe('Done — wrote the README.')
|
||||
})
|
||||
|
||||
it('beforeSubmitPrompt clears the cached tool state from a prior turn', () => {
|
||||
_internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({
|
||||
hook_event_name: 'preToolUse',
|
||||
tool_name: 'Edit',
|
||||
tool_input: { file_path: '/stale.ts' }
|
||||
}),
|
||||
'production'
|
||||
)
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'beforeSubmitPrompt', prompt: 'new turn' }),
|
||||
'production'
|
||||
)
|
||||
expect(result?.payload.state).toBe('working')
|
||||
expect(result?.payload.prompt).toBe('new turn')
|
||||
expect(result?.payload.toolName).toBeUndefined()
|
||||
expect(result?.payload.toolInput).toBeUndefined()
|
||||
})
|
||||
|
||||
it('subsequent stop preserves the cached prompt from beforeSubmitPrompt', () => {
|
||||
_internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'beforeSubmitPrompt', prompt: 'add tests' }),
|
||||
'production'
|
||||
)
|
||||
const stop = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'stop', status: 'completed' }),
|
||||
'production'
|
||||
)
|
||||
expect(stop?.payload.state).toBe('done')
|
||||
expect(stop?.payload.prompt).toBe('add tests')
|
||||
})
|
||||
|
||||
it('unknown event name returns null', () => {
|
||||
const result = _internals.normalizeHookPayload(
|
||||
'cursor',
|
||||
buildBody({ hook_event_name: 'somethingElse' }),
|
||||
'production'
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -22,7 +22,12 @@ import { ORCA_HOOK_PROTOCOL_VERSION } from '../../shared/agent-hook-types'
|
||||
// (session.status, session.idle, permission.asked) rather than settings.json
|
||||
// hook names, so the plugin pre-maps them to our hook_event_name vocabulary
|
||||
// before POSTing. See normalizeOpenCodeEvent below for the mapping.
|
||||
type AgentHookSource = 'claude' | 'codex' | 'gemini' | 'opencode'
|
||||
//
|
||||
// Cursor (cursor-agent) exposes a declarative hooks.json surface that is
|
||||
// conceptually similar to Claude's settings.json hooks but uses camelCase
|
||||
// event names (beforeSubmitPrompt, preToolUse, postToolUse, stop, etc.) per
|
||||
// https://cursor.com/docs/hooks. See normalizeCursorEvent below.
|
||||
type AgentHookSource = 'claude' | 'codex' | 'gemini' | 'opencode' | 'cursor'
|
||||
|
||||
type AgentHookEventPayload = {
|
||||
paneKey: string
|
||||
@@ -585,6 +590,63 @@ function extractOpenCodeToolFields(
|
||||
return {}
|
||||
}
|
||||
|
||||
// Why: Cursor's preToolUse / postToolUse / postToolUseFailure payloads carry
|
||||
// `tool_name` + `tool_input` (same shape as Claude). beforeShellExecution /
|
||||
// beforeMCPExecution carry a `command` field directly — surface that via a
|
||||
// synthetic "Shell" / "MCP" tool name so the dashboard row can show the
|
||||
// pending command while cursor-agent is blocked on approval.
|
||||
// afterAgentResponse carries a `text` field that is cursor's analogue of
|
||||
// Claude's last_assistant_message (the final composed reply for the turn).
|
||||
function extractCursorToolFields(
|
||||
eventName: unknown,
|
||||
hookPayload: Record<string, unknown>
|
||||
): ToolSnapshot {
|
||||
if (
|
||||
eventName === 'preToolUse' ||
|
||||
eventName === 'postToolUse' ||
|
||||
eventName === 'postToolUseFailure'
|
||||
) {
|
||||
const toolName = readString(hookPayload, 'tool_name')
|
||||
const toolInput = deriveToolInputPreview(toolName, hookPayload.tool_input)
|
||||
const update: ToolSnapshot = { toolName, toolInput }
|
||||
if (eventName === 'postToolUse') {
|
||||
const responseText = extractToolResponseText(hookPayload.tool_output)
|
||||
if (responseText) {
|
||||
update.lastAssistantMessage = responseText
|
||||
}
|
||||
}
|
||||
if (eventName === 'postToolUseFailure') {
|
||||
const errorText =
|
||||
extractToolResponseText(hookPayload.tool_output) ??
|
||||
readString(hookPayload, 'error_message') ??
|
||||
readString(hookPayload, 'error')
|
||||
if (errorText) {
|
||||
update.lastAssistantMessage = errorText
|
||||
}
|
||||
}
|
||||
return update
|
||||
}
|
||||
if (eventName === 'beforeShellExecution') {
|
||||
const command = readString(hookPayload, 'command')
|
||||
return { toolName: 'Shell', toolInput: command }
|
||||
}
|
||||
if (eventName === 'beforeMCPExecution') {
|
||||
const toolName = readString(hookPayload, 'tool_name') ?? 'MCP'
|
||||
const toolInput =
|
||||
deriveToolInputPreview(toolName, hookPayload.tool_input) ??
|
||||
readString(hookPayload, 'command') ??
|
||||
readString(hookPayload, 'url')
|
||||
return { toolName, toolInput }
|
||||
}
|
||||
if (eventName === 'afterAgentResponse') {
|
||||
const text = readString(hookPayload, 'text')
|
||||
if (text) {
|
||||
return { lastAssistantMessage: text }
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
function isNewTurnEvent(source: AgentHookSource, eventName: unknown): boolean {
|
||||
if (source === 'claude') {
|
||||
return eventName === 'UserPromptSubmit'
|
||||
@@ -598,6 +660,12 @@ function isNewTurnEvent(source: AgentHookSource, eventName: unknown): boolean {
|
||||
if (source === 'gemini') {
|
||||
return eventName === 'BeforeAgent'
|
||||
}
|
||||
if (source === 'cursor') {
|
||||
// Why: Cursor's beforeSubmitPrompt is the new-turn boundary (it carries
|
||||
// the fresh prompt). sessionStart also begins a fresh session and should
|
||||
// not inherit any cached tool state from whatever was left on disk.
|
||||
return eventName === 'beforeSubmitPrompt' || eventName === 'sessionStart'
|
||||
}
|
||||
// Why: OpenCode has no UserPromptSubmit analogue, AND the plugin emits the
|
||||
// user's MessagePart *before* SessionBusy (message.updated fires on prompt
|
||||
// submission; session.status goes busy only once OpenCode begins processing).
|
||||
@@ -621,6 +689,9 @@ function extractToolFields(
|
||||
if (source === 'gemini') {
|
||||
return extractGeminiToolFields(eventName, hookPayload)
|
||||
}
|
||||
if (source === 'cursor') {
|
||||
return extractCursorToolFields(eventName, hookPayload)
|
||||
}
|
||||
return extractOpenCodeToolFields(eventName, hookPayload)
|
||||
}
|
||||
|
||||
@@ -807,6 +878,67 @@ function normalizeOpenCodeEvent(
|
||||
)
|
||||
}
|
||||
|
||||
// Why: Cursor (cursor-agent) installs hooks via ~/.cursor/hooks.json with
|
||||
// camelCase event names, per https://cursor.com/docs/hooks. The CLI fires
|
||||
// stdin-JSON payloads for each subscribed event; we subscribe to the subset
|
||||
// that marks turn boundaries and produces meaningful working/done/waiting
|
||||
// transitions for the Orca sidebar. afterAgentResponse carries the final
|
||||
// assistant reply text, which is cursor's analogue of Claude's Stop
|
||||
// last_assistant_message — we keep the row in `working` there because the
|
||||
// true turn-end signal is `stop`.
|
||||
function normalizeCursorEvent(
|
||||
eventName: unknown,
|
||||
promptText: string,
|
||||
paneKey: string,
|
||||
hookPayload: Record<string, unknown>
|
||||
): ParsedAgentStatusPayload | null {
|
||||
const state =
|
||||
eventName === 'beforeSubmitPrompt' ||
|
||||
eventName === 'sessionStart' ||
|
||||
eventName === 'preToolUse' ||
|
||||
eventName === 'postToolUse' ||
|
||||
eventName === 'postToolUseFailure' ||
|
||||
eventName === 'afterAgentResponse'
|
||||
? 'working'
|
||||
: eventName === 'stop' || eventName === 'sessionEnd'
|
||||
? 'done'
|
||||
: eventName === 'beforeShellExecution' || eventName === 'beforeMCPExecution'
|
||||
? 'waiting'
|
||||
: null
|
||||
|
||||
if (!state) {
|
||||
return null
|
||||
}
|
||||
|
||||
const snapshot = resolveToolState(paneKey, extractToolFields('cursor', eventName, hookPayload), {
|
||||
resetOnNewTurn: isNewTurnEvent('cursor', eventName)
|
||||
})
|
||||
|
||||
// Why: cursor-agent reports turn interrupts via `stop` with status !==
|
||||
// "completed" (e.g. "cancelled", "stopped"). Forward the boolean so the
|
||||
// sidebar can render the interrupted-turn treatment that Claude uses.
|
||||
const interrupted =
|
||||
eventName === 'stop' &&
|
||||
typeof hookPayload.status === 'string' &&
|
||||
hookPayload.status !== 'completed'
|
||||
? true
|
||||
: undefined
|
||||
|
||||
return parseAgentStatusPayload(
|
||||
JSON.stringify({
|
||||
state,
|
||||
prompt: resolvePrompt(paneKey, promptText, {
|
||||
resetOnNewTurn: isNewTurnEvent('cursor', eventName)
|
||||
}),
|
||||
agentType: 'cursor',
|
||||
toolName: snapshot.toolName,
|
||||
toolInput: snapshot.toolInput,
|
||||
lastAssistantMessage: snapshot.lastAssistantMessage,
|
||||
interrupted
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function readStringField(record: Record<string, unknown>, key: string): string | undefined {
|
||||
const value = record[key]
|
||||
if (typeof value !== 'string') {
|
||||
@@ -899,7 +1031,9 @@ function normalizeHookPayload(
|
||||
? normalizeCodexEvent(eventName, promptText, paneKey, hookPayloadRecord)
|
||||
: source === 'gemini'
|
||||
? normalizeGeminiEvent(eventName, promptText, paneKey, hookPayloadRecord)
|
||||
: normalizeOpenCodeEvent(eventName, promptText, paneKey, hookPayloadRecord)
|
||||
: source === 'cursor'
|
||||
? normalizeCursorEvent(eventName, promptText, paneKey, hookPayloadRecord)
|
||||
: normalizeOpenCodeEvent(eventName, promptText, paneKey, hookPayloadRecord)
|
||||
|
||||
return payload ? { paneKey, tabId, worktreeId, payload } : null
|
||||
}
|
||||
@@ -974,7 +1108,9 @@ export class AgentHookServer {
|
||||
? 'gemini'
|
||||
: pathname === '/hook/opencode'
|
||||
? 'opencode'
|
||||
: null
|
||||
: pathname === '/hook/cursor'
|
||||
? 'cursor'
|
||||
: null
|
||||
if (!source) {
|
||||
res.writeHead(404)
|
||||
res.end()
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { homedir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { app } from 'electron'
|
||||
import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types'
|
||||
import {
|
||||
createManagedCommandMatcher,
|
||||
readHooksJson,
|
||||
removeManagedCommands,
|
||||
writeHooksJson,
|
||||
writeManagedScript,
|
||||
type HookDefinition
|
||||
} from '../agent-hooks/installer-utils'
|
||||
|
||||
// Why: cursor-agent exposes a declarative hooks.json surface at
|
||||
// ~/.cursor/hooks.json (https://cursor.com/docs/hooks) with camelCase event
|
||||
// names. We subscribe to the minimum set that drives the sidebar spinner and
|
||||
// turn-boundary detection:
|
||||
// - beforeSubmitPrompt: new turn starts (carries the user's prompt)
|
||||
// - stop: turn ends (→ done)
|
||||
// - preToolUse/postToolUse/postToolUseFailure: in-flight tool preview
|
||||
// between submit and stop — without these the pane appears idle for the
|
||||
// entire duration of a long tool-heavy turn
|
||||
// - beforeShellExecution / beforeMCPExecution: approval prompts (→ waiting)
|
||||
// - afterAgentResponse: carries the final composed reply text so the
|
||||
// dashboard can surface it on done
|
||||
// sessionStart / sessionEnd are intentionally NOT subscribed — cursor-agent
|
||||
// fires them at process lifetime boundaries rather than at turn boundaries,
|
||||
// and sessionStart's fire-time can race the first beforeSubmitPrompt in a
|
||||
// way that would reset the prompt cache for the just-submitted turn.
|
||||
const CURSOR_EVENTS = [
|
||||
'beforeSubmitPrompt',
|
||||
'stop',
|
||||
'preToolUse',
|
||||
'postToolUse',
|
||||
'postToolUseFailure',
|
||||
'beforeShellExecution',
|
||||
'beforeMCPExecution',
|
||||
'afterAgentResponse'
|
||||
] as const
|
||||
|
||||
function getConfigPath(): string {
|
||||
return join(homedir(), '.cursor', 'hooks.json')
|
||||
}
|
||||
|
||||
function getManagedScriptFileName(): string {
|
||||
return process.platform === 'win32' ? 'cursor-hook.cmd' : 'cursor-hook.sh'
|
||||
}
|
||||
|
||||
function getManagedScriptPath(): string {
|
||||
return join(app.getPath('userData'), 'agent-hooks', getManagedScriptFileName())
|
||||
}
|
||||
|
||||
function getManagedCommand(scriptPath: string): string {
|
||||
return process.platform === 'win32' ? scriptPath : `/bin/sh "${scriptPath}"`
|
||||
}
|
||||
|
||||
function getManagedScript(): string {
|
||||
if (process.platform === 'win32') {
|
||||
return [
|
||||
'@echo off',
|
||||
'setlocal',
|
||||
'if "%ORCA_AGENT_HOOK_PORT%"=="" exit /b 0',
|
||||
'if "%ORCA_AGENT_HOOK_TOKEN%"=="" exit /b 0',
|
||||
'if "%ORCA_PANE_KEY%"=="" exit /b 0',
|
||||
`powershell -NoProfile -ExecutionPolicy Bypass -Command "$inputData=[Console]::In.ReadToEnd(); if ([string]::IsNullOrWhiteSpace($inputData)) { exit 0 }; try { $body=@{ paneKey=$env:ORCA_PANE_KEY; tabId=$env:ORCA_TAB_ID; worktreeId=$env:ORCA_WORKTREE_ID; env=$env:ORCA_AGENT_HOOK_ENV; version=$env:ORCA_AGENT_HOOK_VERSION; payload=($inputData | ConvertFrom-Json) } | ConvertTo-Json -Depth 100; Invoke-WebRequest -UseBasicParsing -Method Post -Uri ('http://127.0.0.1:' + $env:ORCA_AGENT_HOOK_PORT + '/hook/cursor') -Headers @{ 'Content-Type'='application/json'; 'X-Orca-Agent-Hook-Token'=$env:ORCA_AGENT_HOOK_TOKEN } -Body $body | Out-Null } catch {}"`,
|
||||
'exit /b 0',
|
||||
''
|
||||
].join('\r\n')
|
||||
}
|
||||
|
||||
return [
|
||||
'#!/bin/sh',
|
||||
'if [ -z "$ORCA_AGENT_HOOK_PORT" ] || [ -z "$ORCA_AGENT_HOOK_TOKEN" ] || [ -z "$ORCA_PANE_KEY" ]; then',
|
||||
' exit 0',
|
||||
'fi',
|
||||
'payload=$(cat)',
|
||||
'if [ -z "$payload" ]; then',
|
||||
' exit 0',
|
||||
'fi',
|
||||
// Why: worktreeId embeds a filesystem path, so hand-building JSON in POSIX
|
||||
// shell is not safe once a path contains quotes or newlines. Post the raw
|
||||
// hook payload plus metadata as form fields and let the receiver parse it.
|
||||
'curl -sS -X POST "http://127.0.0.1:${ORCA_AGENT_HOOK_PORT}/hook/cursor" \\',
|
||||
' -H "Content-Type: application/x-www-form-urlencoded" \\',
|
||||
' -H "X-Orca-Agent-Hook-Token: ${ORCA_AGENT_HOOK_TOKEN}" \\',
|
||||
' --data-urlencode "paneKey=${ORCA_PANE_KEY}" \\',
|
||||
' --data-urlencode "tabId=${ORCA_TAB_ID}" \\',
|
||||
' --data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" \\',
|
||||
' --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}" \\',
|
||||
' --data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}" \\',
|
||||
' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true',
|
||||
'exit 0',
|
||||
''
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export class CursorHookService {
|
||||
getStatus(): AgentHookInstallStatus {
|
||||
const configPath = getConfigPath()
|
||||
const scriptPath = getManagedScriptPath()
|
||||
const config = readHooksJson(configPath)
|
||||
if (!config) {
|
||||
return {
|
||||
agent: 'cursor',
|
||||
state: 'error',
|
||||
configPath,
|
||||
managedHooksPresent: false,
|
||||
detail: 'Could not parse Cursor hooks.json'
|
||||
}
|
||||
}
|
||||
|
||||
const command = getManagedCommand(scriptPath)
|
||||
const missing: string[] = []
|
||||
let presentCount = 0
|
||||
for (const eventName of CURSOR_EVENTS) {
|
||||
const definitions = Array.isArray(config.hooks?.[eventName]) ? config.hooks![eventName]! : []
|
||||
// Why: Cursor's schema places the command directly on the definition
|
||||
// (not nested under a `hooks` array as Claude does), so match both
|
||||
// shapes to stay robust against future schema changes.
|
||||
const hasCommand = definitions.some(
|
||||
(definition) =>
|
||||
definition.command === command ||
|
||||
(definition.hooks ?? []).some((hook) => hook.command === command)
|
||||
)
|
||||
if (hasCommand) {
|
||||
presentCount += 1
|
||||
} else {
|
||||
missing.push(eventName)
|
||||
}
|
||||
}
|
||||
const managedHooksPresent = presentCount > 0
|
||||
let state: AgentHookInstallState
|
||||
let detail: string | null
|
||||
if (missing.length === 0) {
|
||||
state = 'installed'
|
||||
detail = null
|
||||
} else if (presentCount === 0) {
|
||||
state = 'not_installed'
|
||||
detail = null
|
||||
} else {
|
||||
state = 'partial'
|
||||
detail = `Managed hook missing for events: ${missing.join(', ')}`
|
||||
}
|
||||
return { agent: 'cursor', state, configPath, managedHooksPresent, detail }
|
||||
}
|
||||
|
||||
install(): AgentHookInstallStatus {
|
||||
const configPath = getConfigPath()
|
||||
const scriptPath = getManagedScriptPath()
|
||||
const config = readHooksJson(configPath)
|
||||
if (!config) {
|
||||
return {
|
||||
agent: 'cursor',
|
||||
state: 'error',
|
||||
configPath,
|
||||
managedHooksPresent: false,
|
||||
detail: 'Could not parse Cursor hooks.json'
|
||||
}
|
||||
}
|
||||
|
||||
const command = getManagedCommand(scriptPath)
|
||||
// Why: Cursor's hooks.json wraps the map under a top-level "hooks" key
|
||||
// (same as Claude/Codex). A fresh file with no prior hook install will
|
||||
// have config.hooks === undefined.
|
||||
const nextHooks = { ...config.hooks }
|
||||
const managedEvents = new Set<string>(CURSOR_EVENTS)
|
||||
|
||||
// Why: match by script filename (not exact command string) so a fresh
|
||||
// install sweeps stale entries left by older builds or a different
|
||||
// Electron userData path (dev vs. prod). Without this, repeated installs
|
||||
// accumulate duplicate hook entries pointing at defunct scripts.
|
||||
const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName())
|
||||
|
||||
// Why: sweep managed entries out of events we no longer subscribe to
|
||||
// (e.g. a future rename where we drop an event name). Without this,
|
||||
// users who already had that event registered would keep firing stale
|
||||
// hooks after the app upgrade.
|
||||
for (const [eventName, definitions] of Object.entries(nextHooks)) {
|
||||
if (managedEvents.has(eventName)) {
|
||||
continue
|
||||
}
|
||||
if (!Array.isArray(definitions)) {
|
||||
continue
|
||||
}
|
||||
const cleaned = removeManagedCommands(definitions, isManagedCommand)
|
||||
// Also strip entries with the command at the top level (Cursor schema).
|
||||
const strippedCursorShape = cleaned.filter(
|
||||
(definition) => !isManagedCommand(definition.command as string | undefined)
|
||||
)
|
||||
if (strippedCursorShape.length === 0) {
|
||||
delete nextHooks[eventName]
|
||||
} else {
|
||||
nextHooks[eventName] = strippedCursorShape
|
||||
}
|
||||
}
|
||||
|
||||
for (const eventName of CURSOR_EVENTS) {
|
||||
const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : []
|
||||
// Sweep both the Claude-shaped (hooks[].command) and Cursor-shaped
|
||||
// (definition.command) variants so repeated installs converge on a
|
||||
// single managed entry.
|
||||
const cleaned = removeManagedCommands(current, isManagedCommand).filter(
|
||||
(definition) => !isManagedCommand(definition.command as string | undefined)
|
||||
)
|
||||
// Why: Cursor's documented schema puts `command` directly on the
|
||||
// definition (not under `hooks`). Emit that shape so cursor-agent
|
||||
// actually invokes the script.
|
||||
const definition: HookDefinition = { command }
|
||||
nextHooks[eventName] = [...cleaned, definition]
|
||||
}
|
||||
|
||||
// Why: cursor-agent's config schema requires a top-level `version: 1`
|
||||
// (see https://cursor.com/docs/hooks). Preserve an existing value if the
|
||||
// user has already pinned one, otherwise stamp the default so a fresh
|
||||
// install produces a valid file. HooksConfig has an index signature on
|
||||
// extra keys, so assign via a Record-typed object to satisfy the type.
|
||||
const nextConfig: Record<string, unknown> = { ...config, hooks: nextHooks }
|
||||
if (nextConfig.version === undefined) {
|
||||
nextConfig.version = 1
|
||||
}
|
||||
writeManagedScript(scriptPath, getManagedScript())
|
||||
writeHooksJson(configPath, nextConfig)
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
remove(): AgentHookInstallStatus {
|
||||
const configPath = getConfigPath()
|
||||
const config = readHooksJson(configPath)
|
||||
if (!config) {
|
||||
return {
|
||||
agent: 'cursor',
|
||||
state: 'error',
|
||||
configPath,
|
||||
managedHooksPresent: false,
|
||||
detail: 'Could not parse Cursor hooks.json'
|
||||
}
|
||||
}
|
||||
|
||||
const nextHooks = { ...config.hooks }
|
||||
const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName())
|
||||
for (const [eventName, definitions] of Object.entries(nextHooks)) {
|
||||
if (!Array.isArray(definitions)) {
|
||||
continue
|
||||
}
|
||||
const cleaned = removeManagedCommands(definitions, isManagedCommand).filter(
|
||||
(definition) => !isManagedCommand(definition.command as string | undefined)
|
||||
)
|
||||
if (cleaned.length === 0) {
|
||||
delete nextHooks[eventName]
|
||||
} else {
|
||||
nextHooks[eventName] = cleaned
|
||||
}
|
||||
}
|
||||
const nextConfig = { ...config, hooks: nextHooks }
|
||||
writeHooksJson(configPath, nextConfig)
|
||||
return this.getStatus()
|
||||
}
|
||||
}
|
||||
|
||||
export const cursorHookService = new CursorHookService()
|
||||
+146
-29
@@ -44,6 +44,8 @@ import { agentHookServer } from './agent-hooks/server'
|
||||
import { claudeHookService } from './claude/hook-service'
|
||||
import { codexHookService } from './codex/hook-service'
|
||||
import { geminiHookService } from './gemini/hook-service'
|
||||
import { cursorHookService } from './cursor/hook-service'
|
||||
import { getPtyIdForPaneKey, registerPaneKeyTeardownListener } from './ipc/pty'
|
||||
import { AGENT_DASHBOARD_ENABLED } from '../shared/constants'
|
||||
import { AgentBrowserBridge } from './browser/agent-browser-bridge'
|
||||
import { browserManager } from './browser/browser-manager'
|
||||
@@ -166,32 +168,136 @@ function openMainWindow(): BrowserWindow {
|
||||
if (mainWindow === window) {
|
||||
mainWindow = null
|
||||
}
|
||||
if (AGENT_DASHBOARD_ENABLED) {
|
||||
// Why: detach the agent hook listener on window close so the server
|
||||
// never fires into a destroyed webContents during the gap before
|
||||
// reopen (e.g. macOS dock re-activation). This also ensures the
|
||||
// replay-loop through lastStatusByPaneKey runs only on deliberate
|
||||
// window recreations instead of stacking on top of stale listeners.
|
||||
agentHookServer.setListener(null)
|
||||
// Why: detach the agent hook listener on window close so the server
|
||||
// never fires into a destroyed webContents during the gap before
|
||||
// reopen (e.g. macOS dock re-activation). This also ensures the
|
||||
// replay-loop through lastStatusByPaneKey runs only on deliberate
|
||||
// window recreations instead of stacking on top of stale listeners.
|
||||
agentHookServer.setListener(null)
|
||||
// Why: any running cursor spinner intervals would fire into a destroyed
|
||||
// webContents; stop them all here instead of deferring to per-pane
|
||||
// teardown, which may never run for restored-but-never-torn-down panes
|
||||
// when the window goes away.
|
||||
// Why: stopCursorSpinner deletes only the current entry, which the Map
|
||||
// iterator handles safely — no snapshot copy needed.
|
||||
for (const paneKey of cursorSpinnerByPaneKey.keys()) {
|
||||
stopCursorSpinner(paneKey)
|
||||
}
|
||||
})
|
||||
mainWindow = window
|
||||
if (AGENT_DASHBOARD_ENABLED) {
|
||||
agentHookServer.setListener(({ paneKey, tabId, worktreeId, payload }) => {
|
||||
if (mainWindow?.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
agentHookServer.setListener(({ paneKey, tabId, worktreeId, payload }) => {
|
||||
if (mainWindow?.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
if (AGENT_DASHBOARD_ENABLED) {
|
||||
mainWindow?.webContents.send('agentStatus:set', {
|
||||
paneKey,
|
||||
tabId,
|
||||
worktreeId,
|
||||
...payload
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
// Why: cursor-agent emits no title-based working/idle signal — its OSC
|
||||
// title stays "Cursor Agent" for the whole turn. Synthesize an OSC title
|
||||
// update from the hook state and inject it into the pane's data stream so
|
||||
// the existing renderer-side title tracker (the one that drives the
|
||||
// sidebar spinner, unread badge, and Claude prompt-cache timer for every
|
||||
// other agent) lights up for cursor panes too. Braille prefix ⠋ → working
|
||||
// keyword path; "action required" keyword → permission; bare label → idle.
|
||||
// This runs regardless of AGENT_DASHBOARD_ENABLED because cursor has no
|
||||
// pre-dashboard title heuristic to fall back to.
|
||||
if (payload.agentType === 'cursor') {
|
||||
driveCursorPaneFromHook(paneKey, payload.state)
|
||||
}
|
||||
})
|
||||
return window
|
||||
}
|
||||
|
||||
// Why: Pi-style persistent spinner — cursor-agent re-emits its own
|
||||
// "Cursor Agent" OSC title on every internal redraw, so a single synthesized
|
||||
// "⠋ Cursor Agent" frame gets silently overwritten in the renderer within
|
||||
// milliseconds and the sidebar dot snaps back to solid. Keep asserting a
|
||||
// fresh working frame on an interval until the hook reports a non-working
|
||||
// state. Interval matches Pi's 80ms cadence — fast enough for a smooth
|
||||
// spinner, slow enough to stay well under the per-flush IPC budget.
|
||||
const CURSOR_SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
|
||||
const CURSOR_SPINNER_INTERVAL_MS = 80
|
||||
const cursorSpinnerByPaneKey = new Map<
|
||||
string,
|
||||
{ timer: ReturnType<typeof setInterval>; frame: number }
|
||||
>()
|
||||
|
||||
// Why: on PTY teardown the paneKey→ptyId mapping is dropped, so the spinner
|
||||
// interval would keep firing but sendCursorTitle would no-op forever. Stop
|
||||
// the interval explicitly so the process doesn't carry a timer per dead pane.
|
||||
registerPaneKeyTeardownListener((paneKey) => {
|
||||
stopCursorSpinner(paneKey)
|
||||
})
|
||||
|
||||
function sendCursorTitle(ptyId: string, data: string): void {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
mainWindow.webContents.send('pty:data', { id: ptyId, data })
|
||||
}
|
||||
|
||||
function stopCursorSpinner(paneKey: string): void {
|
||||
const entry = cursorSpinnerByPaneKey.get(paneKey)
|
||||
if (entry) {
|
||||
clearInterval(entry.timer)
|
||||
cursorSpinnerByPaneKey.delete(paneKey)
|
||||
}
|
||||
}
|
||||
|
||||
function driveCursorPaneFromHook(paneKey: string, state: string): void {
|
||||
const ptyId = getPtyIdForPaneKey(paneKey)
|
||||
if (!ptyId) {
|
||||
return
|
||||
}
|
||||
if (state === 'working') {
|
||||
// Why: immediately emit the first frame so the spinner starts visible at
|
||||
// this hook event even if the interval's next tick is 80ms away. Subsequent
|
||||
// frames come from the interval below.
|
||||
const existing = cursorSpinnerByPaneKey.get(paneKey)
|
||||
const frame = existing ? existing.frame : 0
|
||||
sendCursorTitle(ptyId, `\x1b]0;${CURSOR_SPINNER_FRAMES[frame]} Cursor Agent\x07`)
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
const ptyIdNow = getPtyIdForPaneKey(paneKey)
|
||||
if (!ptyIdNow) {
|
||||
stopCursorSpinner(paneKey)
|
||||
return
|
||||
}
|
||||
const cur = cursorSpinnerByPaneKey.get(paneKey)
|
||||
if (!cur) {
|
||||
return
|
||||
}
|
||||
cur.frame = (cur.frame + 1) % CURSOR_SPINNER_FRAMES.length
|
||||
sendCursorTitle(ptyIdNow, `\x1b]0;${CURSOR_SPINNER_FRAMES[cur.frame]} Cursor Agent\x07`)
|
||||
}, CURSOR_SPINNER_INTERVAL_MS)
|
||||
cursorSpinnerByPaneKey.set(paneKey, { timer, frame })
|
||||
return
|
||||
}
|
||||
// Why: leaving the spinner running after a `blocked`/`waiting`/`done` event
|
||||
// would immediately race the terminal state back to "working" on the next
|
||||
// tick. Stop first, then inject the terminal frame. Idle/done uses a
|
||||
// decorated "Cursor ready" label rather than the bare native "Cursor Agent"
|
||||
// — which the detector deliberately treats as a no-op so cursor's own
|
||||
// per-turn re-emissions cannot clobber our synthesized state. The
|
||||
// done/permission frames also carry a trailing BEL (0x07 outside of any OSC
|
||||
// sequence) because cursor-agent does not emit one on its own — and the
|
||||
// tab-level unread badge + notification dispatch in pty-connection keys off
|
||||
// BEL, not the working→idle title transition.
|
||||
stopCursorSpinner(paneKey)
|
||||
const synthetic =
|
||||
state === 'blocked' || state === 'waiting'
|
||||
? '\x1b]0;Cursor - action required\x07\x07'
|
||||
: '\x1b]0;Cursor ready\x07\x07'
|
||||
sendCursorTitle(ptyId, synthetic)
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
electronApp.setAppUserModelId('com.stablyai.orca')
|
||||
app.setName('Orca')
|
||||
@@ -220,6 +326,13 @@ app.whenReady().then(async () => {
|
||||
nativeTheme.themeSource = store.getSettings().theme ?? 'system'
|
||||
// Why: managed hook installation mutates user-global agent config.
|
||||
// Startup must fail open so a malformed local config never bricks Orca.
|
||||
// Claude/Codex/Gemini installs are gated behind AGENT_DASHBOARD_ENABLED
|
||||
// because the surface they feed (the in-progress agent dashboard) isn't
|
||||
// shippable yet. Cursor installs unconditionally because cursor-agent
|
||||
// emits no title-based working/idle signal at all (its terminal title
|
||||
// stays literally "Cursor Agent" across a turn), so the hook channel is
|
||||
// the only way to drive the sidebar spinner + unread path for it — there
|
||||
// is no "pre-dashboard" fallback to degrade to the way Claude/Codex have.
|
||||
if (AGENT_DASHBOARD_ENABLED) {
|
||||
for (const installManagedHooks of [
|
||||
() => claudeHookService.install(),
|
||||
@@ -233,6 +346,11 @@ app.whenReady().then(async () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
cursorHookService.install()
|
||||
} catch (error) {
|
||||
console.error('[agent-hooks] Failed to install Cursor managed hooks:', error)
|
||||
}
|
||||
|
||||
registerAppMenu({
|
||||
onCheckForUpdates: (options) => checkForUpdatesFromMenu(options),
|
||||
@@ -291,18 +409,19 @@ app.whenReady().then(async () => {
|
||||
}
|
||||
setAppRuntimeFlags({ daemonEnabledAtStartup: daemonStarted })
|
||||
|
||||
if (AGENT_DASHBOARD_ENABLED) {
|
||||
try {
|
||||
// Why: PTY spawn env reads ORCA_AGENT_HOOK_* from the live server state.
|
||||
// Start the hook server before opening the window so restored/spawned
|
||||
// terminals never race ahead without hook env on first launch.
|
||||
await agentHookServer.start({ env: app.isPackaged ? 'production' : 'development' })
|
||||
} catch (error) {
|
||||
// Why: Claude/Codex/Gemini/OpenCode hook callbacks are sidebar
|
||||
// enrichment only. Orca must still boot even if the local loopback
|
||||
// receiver cannot bind on this launch.
|
||||
console.error('[agent-hooks] Failed to start local hook server:', error)
|
||||
}
|
||||
// Why: the hook server also runs unconditionally so cursor-agent panes can
|
||||
// reach it. Claude/Codex/Gemini hook scripts stay uninstalled while
|
||||
// AGENT_DASHBOARD_ENABLED is false, so only cursor events flow in. PTY
|
||||
// spawn env reads ORCA_AGENT_HOOK_* from the live server state, so the
|
||||
// server must start before the window opens — otherwise restored terminals
|
||||
// race ahead without the env on first launch.
|
||||
try {
|
||||
await agentHookServer.start({ env: app.isPackaged ? 'production' : 'development' })
|
||||
} catch (error) {
|
||||
// Why: Claude/Codex/Gemini/OpenCode/Cursor hook callbacks are sidebar
|
||||
// enrichment only. Orca must still boot even if the local loopback
|
||||
// receiver cannot bind on this launch.
|
||||
console.error('[agent-hooks] Failed to start local hook server:', error)
|
||||
}
|
||||
|
||||
// Why: once the hook server is ready (or has already failed open), window
|
||||
@@ -349,9 +468,7 @@ app.on('will-quit', () => {
|
||||
// so without this ordering, running agents would produce orphaned
|
||||
// agent_start events with no matching stops.
|
||||
starNag?.stop()
|
||||
if (AGENT_DASHBOARD_ENABLED) {
|
||||
agentHookServer.stop()
|
||||
}
|
||||
agentHookServer.stop()
|
||||
stats?.flush()
|
||||
// Why: agent-browser daemon processes would otherwise linger after Orca quits,
|
||||
// holding ports and leaving stale session state on disk.
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-types'
|
||||
import { claudeHookService } from '../claude/hook-service'
|
||||
import { codexHookService } from '../codex/hook-service'
|
||||
import { geminiHookService } from '../gemini/hook-service'
|
||||
import { cursorHookService } from '../cursor/hook-service'
|
||||
|
||||
// Why: install/remove are intentionally not exposed to the renderer. Orca
|
||||
// auto-installs managed hooks at app startup (see src/main/index.ts), so a
|
||||
@@ -18,6 +19,7 @@ export function registerAgentHookHandlers(): void {
|
||||
ipcMain.removeHandler('agentHooks:claudeStatus')
|
||||
ipcMain.removeHandler('agentHooks:codexStatus')
|
||||
ipcMain.removeHandler('agentHooks:geminiStatus')
|
||||
ipcMain.removeHandler('agentHooks:cursorStatus')
|
||||
|
||||
// Why: errors from getStatus() (fs permission denied, homedir resolution
|
||||
// failure, etc.) must be reported inline via state:'error' so the sidebar can
|
||||
@@ -63,4 +65,17 @@ export function registerAgentHookHandlers(): void {
|
||||
}
|
||||
}
|
||||
})
|
||||
ipcMain.handle('agentHooks:cursorStatus', (): AgentHookInstallStatus => {
|
||||
try {
|
||||
return cursorHookService.getStatus()
|
||||
} catch (err) {
|
||||
return {
|
||||
agent: 'cursor',
|
||||
state: 'error',
|
||||
configPath: '',
|
||||
managedHooksPresent: false,
|
||||
detail: err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -39,6 +39,29 @@ const ptyOwnership = new Map<string, string | null>()
|
||||
// teardown — the renderer knows the paneKey but the PTY lifecycle does not
|
||||
// without this mapping.
|
||||
const ptyPaneKey = new Map<string, string>()
|
||||
// Why: reverse of ptyPaneKey — callers that receive a paneKey from outside the
|
||||
// PTY lifecycle (e.g. the agent-hook server routing a cursor-agent status event
|
||||
// back into the pane's data stream) need to find the ptyId for that paneKey.
|
||||
// Kept in lock-step with ptyPaneKey via the same spawn and teardown sites.
|
||||
const paneKeyPtyId = new Map<string, string>()
|
||||
|
||||
export function getPtyIdForPaneKey(paneKey: string): string | undefined {
|
||||
return paneKeyPtyId.get(paneKey)
|
||||
}
|
||||
|
||||
// Why: consumers (currently the cursor-agent synthesized-spinner loop in
|
||||
// main/index.ts) need to tear down paneKey-scoped state when a PTY exits so
|
||||
// intervals / timers cannot leak for the process lifetime. A callback
|
||||
// registry keeps the cross-module dependency narrow — clearProviderPtyState
|
||||
// only has to know about "things to notify", not about every consumer's
|
||||
// internals.
|
||||
type PaneKeyTeardownListener = (paneKey: string) => void
|
||||
const paneKeyTeardownListeners = new Set<PaneKeyTeardownListener>()
|
||||
|
||||
export function registerPaneKeyTeardownListener(listener: PaneKeyTeardownListener): () => void {
|
||||
paneKeyTeardownListeners.add(listener)
|
||||
return () => paneKeyTeardownListeners.delete(listener)
|
||||
}
|
||||
|
||||
function getProvider(connectionId: string | null | undefined): IPtyProvider {
|
||||
if (!connectionId) {
|
||||
@@ -144,6 +167,17 @@ export function clearProviderPtyState(id: string): void {
|
||||
if (paneKey) {
|
||||
agentHookServer.clearPaneState(paneKey)
|
||||
ptyPaneKey.delete(id)
|
||||
paneKeyPtyId.delete(paneKey)
|
||||
// Why: notify registered consumers AFTER we've dropped the paneKey↔ptyId
|
||||
// entries so a listener that re-reads the map sees the post-teardown
|
||||
// state. Wrap each call so one throwing listener cannot block the rest.
|
||||
for (const listener of paneKeyTeardownListeners) {
|
||||
try {
|
||||
listener(paneKey)
|
||||
} catch (err) {
|
||||
console.error('[pty] paneKey teardown listener threw', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,6 +485,7 @@ export function registerPtyHandlers(
|
||||
const paneKey = args.env?.ORCA_PANE_KEY
|
||||
if (typeof paneKey === 'string' && paneKey.length > 0 && paneKey.length <= 256) {
|
||||
ptyPaneKey.set(result.id, paneKey)
|
||||
paneKeyPtyId.set(paneKey, result.id)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -555,7 +555,9 @@ const api = {
|
||||
codexStatus: (): Promise<AgentHookInstallStatus> =>
|
||||
ipcRenderer.invoke('agentHooks:codexStatus'),
|
||||
geminiStatus: (): Promise<AgentHookInstallStatus> =>
|
||||
ipcRenderer.invoke('agentHooks:geminiStatus')
|
||||
ipcRenderer.invoke('agentHooks:geminiStatus'),
|
||||
cursorStatus: (): Promise<AgentHookInstallStatus> =>
|
||||
ipcRenderer.invoke('agentHooks:cursorStatus')
|
||||
},
|
||||
|
||||
preflight: {
|
||||
|
||||
@@ -152,4 +152,59 @@ describe('dispatcher → transport → onTitleChange for Pi spinner', () => {
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
|
||||
// Why: regression test for the cursor spinner "solid after 500ms" bug.
|
||||
// cursor-agent re-emits its native `OSC 0: "Cursor Agent"` title on every
|
||||
// internal redraw mid-turn. Orca's main process injects synthesized
|
||||
// "⠋ Cursor Agent" spinner frames from the hook server; the renderer must
|
||||
// drop cursor's bare native title so it cannot overwrite the synthesized
|
||||
// working title in `runtimePaneTitlesByTabId` (which drives `getWorktreeStatus`'s
|
||||
// solid/spinning dot decision). If the bare title leaked through, the last
|
||||
// title in the store would flip to "Cursor Agent" (which `detectAgentStatusFromTitle`
|
||||
// classifies as null / not-working) and the sidebar would snap solid
|
||||
// mid-turn.
|
||||
it('drops cursor-agent native "Cursor Agent" title so it cannot overwrite the synthesized spinner', async () => {
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const onTitleChange = vi.fn()
|
||||
|
||||
const transport = createIpcPtyTransport({ onTitleChange })
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
|
||||
// Simulate the realistic interleave: Orca injects a synthesized working
|
||||
// frame, cursor-agent re-emits its bare native title shortly after, Orca
|
||||
// injects the next spinner frame, etc.
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠋ Cursor Agent${BEL}` })
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` })
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠙ Cursor Agent${BEL}` })
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` })
|
||||
|
||||
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
|
||||
// The two bare "Cursor Agent" titles must NOT reach the title-change
|
||||
// pipeline. The two synthesized spinner frames must.
|
||||
expect(seenTitles).not.toContain('Cursor Agent')
|
||||
expect(seenTitles).toContain('⠋ Cursor Agent')
|
||||
expect(seenTitles).toContain('⠙ Cursor Agent')
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
|
||||
it('still surfaces the synthesized "Cursor ready" idle title after working', async () => {
|
||||
// Why: make sure the bare-title drop does not accidentally catch the
|
||||
// decorated "Cursor ready" done frame Orca synthesizes on the `stop` hook.
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const onTitleChange = vi.fn()
|
||||
|
||||
const transport = createIpcPtyTransport({ onTitleChange })
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠋ Cursor Agent${BEL}` })
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` })
|
||||
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor ready${BEL}${BEL}` })
|
||||
|
||||
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
|
||||
expect(seenTitles).toContain('⠋ Cursor Agent')
|
||||
expect(seenTitles).toContain('Cursor ready')
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -200,6 +200,21 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
|
||||
}
|
||||
|
||||
function applyObservedTerminalTitle(title: string): void {
|
||||
// Why: cursor-agent's native OSC title is the literal string "Cursor Agent"
|
||||
// and it re-emits that title many times per turn (on every internal redraw)
|
||||
// even while it's actively working. Orca drives the cursor spinner/unread
|
||||
// path by injecting its own synthesized "⠋ Cursor Agent" and "Cursor ready"
|
||||
// frames from the hook server (see src/main/index.ts). If we let cursor's
|
||||
// bare title through, it lands in `runtimePaneTitlesByTabId` — where
|
||||
// `getWorktreeStatus` reads from — and flips the sidebar dot back to solid
|
||||
// within a second of the spinner appearing. Dropping the bare title before
|
||||
// it reaches the store leaves the synthesized frame as the last-applied
|
||||
// state until the next hook event overwrites it. Match is literal (trimmed,
|
||||
// case-insensitive) so any task/chat title cursor auto-generates still
|
||||
// passes through unchanged.
|
||||
if (title.trim().toLowerCase() === 'cursor agent') {
|
||||
return
|
||||
}
|
||||
lastEmittedTitle = normalizeTerminalTitle(title)
|
||||
onTitleChange?.(lastEmittedTitle, title)
|
||||
agentTracker?.handleTitle(title)
|
||||
|
||||
@@ -167,6 +167,32 @@ describe('detectAgentStatusFromTitle', () => {
|
||||
expect(detectAgentStatusFromTitle('π - session-name - my-project')).toBe('idle')
|
||||
})
|
||||
|
||||
// --- Cursor (cursor-agent) synthesized titles ---
|
||||
// Why: cursor-agent's native OSC title stays literally "Cursor Agent" for
|
||||
// the entire turn, so Orca synthesizes decorated titles from hook events
|
||||
// to drive the existing spinner/unread pipeline. These tests pin the
|
||||
// contract the main-process hook listener relies on.
|
||||
it('treats the bare "Cursor Agent" native title as a no-op (not idle)', () => {
|
||||
// Why: if the native title classified as idle, cursor's own per-turn
|
||||
// re-emissions would trigger working→idle transitions between our
|
||||
// synthesized working frames, stomping the spinner off mid-turn.
|
||||
expect(detectAgentStatusFromTitle('Cursor Agent')).toBeNull()
|
||||
expect(detectAgentStatusFromTitle('cursor agent')).toBeNull()
|
||||
expect(detectAgentStatusFromTitle(' Cursor Agent ')).toBeNull()
|
||||
})
|
||||
|
||||
it('classifies synthesized "⠋ Cursor Agent" working title as working', () => {
|
||||
expect(detectAgentStatusFromTitle('⠋ Cursor Agent')).toBe('working')
|
||||
})
|
||||
|
||||
it('classifies synthesized "Cursor ready" idle title as idle', () => {
|
||||
expect(detectAgentStatusFromTitle('Cursor ready')).toBe('idle')
|
||||
})
|
||||
|
||||
it('classifies synthesized "Cursor - action required" title as permission', () => {
|
||||
expect(detectAgentStatusFromTitle('Cursor - action required')).toBe('permission')
|
||||
})
|
||||
|
||||
// --- Case insensitivity ---
|
||||
it('is case-insensitive for agent names', () => {
|
||||
expect(detectAgentStatusFromTitle('CLAUDE')).toBe('idle')
|
||||
@@ -403,6 +429,26 @@ describe('createAgentStatusTracker', () => {
|
||||
expect(onBecameIdle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
// Why: end-to-end tracker coverage for cursor — synthesized working frames
|
||||
// interleaved with cursor's own "Cursor Agent" re-emissions must not fire
|
||||
// onBecameIdle until the "Cursor ready" done frame arrives.
|
||||
it('fires on Cursor working → idle across native "Cursor Agent" re-emissions', () => {
|
||||
const onBecameIdle = vi.fn()
|
||||
const tracker = createAgentStatusTracker(onBecameIdle)
|
||||
|
||||
tracker.handleTitle('⠋ Cursor Agent') // synthesized working
|
||||
expect(onBecameIdle).not.toHaveBeenCalled()
|
||||
|
||||
tracker.handleTitle('Cursor Agent') // cursor's native re-emission — no-op
|
||||
expect(onBecameIdle).not.toHaveBeenCalled()
|
||||
|
||||
tracker.handleTitle('Cursor Agent') // more native re-emissions
|
||||
expect(onBecameIdle).not.toHaveBeenCalled()
|
||||
|
||||
tracker.handleTitle('Cursor ready') // synthesized done → idle
|
||||
expect(onBecameIdle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('fires on Pi working → idle', () => {
|
||||
const onBecameIdle = vi.fn()
|
||||
const tracker = createAgentStatusTracker(onBecameIdle)
|
||||
@@ -598,8 +644,12 @@ describe('formatAgentTypeLabel', () => {
|
||||
expect(formatAgentTypeLabel('gemini')).toBe('Gemini')
|
||||
})
|
||||
|
||||
it("passes through unknown-but-nonsentinel strings as-is (e.g. 'cursor')", () => {
|
||||
expect(formatAgentTypeLabel('cursor')).toBe('cursor')
|
||||
it("maps 'cursor' to 'Cursor'", () => {
|
||||
expect(formatAgentTypeLabel('cursor')).toBe('Cursor')
|
||||
})
|
||||
|
||||
it('passes through arbitrary custom agent names as-is', () => {
|
||||
expect(formatAgentTypeLabel('weirdo')).toBe('weirdo')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -97,6 +97,7 @@ const WELL_KNOWN_LABELS: Record<string, string> = {
|
||||
codex: 'Codex',
|
||||
gemini: 'Gemini',
|
||||
opencode: 'OpenCode',
|
||||
cursor: 'Cursor',
|
||||
aider: 'Aider'
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ const GEMINI_SILENT_WORKING = '\u23F2' // ⏲
|
||||
const GEMINI_IDLE = '\u25C7' // ◇
|
||||
const GEMINI_PERMISSION = '\u270B' // ✋
|
||||
|
||||
export const AGENT_NAMES = ['claude', 'codex', 'copilot', 'gemini', 'opencode', 'aider']
|
||||
export const AGENT_NAMES = ['claude', 'codex', 'copilot', 'cursor', 'gemini', 'opencode', 'aider']
|
||||
|
||||
// Why: idle keywords used inside `detectAgentStatusFromTitle` to map titles
|
||||
// like "Codex done", "OpenCode ready", "Aider idle" to AgentStatus 'idle'.
|
||||
@@ -293,6 +293,13 @@ export function isClaudeAgent(title: string): boolean {
|
||||
return true
|
||||
}
|
||||
if (containsBrailleSpinner(title)) {
|
||||
// Why: Orca synthesizes `⠋ Cursor Agent` working titles for cursor-agent
|
||||
// panes (see hook listener in main/index.ts). Those titles carry a braille
|
||||
// spinner but are decidedly not Claude — the prompt-cache timer and other
|
||||
// Claude-scoped paths must not fire for them.
|
||||
if (title.toLowerCase().includes('cursor')) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
// Why: permission/action-required Claude titles can omit the usual prefixes.
|
||||
@@ -331,6 +338,15 @@ export function getAgentLabel(title: string): string | null {
|
||||
if (lower.includes('aider')) {
|
||||
return 'Aider'
|
||||
}
|
||||
// Why: the cursor-agent native title is the literal string "Cursor Agent"
|
||||
// (verified against the 2026.04.17 release) — Orca synthesizes the same
|
||||
// label from hook events so the braille-spinner + agent-name path lights
|
||||
// up working/permission/idle transitions in the renderer. Match before
|
||||
// `isClaudeAgent` because Claude's generic braille heuristic would
|
||||
// otherwise claim every "⠋ Cursor Agent" frame as Claude.
|
||||
if (lower.includes('cursor')) {
|
||||
return 'Cursor'
|
||||
}
|
||||
if (isClaudeAgent(title)) {
|
||||
return 'Claude Code'
|
||||
}
|
||||
@@ -338,10 +354,25 @@ export function getAgentLabel(title: string): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
// Why: cursor-agent's native OSC title is the literal string "Cursor Agent"
|
||||
// across the entire turn — it carries zero working/idle information. Orca
|
||||
// synthesizes its own titles ("⠋ Cursor Agent" for working, "Cursor -
|
||||
// action required" for permission) from cursor's hook events; the bare
|
||||
// native title must be a no-op so cursor's per-turn re-emissions cannot
|
||||
// stomp the synthesized state back to idle.
|
||||
const CURSOR_NATIVE_TITLE_LOWER = 'cursor agent'
|
||||
|
||||
export function detectAgentStatusFromTitle(title: string): AgentStatus | null {
|
||||
if (!title) {
|
||||
return null
|
||||
}
|
||||
// Why: "Cursor Agent" exactly (case-insensitive, no prefix/suffix) is cursor's
|
||||
// native title. Anything with additional tokens ("⠋ Cursor Agent", "Cursor -
|
||||
// action required") is either an Orca-synthesized working/permission title
|
||||
// or a tighter match worth classifying.
|
||||
if (title.trim().toLowerCase() === CURSOR_NATIVE_TITLE_LOWER) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Gemini CLI symbols are the most specific and should take precedence.
|
||||
if (title.includes(GEMINI_PERMISSION)) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Keeping the types shared up-front avoids a churn PR that renames or splits
|
||||
// them once the hook server imports them.
|
||||
|
||||
export type AgentHookTarget = 'claude' | 'codex' | 'gemini'
|
||||
export type AgentHookTarget = 'claude' | 'codex' | 'gemini' | 'cursor'
|
||||
|
||||
export type AgentHookInstallState = 'installed' | 'not_installed' | 'partial' | 'error'
|
||||
|
||||
|
||||
@@ -9,7 +9,14 @@ export type AgentStatusState = (typeof AGENT_STATUS_STATES)[number]
|
||||
// regularly and users may run custom agents. Any non-empty string is accepted;
|
||||
// well-known names are kept as a convenience union for internal code that
|
||||
// wants to pattern-match on common agents.
|
||||
export type WellKnownAgentType = 'claude' | 'codex' | 'gemini' | 'opencode' | 'aider' | 'unknown'
|
||||
export type WellKnownAgentType =
|
||||
| 'claude'
|
||||
| 'codex'
|
||||
| 'gemini'
|
||||
| 'opencode'
|
||||
| 'cursor'
|
||||
| 'aider'
|
||||
| 'unknown'
|
||||
export type AgentType = WellKnownAgentType | (string & {})
|
||||
|
||||
/** A snapshot of a previous agent state, used to render activity blocks.
|
||||
|
||||
Reference in New Issue
Block a user