Repository navigation
fix(runtime): wait for Grok background tasks - #9915
OnlyYu1996 wants to merge 1 commit into
Conversation
📝 WalkthroughWalkthroughAdds Grok background-task status parsing based on the latest task and command counters. Runtime TUI-idle detection now remains pending for PTY and leaf previews while active Grok background tasks are present, including fast paths, waiter resolution, and foreground polling. Tests cover active, inactive, retained, and partial status output, plus timeout, session isolation, blocked output, and eventual resolution after task counters clear. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)
26083-26169: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winBackground-task gate short-circuits blocked/permission detection in the fallback polls.
In both
startTuiIdleFallbackPoll(leaf) andstartPtyTuiIdleFallbackPoll(pty), the newhasActiveGrokBackgroundTasks(...)check is the very first thing evaluated in the poll body and returns immediately when true — beforedetectTerminalWaitBlockedReasonruns later in the same function. Everywhere else in this PR (the registration/fast-path branches at lines 13244-13438), blocked-reason detection is deliberately checked first, independent of the Grok gate. These polling loops are the only place a registeredtui-idlewaiter gets rechecked over time, so while Grok background tasks are active, a genuine permission/blocked prompt on the same terminal will never be surfaced via the poll — the waiter can only resolve once background tasks clear or the wait times out, even though the terminal is actually blocked on user input right now.🐛 Suggested reordering (leaf poll shown; apply symmetrically to the pty poll)
try { - if (hasActiveGrokBackgroundTasks(leaf.preview)) { - return - } - if (leaf.lastAgentStatus === 'idle') { + const leafWaitTextForBlockedCheck = buildTerminalWaitText( + leaf.tailBuffer, + leaf.tailPartialLine, + leaf.preview + ) + const blockedReason = detectTerminalWaitBlockedReason(leafWaitTextForBlockedCheck) + if (blockedReason) { + if (waiter.pollInterval) { + clearInterval(waiter.pollInterval) + waiter.pollInterval = null + } + this.resolveWaiter( + waiter, + buildTerminalWaitBlockedResult(waiter.handle, 'tui-idle', leaf, blockedReason) + ) + return + } + if (hasActiveGrokBackgroundTasks(leaf.preview)) { + return + } + if (leaf.lastAgentStatus === 'idle') { ...Also applies to: 26171-26238
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: afbe66a0-b366-4d8a-954d-91c1722ee14b
📥 Commits
Reviewing files that changed from the base of the PR and between 7304776 and 21a04e6b6ef5e5c8207d8832bcb5d43e3af6add9.
📒 Files selected for processing (4)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/shared/grok-background-task-status.test.tssrc/shared/grok-background-task-status.ts
|
Updated in
Validation: 2 related test files / 859 tests, |
|
@coderabbitai review |
✅ Action performedReview finished.
|
| function readLatestCount(text: string, pattern: RegExp): number | null { | ||
| let count: number | null = null | ||
| for (const match of text.matchAll(pattern)) { | ||
| count = Number(match[1]) | ||
| } | ||
| return count |
There was a problem hiding this comment.
Independent counter scans can misread across output frames
readLatestCount is called twice with two separate regexes, so taskCount and watchingCount each report the last occurrence of their own pattern independently. If Grok emits a new task header (Tasks 1) in one PTY data chunk and the corresponding watching · 1 command line arrives in the next chunk, there is a brief window where taskCount=1 but watchingCount=0 — the function returns false and tui-idle waiters could resolve prematurely before the watching counter catches up. The practical risk is low (Grok renders both lines in the same TUI frame, and the condition requires lastAgentStatus === 'idle' simultaneously), but a brief false-negative on task detection is possible in a split-chunk delivery scenario.
Greptile SummaryThis PR prevents
Confidence Score: 4/5Safe to merge — the change adds a well-gated detection layer and does not alter behavior for non-Grok sessions. The Grok session identification is multi-signal (launch agent, foreground process, OSC title) and the two-counter requirement keeps false positives low. The independent regex passes for task and watching counts can produce a brief false negative when a new task header and its watching line arrive in separate PTY chunks, but the window is narrow and a stale idle resolution requires Files Needing Attention: src/shared/grok-background-task-status.ts — the independent counter scans and the pre-existing gap in resolveTuiIdleWaiters are worth a second look.
|
| Filename | Overview |
|---|---|
| src/shared/grok-background-task-status.ts | New module: regex-based Grok background-task detection; logic is sound but both counters are scanned independently via separate regex passes, so they may reflect different output frames. |
| src/shared/grok-background-task-status.test.ts | New unit tests covering active detection, "latest-wins" counter semantics, non-Grok session gating, and single-counter rejection — all critical paths exercised. |
| src/main/runtime/orca-runtime.ts | Background-task gate inserted before every tui-idle resolution path (PTY, leaf, daemon fallback poll); blocked-reason check now correctly precedes lastAgentStatus === 'idle' in the daemon PTY poll path, fixing a pre-existing ordering bug. |
| src/main/runtime/orca-runtime.test.ts | Four new integration tests cover: background-task hold, non-Grok session isolation, blocked-prompt priority over background-task gate, and counter-clear resolution. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[PTY / Leaf data arrives] --> B[buildTerminalWaitText]
B --> C{detectTerminalWaitBlockedReason?}
C -- yes --> D[Resolve: blocked\nblockedReason surfaced]
C -- no --> E{isGrokRuntimeTerminal?\nlaunchAgent / foregroundAgent / OSC title}
E -- not Grok --> G
E -- is Grok --> F{hasActiveGrokBackgroundTasks?\ntaskCount > 0 AND watchingCount > 0}
F -- active tasks --> H[Return — waiter stays pending\n2s fallback poll will retry]
F -- no active tasks --> G{lastAgentStatus === 'idle'\nor known ready prompt?}
G -- yes --> I[Resolve: tui-idle satisfied]
G -- no --> J[Return — waiter stays pending]
Comments Outside Diff (1)
-
src/main/runtime/orca-runtime.ts, line 27930-27954 (link)resolveTuiIdleWaitersskips blocked-reason check before resolvingThe early-return for active Grok background tasks is correct, but when background tasks are absent the function immediately resolves all
tui-idlewaiters viabuildTerminalWaitResultwithout first callingdetectTerminalWaitBlockedReason. If a permission prompt appears at the exact moment Grok clears its task counters, the waiter resolves as idle instead of surfacingblockedReason. This pattern predates this PR (the other resolution sites added the blocked-reason gate here), so it's a pre-existing gap that this change doesn't worsen — but the new early-return makes the omission more visible now that this function is touched.
Reviews (1): Last reviewed commit: "fix(runtime): wait for Grok background t..." | Re-trigger Greptile
Summary
tui-idlepending while a confirmed Grok session still reports active background tasks.Fixes #9905
Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm typecheck:nodepassed.pnpm testpnpm buildAdditional repository gates passed: touched-file Oxfmt,
git diff --check, max-lines ratchet, and reliability gates.AI Review Report
The review checked the three reported failure modes: counters scrolling outside the 6-line preview, matching similar output from non-Grok CLIs, and blocked or permission prompts being hidden by the background-task gate. The implementation now scans the bounded retained tail only at wait registration, idle transitions, and the 2-second fallback poll; requires Grok identity from launch metadata, foreground-agent detection, or an explicit Grok title; and checks blocked state before the task gate. Regression tests cover each case.
The review also checked PTY and leaf handles, adopted/background PTYs, daemon-hosted terminals, SSH sessions, fallback polling, and repeated counter updates. Cross-platform compatibility was reviewed for macOS, Linux, and Windows. This change does not alter shortcuts, labels, filesystem paths, shell commands, Electron platform branches, or Git-provider behavior.
Security Audit
This change only parses already-retained terminal text and existing agent metadata. It adds no command execution, path handling, authentication, secrets, dependencies, network access, or IPC surface. The scanned text remains bounded by the existing 256 KiB retained-tail limit, and parser results do not leave the runtime process. No follow-up security work is needed.
Notes
ELI5
Waiting for Grok to be "idle" returned too early while background tasks were still running. tui-idle now stays pending until those tasks finish so automation does not inject the next step too soon.