Skip to content

fix(runtime): wait for Grok background tasks - #9915

Closed
OnlyYu1996 wants to merge 1 commit into
stablyai:mainfrom
OnlyYu1996:codex/issue-9905-grok-background-idle
Closed

OnlyYu1996 wants to merge 1 commit into
stablyai:mainfrom
OnlyYu1996:codex/issue-9905-grok-background-idle

Conversation

@OnlyYu1996

@OnlyYu1996 OnlyYu1996 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Keep tui-idle pending while a confirmed Grok session still reports active background tasks.
  • Read the latest Grok task counters from the bounded retained terminal tail so status is not lost when the short preview scrolls.
  • Keep blocked and permission prompts higher priority than the background-task gate across PTY, leaf, daemon, and fallback-poll paths.

Fixes #9905

Screenshots

No visual change.

Testing

  • pnpm lint
    • Touched-file Oxlint passed.
  • pnpm typecheck
    • pnpm typecheck:node passed.
  • pnpm test
    • Related runtime and shared parser tests passed: 2 files, 859 tests.
  • pnpm build
    • Not run; this change does not alter build configuration or bundled assets.
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Additional 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

  • Grok background-task detection is deliberately disabled unless the runtime can identify the session as Grok.
  • No UI, platform-specific, remote-only, or Git-provider-specific behavior is introduced.
  • X/Twitter: N/A (no account)

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.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main runtime change: waiting for Grok background tasks before resolving idle.
Description check ✅ Passed The description matches the template with Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections.

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

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 win

Background-task gate short-circuits blocked/permission detection in the fallback polls.

In both startTuiIdleFallbackPoll (leaf) and startPtyTuiIdleFallbackPoll (pty), the new hasActiveGrokBackgroundTasks(...) check is the very first thing evaluated in the poll body and returns immediately when true — before detectTerminalWaitBlockedReason runs 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 registered tui-idle waiter 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.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/grok-background-task-status.test.ts
  • src/shared/grok-background-task-status.ts

Comment thread src/main/runtime/orca-runtime.ts Resolved
@OnlyYu1996

Copy link
Copy Markdown
Contributor Author

Updated in d626f3bcd after review:

  • Grok counters are read from the bounded retained tail instead of the short preview.
  • Matching output is ignored unless the runtime identifies a Grok session.
  • Blocked and permission prompts are checked before the background-task gate in both leaf and PTY fallback polls.
  • The PR is rebased onto current upstream/main (41751dd90).

Validation: 2 related test files / 859 tests, typecheck:node, touched-file Oxlint/Oxfmt, max-lines ratchet, reliability gates, and git diff --check all pass.

@OnlyYu1996

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
Comment on lines +4 to +9
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 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-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR prevents tui-idle from resolving while a Grok session still has active background tasks by inserting a regex-based counter check (Tasks N + watching · N commands) ahead of every idle-resolution path. Grok identity is confirmed via launch agent, foreground process name, or OSC title before the counter logic is applied, so non-Grok sessions are unaffected.

  • Adds src/shared/grok-background-task-status.ts with hasActiveGrokBackgroundTasks, which reads the last occurrence of each counter pattern from the retained terminal tail to handle scrolled-away output.
  • Inserts the background-task gate into six resolution sites (PTY synchronous path, PTY OSC-event path, PTY daemon poll, leaf synchronous path, leaf OSC-event path, leaf daemon poll), with the blocked-prompt check taking priority in every site.
  • As a side effect, the daemon PTY poll path now evaluates blockedReason before lastAgentStatus === 'idle', fixing a pre-existing ordering issue where a cached idle status could shadow a live permission prompt.

Confidence Score: 4/5

Safe 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 lastAgentStatus === 'idle' to hold simultaneously. The omission of detectTerminalWaitBlockedReason inside resolveTuiIdleWaiters is a pre-existing gap that this PR makes slightly more visible but does not introduce. New tests cover all advertised scenarios.

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.

Important Files Changed

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]
Loading

Comments Outside Diff (1)

  1. src/main/runtime/orca-runtime.ts, line 27930-27954 (link)

    P2 resolveTuiIdleWaiters skips blocked-reason check before resolving

    The early-return for active Grok background tasks is correct, but when background tasks are absent the function immediately resolves all tui-idle waiters via buildTerminalWaitResult without first calling detectTerminalWaitBlockedReason. If a permission prompt appears at the exact moment Grok clears its task counters, the waiter resolves as idle instead of surfacing blockedReason. 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

@OnlyYu1996 OnlyYu1996 closed this Aug 28, 2026
@OnlyYu1996
OnlyYu1996 deleted the codex/issue-9905-grok-background-idle branch August 28, 2026 06:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

terminal wait tui-idle reports success while Grok background task is still active

3 participants