Skip to content

fix(pi): bind the titlebar spinner to its session incarnation (STA-4246) - #14618

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/pi-status-p0s-4246
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/pi-status-p0s-4246

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

ELI5

Orca's π spinner asked pi "what's this session called?" 12 times a second. If you forked or switched sessions mid-turn, the next tick asked a session that no longer existed, pi threw, and because the question was being asked from inside a timer there was nobody around to catch it — so the whole agent died. Now the spinner asks once per turn, and lets go of the session the moment it's replaced.

What Changed

orca-titlebar-spinner.ts (regenerated from src/main/pi/titlebar-extension-source.ts on every launch):

  • The animation frame no longer calls pi.getSessionName(). The session name and cwd are snapshotted once per turn at agent_start; the frame is now pure string formatting plus one setTitle.
  • New session_start handler unbinds the running animation and repaints the base title. session_start is the runtime's signal for new / fork / switch / resume / reload — exactly the replacements that invalidate the captured ctx.
  • The next agent_start re-arms the spinner against the incoming ctx, so the spinner survives a session replacement instead of dying with it.
  • A failed setTitle unbinds the timer instead of propagating, and a stale getSessionName latches so a dead handle isn't re-probed every turn boundary (the last known name is kept, so the title degrades rather than losing the name).
  • The interval is unref'd so a cosmetic animation can't hold a shutting-down agent alive.

Why

The frame ran pi.getSessionName() on the module-captured handle. After newSession / fork / switchSession / reload, pi's assertActive guard rejects that handle. A setInterval callback is a top-level stack frame with no caller, so the throw became an uncaughtException and terminated pi.

Is catching the stale-handle error the right contract, or should the extension unbind? Unbind. Three reasons, and the PR does both — but with catching as the backstop, not the fix:

  1. The defect is lifetime, not error handling. The timer is bound to one session incarnation (ctx) but its lifetime was governed by turn events (agent_start/agent_end) belonging to a different lifetime. Session replacement ends the ctx without ending the turn, so the timer outlived its owner. The fix is to make the timer's lifetime a subset of its ctx's — which is what the session_start unbind does.
  2. The runtime's throw is deliberate. assertActive is a use-after-dispose guard; its message literally instructs the extension not to hold the handle across replacement. Treating that as noise to swallow keeps violating the contract and just hides it.
  3. Orca's own sibling extension already models this. agent-status-handler-source.ts registers session_start and branches on event.reason. The titlebar extension not listening to session_start at all is the actual gap.

The try/catch around setTitle stays — not because stale ctx should be ignored, but because a timer callback structurally cannot let a throw reach a caller. Any error there is fatal to the host process, so that boundary is required regardless of this bug. It must not be the only thing standing between a routine session switch and a dead agent.

On the alternative in #14412 (wrap the existing calls in try/catch and clear the timer): it converts the crash into a permanent silent regression. Once the catch fires, the module-captured pi handle stays stale, so stopAnimation also swallows and never repaints the base title — the titlebar is left frozen mid-braille-frame — and every subsequent turn's first frame catches and clears immediately. The spinner never animates again for the life of the process. That's why this PR fixes the binding instead.

Linked Issue

Fixes #14400

Visual Proof

N/A — no Orca UI surface changes. This is the generated pi/OMP extension that writes the terminal title; the spinner renders identically during a live turn. The only behavioral differences are on the replacement path (previously: process death).

Testing

Limitation stated plainly: the pi CLI is not installed on this machine, so this was fixed without a live reproduction. I did not observe the crash or the fix in a running pi process, and I am not claiming otherwise.

What I did instead:

  • Regression coverage proven non-vacuous. All 9 behavioral specs in titlebar-extension-source.test.ts were run against the pre-fix source and all 9 fail; against the fix all pass. The generated extension is executed for real in a VM sandbox (titlebar-extension-test-harness.ts, mirroring the harness pattern from fix(agents): settle and surface the OMP terminal lifecycle (#14278) #14605), driven by a pi handle and ctx that throw pi's exact assertActive message. The crash spec fails against old code precisely because the throw escapes the timer.
  • Covered: no-op outside a pane; animation + base-title restore; frame never reads the session handle; unbind on session_start; re-arm on the next turn after replacement; unbind-not-crash on a replaced ctx; stale-handle degradation without re-probing; last-known-name retention; session_shutdown with both handle and ctx stale; interval unref.
  • Per-kind install coverage for the pi/OMP/prime-agent triple: the spinner is shipped to pi and OMP and both get the fixed source (new spec in titlebar-extension-service.test.ts); prime-agent never receives this extension, already asserted by the existing Prime spec. The source string is identical across kinds, so there is no per-kind divergence to test beyond installation.
  • vitest run src/main/pi/ — 73 passed.
  • pnpm run typecheck:node — passed. Full typecheck deliberately not run (OOM risk on this machine); changes are confined to src/main.
  • oxlint + oxfmt on changed files, plus pre-commit hooks (including React Doctor) — clean.

Supporting evidence for the design, since I could not test against pi: I grepped the installed OMP binary (the pi-compatible runtime) and confirmed session_start is emitted with a reason and previousSessionFile, with reason values including start, new, fork, switch, resume, and handoff. That is the replacement signal this fix binds to. Orca's own status extension already depends on session_start carrying reason === 'reload'.

  • I manually tested these changes locally
  • Automated tests added/updated

Platforms: the generated extension is a single source string, identical on macOS / Linux / Windows / SSH; the cwd label already splits on both separators. Folder workspaces and remote hosts are unaffected — no wire, IPC, or env surface changes.

AI Disclosure

Review

  • Security: no new IPC, env, credentials, or network surface.
  • Cross-platform: source string only; cwd label splits on / and \ as before.
  • Remote SSH: none — this runs inside the agent process, and no client/host wire field changed.
  • Mobile: N/A.
  • Backwards compatibility: the extension is rewritten on every launch, so there is no mixed-version window. Behavior during a normal turn is byte-identical in output; only the replacement path differs.
  • Performance: strictly less work per frame — one setTitle instead of a getSessionName() + process.cwd() + split/filter on every 80ms tick.

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) — scoped checks passed (see Testing); full suites left to CI

Author

  • X / Twitter: @BrennanKB5

The 80ms spinner frame called pi.getSessionName() on the module-captured
handle. After newSession/fork/switchSession/reload that handle is invalid,
so the next frame threw pi's assertActive guard out of a setInterval
callback — a top-level frame with no caller to catch it — and the
uncaughtException killed the agent process.

Fix the lifetime, not the throw: read the session name and cwd once per
turn so the frame never touches a replaceable handle, unbind on
session_start (the runtime's new/fork/switch/resume/reload signal) so no
frame can run against a replaced ctx, and re-arm on the next agent_start
with the incoming ctx. A failed title write unbinds rather than escalating,
since a timer callback can never let a throw reach a catch.
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The titlebar extension now caches session and working-directory labels, handles invalidated session handles, guards title writes, and stops failed animations. Session replacement resets state and writes a static title. A VM-based harness and Vitest tests cover runtime behavior, timers, stale contexts, shutdown, and interval unref. Integration coverage verifies installation for Pi and OMP.

Merge Risk: 🔵 Low · up to fe99c

The spinner is now tied to the active session and avoids crashes during session replacement, with focused automated coverage. Merge readiness is generally good, but the OMP installation test should be isolated so it cannot pass by reading a stale Pi-generated artifact if the OMP write is unsuccessful.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes binding the Pi titlebar spinner to the correct session incarnation.
Description check ✅ Passed The description covers all required sections, explains the fix, links issue #14400, documents testing limits, and addresses review concerns.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
📝 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: 1

🧹 Nitpick comments (3)
src/main/pi/titlebar-extension-source.ts (1)

112-118: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider clearing sessionLabel when the re-probe fails on session_start.

session_start resets handleStale and re-probes the handle. If pi.getSessionName() throws, handleStale latches again and sessionLabel keeps the previous session's name. The static title then shows the old name for the replacement session, and the next agent_start animates that same wrong name.

Inside a single turn, keeping the last good label is correct. Across a session replacement, the identity has changed, so a cwd-only title is more accurate than a name from the previous session.

♻️ Optional adjustment to drop the label when the replacement handle is dead
     "  pi.on('session_start', async (_event, ctx) => {",
     '    clearTimer()',
     '    handleStale = false',
     '    cwdLabel = getCwdLabel()',
+    '    sessionLabel = null',
     '    refreshSessionLabel()',
     "    writeTitle(ctx, formatTitle('', sessionLabel, cwdLabel))",
     '  })',
src/main/pi/titlebar-extension-test-harness.ts (1)

71-80: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The unref fallback can make the unref assertion pass without a real unref.

If the timer handle has no unref, line 74 substitutes () => handle and still pushes a spy. The extension guards its call with typeof timer.unref === 'function', so it then calls the fabricated function. intervalUnrefs[0] is therefore recorded as called even though the real handle never supported unref.

Only wrap an existing unref so the spec fails if the handle stops exposing one.

♻️ Optional change to wrap only a real `unref`
-    if (handle && typeof handle === 'object') {
-      const original = typeof handle.unref === 'function' ? handle.unref.bind(handle) : () => handle
-      const spy = vi.fn(original)
+    if (handle && typeof handle === 'object' && typeof handle.unref === 'function') {
+      const spy = vi.fn(handle.unref.bind(handle))
       handle.unref = spy
       intervalUnrefs.push(spy)
     }
src/main/pi/titlebar-extension-service.test.ts (1)

192-192: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import the filename constant instead of repeating the literal.

titlebar-extension-source.ts exports ORCA_PI_EXTENSION_FILE = 'orca-titlebar-spinner.ts'. Use it here so a rename cannot silently break this test.

♻️ Optional change
-      const source = readFileSync(join(piHome, 'extensions', 'orca-titlebar-spinner.ts'), 'utf-8')
+      const source = readFileSync(join(piHome, 'extensions', ORCA_PI_EXTENSION_FILE), 'utf-8')

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c1983506-b780-4ec1-acc8-8e48676ae59a

📥 Commits

Reviewing files that changed from the base of the PR and between 9bb8836 and fe99c83.

📒 Files selected for processing (4)
  • src/main/pi/titlebar-extension-service.test.ts
  • src/main/pi/titlebar-extension-source.test.ts
  • src/main/pi/titlebar-extension-source.ts
  • src/main/pi/titlebar-extension-test-harness.ts

Comment on lines +190 to +201
for (const kind of ['pi', 'omp'] as const) {
svc.buildPtyEnv(`pty-spinner-${kind}`, piHome, kind)
const source = readFileSync(join(piHome, 'extensions', 'orca-titlebar-spinner.ts'), 'utf-8')
expect(source).toContain("pi.on('session_start'")

// The crashing frame read the session handle on every tick; it must not anymore.
const bodyStart = source.indexOf('timer = setInterval(')
const bodyEnd = source.indexOf('}, FRAME_INTERVAL_MS)')
expect(bodyStart).toBeGreaterThan(-1)
expect(bodyEnd).toBeGreaterThan(bodyStart)
expect(source.slice(bodyStart, bodyEnd)).not.toContain('pi.getSessionName()')
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Determine where the titlebar spinner extension is written per PiAgentKind.
set -euo pipefail

fd -t f 'titlebar-extension-service.ts' -x ast-grep outline {} --items all

fd -t f 'titlebar-extension-service.ts' -x rg -n -C 12 \
  'installManagedExtensions|getSourceOverlayDir|ORCA_PI_EXTENSION_FILE|extensions' {}

Repository: stablyai/orca

Length of output: 8483


🏁 Script executed:

#!/bin/bash
set -euo pipefail

test_file="src/main/pi/titlebar-extension-service.test.ts"
service_file="src/main/pi/titlebar-extension-service.ts"

printf '%s\n' '--- test context ---'
sed -n '140,220p' "$test_file"

printf '%s\n' '--- write/build implementations ---'
sed -n '90,225p' "$service_file"

Repository: stablyai/orca

Length of output: 8906


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

service = Path("src/main/pi/titlebar-extension-service.ts").read_text()
test = Path("src/main/pi/titlebar-extension-service.test.ts").read_text()

assert "const extensionsDir = join(sourceAgentDir, 'extensions')" in service
assert "join(extensionsDir, ORCA_PI_EXTENSION_FILE)" in service
assert "getPiTitlebarExtensionSource()" in service
assert "if (kind !== 'prime-agent')" in service
assert "const source = readFileSync(join(piHome, 'extensions', 'orca-titlebar-spinner.ts')" in test

write_call = "this.writeManagedExtension(\n        join(extensionsDir, ORCA_PI_EXTENSION_FILE)"
assert service.count(write_call) == 1

print("titlebar target: sourceAgentDir/extensions for both pi and omp")
print("titlebar source: getPiTitlebarExtensionSource() is not kind-specific")
print("test read path: piHome/extensions/orca-titlebar-spinner.ts for both iterations")
print("shared-path false-positive risk: present if the OMP write fails or is skipped")
PY

Repository: stablyai/orca

Length of output: 440


Prevent the OMP iteration from reusing the Pi artifact

buildPtyEnv writes both kinds to piHome/extensions. However, writeManagedExtension can fail or skip silently, so the OMP iteration can read the file left by the Pi iteration. Remove orca-titlebar-spinner.ts before each iteration so an OMP write failure fails the test.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Staleness check (coordinator, 2026-08-20) — this is safe to rebase and land; the age is not a risk here.

This PR is 308 commits behind origin/main and last touched 2026-08-14, so its green check is against a six-day-old base and is not by itself evidence the merged tree is green. I checked the merged result directly rather than trusting either the age or the clean merge:

  • git merge-tree against current origin/main: clean, no conflicts.
  • None of the four files it touches have changed on main since it branched — titlebar-extension-source.ts, titlebar-extension-source.test.ts, titlebar-extension-service.test.ts, titlebar-extension-test-harness.ts all have zero intervening commits. The distance is in unrelated areas.
  • I built the actual merge in a scratch worktree (origin/main + this branch) and ran it: src/main/pi 73 tests pass, pnpm typecheck clean, and orca-runtime.test.ts 1183 pass as a broader smoke.

So the 308-commit gap is cosmetic in this case. A rebase and a re-run should go green.

Related: this also covers STA-4394. That was filed separately for the same crash — the 80 ms orca-titlebar-spinner timer calling pi.getSessionName() after a reload, throwing stale extension generation after reload out of Timeout._onTimeout and killing the whole pi process. I confirmed it is one defect, not two, and deliberately did not open a second PR.

This approach is also the right one versus the community alternatives: #14412 and #14664 are try/catch-only, which is strictly worse — the spinner dies silently for the rest of the process. Unbinding on session_start and snapshotting the session name so the frame never calls getSessionName fixes the lifetime problem rather than muffling its symptom.

Recommend rebasing onto current main and landing it; it closes two P1 tickets.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as obsolete: main no longer has the code this PR changes, or already behaves as it intended. Main already contains the crash class. titlebar-extension-source.ts:135-148 paintTitle wraps getSessionName and process.cwd in try and clears the timers on a throw (#19533, bba68b1). :253 session_start clears all owned timers. #20035 (a93e0ae) retires stale timers across

(Stale-PR cleanup 2026-10-20, approved by Brennan. Reopen if something here is still missing on main.)

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]: orca-titlebar-spinner extension crashes pi with uncaughtException on stale ctx after session replacement

1 participant