Skip to content

fix(agent-hooks): restore Cursor launch tokens and new-turn restart (STA-3487) - #15695

Closed
brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/sta-3487-cursor-authority-drop
Closed

brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/sta-3487-cursor-authority-drop

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​363 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​362
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​79 $\color{#cf222e}{\Huge{\mathbf{−}}}$​13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​66

ELI5

Some Cursor panes kept showing Working after the agent finished. Two things stacked: a Cursor pane started as a plain cursor-agent command never got a launch token, and when launch authority was later retired, Orca only treated Claude's UserPromptSubmit / SessionStart as a new turn. Cursor's beforeSubmitPrompt was ignored, so a completed stop never landed. This stamps a launch token on bare Cursor launches and lets Cursor's own new-turn events reopen a retired pane. A completed stop still cannot stamp a sibling pane.

What Changed

  • Queued bare TUI agent commands (cursor-agent, codex, …) now get launchConfig + ORCA_AGENT_LAUNCH_TOKEN. Plain shell commands and non-bare invocations like codex exec stay tokenless.
  • Retired-pane restart now includes Cursor beforeSubmitPrompt / sessionStart (in addition to Claude UserPromptSubmit / SessionStart).
  • Tests: tokenless Cursor stop still settles; a retired Cursor pane restarts on beforeSubmitPrompt (local HTTP and SSH ingestRemote) then stop reaches done; a retired sibling cannot stamp another pane; queued cursor-agent carries the token.

Why

Paired Windows observation: same hook sequence (beforeSubmitPrompt → stop completed → afterAgentResponse), one pane done with a persisted authority commitment, the other stuck working with ORCA_AGENT_LAUNCH_TOKEN absent and no commitment.

Tokenless HTTP ingest already accepted stop (so loosening the authority check would not have been the right fix). The missing token is minted only when launchConfig exists; default-tab / command-only Cursor starts queue { command: 'cursor-agent' } and never got one. Independently, retirePaneAuthority (command-finished / restored receipt) deletes the row and fences the pane; Claude can restart on the next prompt, Cursor could not.

Related in-flight work: #15658 still owns nested-shell OSC 133;D falsely retiring launch authority while an agent is in the foreground. This PR does not duplicate that guard. It restores the lost token on the command-only launch path and makes Cursor's new-turn event reopen a retired pane the same way Claude already does.

Linked Issue

Fixes #12686
Fixes STA-3487

Visual Proof

N/A — hook-server ingest and queued-startup env stamping. No new chrome. The user-visible effect is the existing Cursor Working indicator settling to idle after a completed stop.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

TDD:

Stage Result
Pre-fix Tokenless Cursor stop already passed. Retired-pane Cursor restart failed (expected [] vs done). Queued cursor-agent had no launchToken (expected 'cursor', received undefined).
Post-fix server-cursor-pane-authority.test.ts 4/4, server-closed-tab-suppression.test.ts 20/20, queued-agent-launch-authority.test.ts 4/4, terminal-startup-command-retention.test.ts 6/6, launch-agent-in-new-tab.test.ts 27/27
Neutered (Cursor restart branch and queue attach removed, tests kept) Same two ingest restart tests and the queued cursor-agent token test failed again

Also: pnpm typecheck passed. oxlint --deny-warnings and oxfmt on changed files only — clean.

Windows host unreachable this session — Windows env propagation into Cursor panes is unvalidated.

Review

  • Security: launch tokens are still not a license to stamp another paneKey. Retired Cursor stop without a new-turn event stays suppressed. Plain shell startups remain tokenless so a typed agent cannot inherit a sibling token.
  • Cross-platform: token minting and hook disposition are host-agnostic. Windows ConPTY env was the original report and is unvalidated here.
  • Remote SSH: ingestRemote now forwards source into disposition; covered by the remote restart test. Folder workspaces use the same queueTabStartupCommand path.
  • Mobile: no client change; mobile consumes the same hook status rows.
  • Backwards compatibility: additive. No wire/RPC/stream opcode changes.
  • Performance: one command-line recognition pass when queueing a startup command.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author

  • X / Twitter: @BrennanKB5

Out of scope

@coderabbitai

coderabbitai Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 33b59ed3-bdeb-4844-882a-bf08da48c590

📥 Commits

Reviewing files that changed from the base of the PR and between efe0454 and 18b4e27.

📒 Files selected for processing (4)
  • src/main/agent-hooks/server.ts
  • src/renderer/src/store/slices/terminal-startup-command-retention.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/shared/queued-agent-launch-authority.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The change adds launch authority handling for queued agent commands. It generates or preserves launch tokens, records launch metadata, and injects ORCA_AGENT_LAUNCH_TOKEN into startup environments. Resume and terminal tests verify token propagation, replacement, uniqueness, and command filtering. Agent hook status disposition now receives the event source and recognizes non-replayed Cursor new-turn events. Cursor pane tests cover restart, completion, authority retirement, and launch-token fencing.

Merge Risk: 🔵 Low · up to 18b4e

Queued agent startup may fail in renderer environments that do not provide crypto.randomUUID, preventing the agent from launching. The PR is otherwise mergeable, but this bounded runtime-compatibility risk needs explicit owner awareness or follow-up.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the two main changes: restoring Cursor launch tokens and enabling new-turn restart behavior.
Description check ✅ Passed The description covers all template sections, explains the changes and rationale, documents testing and known gaps, and includes the linked issues.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5f2afc67-24a8-4cec-9532-b27135a9e55d

📥 Commits

Reviewing files that changed from the base of the PR and between 012e9f4 and efe0454.

📒 Files selected for processing (7)
  • src/main/agent-hooks/server-cursor-pane-authority.test.ts
  • src/main/agent-hooks/server.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • src/renderer/src/store/slices/terminal-startup-command-retention.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/shared/queued-agent-launch-authority.test.ts
  • src/shared/queued-agent-launch-authority.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +14 to +15
function mintLaunchToken(): string {
return globalThis.crypto.randomUUID()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- candidate files ---'
git ls-files | rg '(^|/)(queued-agent-launch-authority|.*browser.*uuid|.*uuid).*\.tsx?$|queued-agent-launch-authority'

printf '%s\n' '--- target outline ---'
if command -v ast-grep >/dev/null 2>&1; then
  ast-grep outline src/shared/queued-agent-launch-authority.ts
fi

printf '%s\n' '--- target source ---'
nl -ba src/shared/queued-agent-launch-authority.ts | sed -n '1,180p'

printf '%s\n' '--- createBrowserUuid references ---'
rg -n -C 5 'createBrowserUuid|randomUUID|getRandomValues|pendingStartupByTabId|mintLaunchToken' src test tests 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- exact target ---'
nl -ba src/shared/queued-agent-launch-authority.ts | sed -n '1,140p'

printf '%s\n' '--- browser uuid files ---'
git ls-files | rg '(^|/)(browser-uuid|.*uuid.*)\.(ts|tsx|js|jsx)$'

printf '%s\n' '--- browser uuid implementation ---'
while IFS= read -r f; do
  case "$f" in
    *browser-uuid*) nl -ba "$f" | sed -n '1,160p' ;;
  esac
done < <(git ls-files | rg '(^|/)(browser-uuid|.*uuid.*)\.(ts|tsx|js|jsx)$')

printf '%s\n' '--- queued launch references ---'
rg -n -C 4 --glob '*.ts' --glob '*.tsx' \
  'queued-agent-launch-authority|pendingStartupByTabId|mintLaunchToken|normalize.*Startup|launchToken' \
  src/shared src/renderer src/main | head -n 1200

Repository: stablyai/orca

Length of output: 429


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- exact target ---'
awk '{printf "%6d  %s\n", NR, $0}' src/shared/queued-agent-launch-authority.ts | sed -n '1,140p'

printf '%s\n' '--- browser uuid implementation ---'
awk '{printf "%6d  %s\n", NR, $0}' src/renderer/src/lib/browser-uuid.ts | sed -n '1,160p'

printf '%s\n' '--- browser uuid tests ---'
awk '{printf "%6d  %s\n", NR, $0}' src/renderer/src/lib/browser-uuid.test.ts | sed -n '1,220p'

printf '%s\n' '--- queued launch references ---'
rg -n -C 4 --glob '*.ts' --glob '*.tsx' \
  'queued-agent-launch-authority|pendingStartupByTabId|mintLaunchToken|normalize.*Startup|launchToken' \
  src/shared src/renderer src/main | sed -n '1,1200p'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- helper imports and calls ---'
rg -n -C 8 --glob '*.ts' --glob '*.tsx' \
  'attachQueuedAgentLaunchAuthority|queued-agent-launch-authority' \
  src

printf '%s\n' '--- pending startup definitions and writes ---'
rg -n -C 6 --glob '*.ts' --glob '*.tsx' \
  'pendingStartupByTabId|setPendingStartup|pendingStartup' \
  src/renderer/src/store src/renderer/src/runtime src/renderer/src/hooks src/shared \
  | rg -v 'test|snapshot|fixture' | sed -n '1,1600p'

printf '%s\n' '--- browser/build context for the shared module ---'
rg -n -C 5 --glob 'package.json' --glob '*.config.*' --glob '*.ts' --glob '*.tsx' \
  'src/shared|renderer|web|browser|queued-agent-launch-authority' \
  package.json src/renderer vite.config.* electron.vite.config.* tsconfig*.json 2>/dev/null \
  | sed -n '1,1200p'

Repository: stablyai/orca

Length of output: 50370


🌐 Web query:

MDN Crypto.randomUUID secure context getRandomValues available insecure contexts

💡 Result:

The Crypto.randomUUID method requires a secure context (HTTPS) to function [1][2]. In contrast, the getRandomValues method is the only member of the Crypto interface that remains available and usable in insecure contexts [3][4][5]. Key points regarding these APIs: 1. Security Requirement: While the crypto property itself is available on the window or worker object in insecure contexts [6][4], most of its methods—including randomUUID—are restricted to secure contexts [1][6][2]. 2. Localhost Exception: Browsers treat localhost as a secure origin, which allows crypto.randomUUID to function even when using HTTP on localhost [7]. However, for other insecure origins, this method will be undefined or unavailable [7]. 3. Recommended Usage: Developers are generally advised to use the Web Crypto API only in secure contexts to ensure appropriate security posture [6][4]. If a cryptographically secure random value is needed in an insecure context, getRandomValues is the supported option [3][5], though it should not be used for key generation, which also requires a secure context [3][2][5].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

node - <<'JS'
function mintLaunchTokenDirect(cryptoApi) {
  return cryptoApi.randomUUID()
}

function mintLaunchTokenWithGetRandomValues(cryptoApi) {
  if (typeof cryptoApi?.randomUUID === 'function') {
    return cryptoApi.randomUUID()
  }
  if (typeof cryptoApi?.getRandomValues !== 'function') {
    throw new Error('cryptographically secure UUID source unavailable')
  }
  const bytes = new Uint8Array(16)
  cryptoApi.getRandomValues(bytes)
  bytes[6] = (bytes[6] & 0x0f) | 0x40
  bytes[8] = (bytes[8] & 0x3f) | 0x80
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
}

const cryptoWithoutRandomUUID = {
  getRandomValues(bytes) {
    for (let i = 0; i < bytes.length; i += 1) bytes[i] = i
    return bytes
  }
}

let directThrew = false
try {
  mintLaunchTokenDirect(cryptoWithoutRandomUUID)
} catch (error) {
  directThrew = error instanceof TypeError
}

const fallbackToken = mintLaunchTokenWithGetRandomValues(cryptoWithoutRandomUUID)
console.log(JSON.stringify({ directThrew, fallbackToken }))
JS

Repository: stablyai/orca

Length of output: 223


Use a cryptographically secure UUID fallback for launch tokens.

randomUUID() is unavailable on non-secure web origins, so this call can throw before pendingStartupByTabId is written. Use getRandomValues or an injected token factory. Do not use createBrowserUuid unchanged because its final fallback uses Math.random. Add a regression test with randomUUID unavailable.

…STA-3487)

Bare cursor-agent queued startups never minted ORCA_AGENT_LAUNCH_TOKEN, and
retired panes only restarted on Claude UserPromptSubmit/SessionStart, so a
Cursor beforeSubmitPrompt after authority retire could not settle stop to done.
STA-3487 stamps ORCA_AGENT_LAUNCH_TOKEN onto a recognized TUI-agent startup, so
resume's env is no longer only the captured agentEnv. Keeps the captured-vs-changed
intent and the exact key set, and pins the token to the queued launchToken.
…lper

Stop queueTabStartupCommand from minting a launchConfig-only token that
never reached ORCA_AGENT_LAUNCH_TOKEN. Pin resume overwriting a captured
token, sibling isolation, and non-bare/unrecognized commands staying
tokenless.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-3487-cursor-authority-drop branch from efe0454 to 18b4e27 Compare August 21, 2026 04:25
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status

Rebased onto current main and reviewed this as an authority change, not an ergonomics tweak. Review/fix loop returned clean. One in-scope security contract fix was pushed.

What this PR does

Bare cursor-agent queued startups now mint ORCA_AGENT_LAUNCH_TOKEN, and a retired Cursor pane can restart on beforeSubmitPrompt / sessionStart so a completed stop can settle to done. Plain shell commands stay tokenless. A completed stop is not a new-turn proof and cannot stamp a sibling pane.

Review fix pushed

queueTabStartupCommand no longer mints a leftover token when launchConfig is present on an unrecognized command (token without ORCA_AGENT_LAUNCH_TOKEN in env). The helper is the sole mint.

Pinned extra tests:

  • captured ORCA_AGENT_LAUNCH_TOKEN cannot win on resume-shaped queue (fresh token overwrites)
  • sibling tabs get distinct tokens
  • cursor-agent --foo / codex exec stay tokenless
  • unrecognized command + launchConfig stays tokenless

The resume captured-vs-changed test was not loosened: CODEX_PROFILE still must be captured, env keys are exactly CODEX_PROFILE + ORCA_AGENT_LAUNCH_TOKEN, and the token is the queued launchToken.

Intentionally not done

Did not lift the retired-pane gate to the full isNewTurnEvent map. That classifier is for observation stamping; using it here unfences a closed tab's pane after closedAgentStatusTabIds LRU eviction (STA-4114). Cursor stays the special-case next to Claude UserPromptSubmit / SessionStart.

Checks

Visual proof

Hook-server ingest has no new chrome. These are uncropped full-window shots of the terminal surface in the review build, plus a queued startup that returned to idle.

15695-electron-app.png

15695-electron-terminal-surface.png

Remaining gaps (not blockers)

  • Cursor is not installed on this host, so the live Working → idle settle after a completed Cursor stop was not exercised in the app. Covered by unit tests (local HTTP + ingestRemote).
  • Windows ConPTY env injection into Cursor panes is still unvalidated (original report surface).
  • Complementary hole fix(pi): settle OMP status from the agent-end contract #15658 (nested-shell OSC 133;D retiring launch authority while the agent is still foreground) is out of scope.

Landable from this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing: its issue #12686 is closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Some Cursor panes remain Working despite completed stop hooks

1 participant