Repository navigation
fix(stats): count agent sessions from hook transitions, not OSC titles (STA-2445) - #14657
Conversation
📝 WalkthroughWalkthroughThe change replaces PTY-based agent detection with hook-status session tracking. A new recorder classifies live and terminal states, handles pane and connection cleanup, and limits stored mirrors. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 09fc892e-b271-43bc-acf1-81b6ca462530
📒 Files selected for processing (10)
src/main/index.tssrc/main/runtime/orca-runtime.tssrc/main/stats/agent-detector-resurrection-leak.test.tssrc/main/stats/agent-detector.test.tssrc/main/stats/agent-detector.tssrc/main/stats/agent-session-transition-recorder.test.tssrc/main/stats/agent-session-transition-recorder.tssrc/main/stats/collector.tssrc/main/stats/stats-title-detection-independence.test.tssrc/main/stats/types.ts
💤 Files with no reviewable changes (4)
- src/main/stats/agent-detector.test.ts
- src/main/stats/agent-detector-resurrection-leak.test.ts
- src/main/stats/agent-detector.ts
- src/main/runtime/orca-runtime.ts
| if (transition === 'none' && previous?.state === event.payload.state) { | ||
| // Refresh recency without touching session state so a long-running pane | ||
| // isn't evicted ahead of an idle one. | ||
| this.touch(event.paneKey, previous) | ||
| return |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Refresh connectionId when the state is unchanged.
A working pane can move to a new connection without a state transition. This path preserves the old connectionId. A clear for the new connection then cannot close the active session, so its duration continues until a later status or quit flush.
Proposed fix
if (transition === 'none' && previous?.state === event.payload.state) {
- this.touch(event.paneKey, previous)
+ this.touch(event.paneKey, {
+ ...previous,
+ connectionId: event.connectionId
+ })
return
}Add a test that changes connectionId on an unchanged working event, then clears the new connection.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (transition === 'none' && previous?.state === event.payload.state) { | |
| // Refresh recency without touching session state so a long-running pane | |
| // isn't evicted ahead of an idle one. | |
| this.touch(event.paneKey, previous) | |
| return | |
| if (transition === 'none' && previous?.state === event.payload.state) { | |
| // Refresh recency without touching session state so a long-running pane | |
| // isn't evicted ahead of an idle one. | |
| this.touch(event.paneKey, { | |
| ...previous, | |
| connectionId: event.connectionId | |
| }) | |
| return |
| import { join } from 'node:path' | ||
| import { describe, expect, it } from 'vitest' | ||
|
|
||
| const STATS_DIR = join(__dirname) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Check the runtime integration source and multiline imports.
statsSourceFiles() only scans src/main/stats. It does not inspect src/main/index.ts, where the stats pipeline subscribes to agent status. Also, splitting the source before matching misses multiline imports.
A title detector can be wired into the runtime path with a multiline import and this test will pass. Scan complete source text and include the runtime stats entry point in the checked file set.
Also applies to: 29-45
Review statusState: What the review loop established. The stats counters were near-zero not because a subscription was missing, but because The replacement (
Validation — what was and was not done. Done, and this is the substantive part: a dual-record comparison before switchover. The work landed in two commits —
The detector's higher total is not better coverage — two of its three are wrong (one phantom TUI, one duplicate) and the one real agent is the one it never saw. The reconnect row is structural: Note the harness is deleted in commit 2 along with the detector it measures, so it is reviewable in Tests were proven non-vacuous by mutation: removing the same-state snapshot guard, letting a replay open a session, removing both Scoped checks: Not done — read before merging:
Known limit worth carrying: on an SSH transient disconnect, the batch clear closes sessions at its stamped Wire / compat: no wire change; this subscribes to an existing main-process listener. Supersedes: nothing. |
…k transitions
Adds an AgentSessionTransitionRecorder that derives agent-session start/stop
boundaries from agent-hook status transitions, and a side-by-side comparison
that feeds both pipelines into a real StatsCollector.
Nothing is rewired yet — this commit only measures the delta:
title detector canonical
hook-only agent 0 1
braille-spinner non-agent TUI 1 0
one agent, one reconnect 2 1
totals 3 2
Refs #10201, STA-2445.
… title detector Switches StatsCollector off AgentDetector and onto the canonical agent-hook status stream, then removes the detector and its raw-PTY invocation. - main/index.ts subscribes the recorder to subscribeEnrichedStatus and subscribePaneStatusClear, next to where StatsCollector is constructed. - orca-runtime.ts no longer feeds raw PTY bytes to a stats detector. - StatsCollector keys sessions on a stable pane key, not a per-spawn ptyId. Fixes #10201, refs STA-2445.
f0cfcd7 to
5c4d084
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/stats/stats-title-detection-independence.test.ts (1)
1-10: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the file header comment.
Lines 1-10 use ten lines for one regression rationale. Keep one concise comment that states the OSC-title spinner false-positive risk.
Proposed change
-// Regression guard for the second half of `#10201`. -// -// The deleted AgentDetector read OSC titles, and detectAgentStatusFromTitle -// classifies ANY braille/quarter-circle spinner glyph as `working` with no -// agent-name requirement (agent-title-status.ts). That made every spinner TUI — -// `⠋ npm run build`, a progress bar, a REPL — a counted "agent spawned". -// -// Stats now derive sessions from agent-hook transitions only. This test fails if -// title detection is ever wired back into the stats pipeline, which is the only -// way that false positive can return. +// Guard statistics against OSC-title spinner false positives.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bc3a0a34-a17a-44f4-a5b3-23286419ec0a
📒 Files selected for processing (10)
src/main/index.tssrc/main/runtime/orca-runtime.tssrc/main/stats/agent-detector-resurrection-leak.test.tssrc/main/stats/agent-detector.test.tssrc/main/stats/agent-detector.tssrc/main/stats/agent-session-transition-recorder.test.tssrc/main/stats/agent-session-transition-recorder.tssrc/main/stats/collector.tssrc/main/stats/stats-title-detection-independence.test.tssrc/main/stats/types.ts
💤 Files with no reviewable changes (4)
- src/main/stats/agent-detector.ts
- src/main/stats/agent-detector-resurrection-leak.test.ts
- src/main/runtime/orca-runtime.ts
- src/main/stats/agent-detector.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- src/main/stats/types.ts
- src/main/stats/collector.ts
- src/main/stats/agent-session-transition-recorder.ts
- src/main/stats/agent-session-transition-recorder.test.ts
- src/main/index.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 3 remain after this review.
…s (STA-2445) (stablyai#14657) * test(stats): dual-record the OSC-title detector against canonical hook transitions Adds an AgentSessionTransitionRecorder that derives agent-session start/stop boundaries from agent-hook status transitions, and a side-by-side comparison that feeds both pipelines into a real StatsCollector. Nothing is rewired yet — this commit only measures the delta: title detector canonical hook-only agent 0 1 braille-spinner non-agent TUI 1 0 one agent, one reconnect 2 1 totals 3 2 Refs stablyai#10201, STA-2445. * fix(stats): count agent sessions from hook transitions and delete the title detector Switches StatsCollector off AgentDetector and onto the canonical agent-hook status stream, then removes the detector and its raw-PTY invocation. - main/index.ts subscribes the recorder to subscribeEnrichedStatus and subscribePaneStatusClear, next to where StatsCollector is constructed. - orca-runtime.ts no longer feeds raw PTY bytes to a stats detector. - StatsCollector keys sessions on a stable pane key, not a per-spawn ptyId. Fixes stablyai#10201, refs STA-2445.
…s (STA-2445) (stablyai#14657) * test(stats): dual-record the OSC-title detector against canonical hook transitions Adds an AgentSessionTransitionRecorder that derives agent-session start/stop boundaries from agent-hook status transitions, and a side-by-side comparison that feeds both pipelines into a real StatsCollector. Nothing is rewired yet — this commit only measures the delta: title detector canonical hook-only agent 0 1 braille-spinner non-agent TUI 1 0 one agent, one reconnect 2 1 totals 3 2 Refs stablyai#10201, STA-2445. * fix(stats): count agent sessions from hook transitions and delete the title detector Switches StatsCollector off AgentDetector and onto the canonical agent-hook status stream, then removes the detector and its raw-PTY invocation. - main/index.ts subscribes the recorder to subscribeEnrichedStatus and subscribePaneStatusClear, next to where StatsCollector is constructed. - orca-runtime.ts no longer feeds raw PTY bytes to a stats detector. - StatsCollector keys sessions on a stable pane key, not a per-spawn ptyId. Fixes stablyai#10201, refs STA-2445.
…s (STA-2445) (stablyai#14657) * test(stats): dual-record the OSC-title detector against canonical hook transitions Adds an AgentSessionTransitionRecorder that derives agent-session start/stop boundaries from agent-hook status transitions, and a side-by-side comparison that feeds both pipelines into a real StatsCollector. Nothing is rewired yet — this commit only measures the delta: title detector canonical hook-only agent 0 1 braille-spinner non-agent TUI 1 0 one agent, one reconnect 2 1 totals 3 2 Refs stablyai#10201, STA-2445. * fix(stats): count agent sessions from hook transitions and delete the title detector Switches StatsCollector off AgentDetector and onto the canonical agent-hook status stream, then removes the detector and its raw-PTY invocation. - main/index.ts subscribes the recorder to subscribeEnrichedStatus and subscribePaneStatusClear, next to where StatsCollector is constructed. - orca-runtime.ts no longer feeds raw PTY bytes to a stats detector. - StatsCollector keys sessions on a stable pane key, not a per-spawn ptyId. Fixes stablyai#10201, refs STA-2445.
…5852) * perf(stats): stop retaining and rewriting the raw stats event log (#35544) The collector kept up to 10K raw events (~203 B each since #14657 switched meta to pane keys and added worktree ids) and re-serialized the whole ~2 MB file every 5 s. No consumer reads events; persist aggregates only, keep the v1 file shape with an empty events array, and compact legacy files on load. * test(stats): use a small event burst for the retained-size bound
ELI5
Orca's stats page said you'd spawned almost no agents and they'd worked almost no time. That's because the counter wasn't watching agents — it was watching the text in the terminal's title bar and guessing. Agents that report their status properly (over hooks) but don't paint a fancy title were invisible to it. Meanwhile a spinning
⠋fromnpm run buildlooked exactly like an agent, so it got counted as one.Now the counter listens to the same agent status stream the sidebar and dashboard already use. It counts changes ("this agent just started working", "this agent just finished"), not reports — so when Orca reconnects and the host re-sends everything it remembers, nothing gets counted twice.
What Changed
New:
src/main/stats/agent-session-transition-recorder.ts— mirrors the last hook state per pane and forwards start/stop edges toStatsCollector. Two guards carry the whole contract:restoredUnconfirmedworkingdescribes work that began in an earlier runtime, so crediting it would mint a phantom spawn. A replayed terminating state still closes a session — that is how a client learns about a completion it missed while disconnected, and refusing it would strand the session open until quit.Also ignores
providerSessionOnlyevents: they carry astatefield but are identity-only resume-metadata refreshes with no turn-state transition.Wired in
main/index.tsbeside theStatsCollectorconstruction, tosubscribeEnrichedStatus+subscribePaneStatusClear(pane teardown and the SSH transient-disconnect batch close out open sessions rather than leaking their duration to the quit flush).Deleted:
src/main/stats/agent-detector.ts(295 lines) and its raw-PTY invocation inorca-runtime.ts(onDataon every chunk, plusonExit). Stats no longer parse a single byte of terminal output.StatsCollectornow keys sessions on a stable pane key instead of a per-spawnptyId; the eventmetafield is renamedptyId→sessionKey(internal log, no readers outside the stats module).Why
AgentDetectorread raw PTY bytes, pulled ordinary OSC titles out of them, and calleddetectAgentStatusFromTitle. Hook-only transitions never entered that path at all — so the near-zero counters weren't a missing subscription, they were a second, separate truth store.The detector was provably wrong in both directions:
agent-detector.ts:141-144returned early whenever the title didn't classify. An agent reporting cleanly over hooks in a pane showing an ordinary shell title contributed nothing.detectAgentStatusFromTitlereturns'working'for any braille or quarter-circle spinner glyph, with no agent-name requirement (agent-title-status.ts:192-194). Every spinner TUI was an "agent spawned".Dual-record comparison (the measured delta)
Per the review recommendation this landed in two commits: the first adds the recorder alongside the detector with a side-by-side harness feeding both into a real
StatsCollector, and changes no behavior. The second switches over and deletes. The measured aggregates:⠋ npm run build)The detector's higher total is not better coverage. Two of its three are wrong — one phantom TUI and one duplicate — and the one real agent is the one it never saw. The reconnect row is structural:
ptyIds are per-spawn UUIDs that are never reused (agent-detector.ts:78), so restoring buffered output into a fresh PTY re-runs the wholeUNKNOWN → AGENTfirst-classification. Pane keys are stable across reconnect.Shipped as one PR because the comparison came out clean and unambiguous in every direction. The comparison harness is deleted in commit 2 along with the detector it measures, so it is reviewable in
bc0503b9rather than in the squashed diff.On idempotency
Counting transitions, not snapshots is the design constraint, and the prior art is why. #14610 fixed a replayed status re-arming a live staleness timer; STA-3524 covers cached replays re-firing task-complete notifications. Both are the same shape: a re-delivered snapshot treated as news. A snapshot-counting stats path would inflate on every WSL relay reconnect and every host-side relay restart. Both guards are mutation-tested below.
Linked Issue
Fixes #10201
Refs STA-2445
Visual Proof
N/A— main-process metric accounting with no rendered surface of its own. The Stats view readsStatsCollector.getSummary()unchanged; only the numbers flowing into it change, and a meaningful before/after would need weeks of real usage rather than a screenshot. The measured delta table above is the evidence.Testing
src/main/stats/agent-session-transition-recorder.test.tsandstats-title-detection-independence.test.tsdrive realStatsCollectoraggregates against a tempuserDatadir. Required coverage:Plus: repeated working/done cycles count one session per turn;
waiting/blockedare boundaries, not agent work;providerSessionOnlyrefreshes are inert; pane teardown and SSH batch clears close open sessions; the mirror is bounded and closes what it evicts.Proven non-vacuous — each guard was mutated and a test killed it:
does not double-count a re-emitted live status mid-turn,treats an unchanged state as a snapshotlive = true)never opens a session from a replayed or disk-restored working status,opens only on a live working edgeproviderSessionOnlyguardsignores identity-only provider-session refreshesno stats source imports a title-based agent detectorScoped checks run (full typecheck skipped — OOM risk; all changes are in
src/main, covered by the node project):tsc --noEmit -p config/tsconfig.node.json— cleanvitest src/main/stats src/main/agent-hooks— 635 passedvitest src/main/runtime— 4135 passedcheck-changed-code-quality.mjs— 0 new findings across 6 files (native, type-aware, React Doctor)check-max-lines-ratchet.mjs— OK, no new bypassesoxlint verified live by injecting a violation (it prints nothing when clean)
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Review
clearedAtrather than leaving them open. A remote agent still working through a blip is under-counted rather than credited an unbounded idle span, which is the safe direction for "time agents worked".orca-stats.jsonschema version and aggregate fields are unchanged, so existing totals carry forward. Only themetakey on newly appended events changes (ptyId→sessionKey); nothing reads that field back.onPtyDatapath, and replaces it with aMaplookup on an event that already fires.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author