Repository navigation
fix(pi): bind the titlebar spinner to its session incarnation (STA-4246) - #14618
brennanb2025 wants to merge 1 commit into
Conversation
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.
📝 WalkthroughWalkthroughThe 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 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)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/main/pi/titlebar-extension-source.ts (1)
112-118: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConsider clearing
sessionLabelwhen the re-probe fails onsession_start.
session_startresetshandleStaleand re-probes the handle. Ifpi.getSessionName()throws,handleStalelatches again andsessionLabelkeeps the previous session's name. The static title then shows the old name for the replacement session, and the nextagent_startanimates 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 valueThe
unreffallback can make the unref assertion pass without a realunref.If the timer handle has no
unref, line 74 substitutes() => handleand still pushes a spy. The extension guards its call withtypeof timer.unref === 'function', so it then calls the fabricated function.intervalUnrefs[0]is therefore recorded as called even though the real handle never supportedunref.Only wrap an existing
unrefso 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 valueImport the filename constant instead of repeating the literal.
titlebar-extension-source.tsexportsORCA_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
📒 Files selected for processing (4)
src/main/pi/titlebar-extension-service.test.tssrc/main/pi/titlebar-extension-source.test.tssrc/main/pi/titlebar-extension-source.tssrc/main/pi/titlebar-extension-test-harness.ts
| 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()') | ||
| } |
There was a problem hiding this comment.
🎯 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")
PYRepository: 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.
|
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
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 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 Recommend rebasing onto current main and landing it; it closes two P1 tickets. |
|
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.) |
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 fromsrc/main/pi/titlebar-extension-source.tson every launch):pi.getSessionName(). The session name and cwd are snapshotted once per turn atagent_start; the frame is now pure string formatting plus onesetTitle.session_starthandler unbinds the running animation and repaints the base title.session_startis the runtime's signal for new / fork / switch / resume / reload — exactly the replacements that invalidate the captured ctx.agent_startre-arms the spinner against the incoming ctx, so the spinner survives a session replacement instead of dying with it.setTitleunbinds the timer instead of propagating, and a stalegetSessionNamelatches 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).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. AfternewSession/fork/switchSession/reload, pi'sassertActiveguard rejects that handle. AsetIntervalcallback is a top-level stack frame with no caller, so the throw became anuncaughtExceptionand 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:
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 thesession_startunbind does.assertActiveis 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.agent-status-handler-source.tsregisterssession_startand branches onevent.reason. The titlebar extension not listening tosession_startat all is the actual gap.The
try/catcharoundsetTitlestays — 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/catchand clear the timer): it converts the crash into a permanent silent regression. Once the catch fires, the module-capturedpihandle stays stale, sostopAnimationalso 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:
titlebar-extension-source.test.tswere 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 apihandle and ctx that throw pi's exactassertActivemessage. The crash spec fails against old code precisely because the throw escapes the timer.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_shutdownwith both handle and ctx stale; intervalunref.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 tosrc/main.oxlint+oxfmton 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_startis emitted with areasonandpreviousSessionFile, with reason values includingstart,new,fork,switch,resume, andhandoff. That is the replacement signal this fix binds to. Orca's own status extension already depends onsession_startcarryingreason === 'reload'.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
/and\as before.setTitleinstead of agetSessionName()+process.cwd()+ split/filter on every 80ms tick.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred) — scoped checks passed (see Testing); full suites left to CIAuthor