Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(orchestrator/grok): Prevent spurious wake run after in-turn monitors #4218

Mergedmwolson(GitHub profile, opens in a new tab)merged 2 commits intot3code/codex-turn-mapping fromrefs/pull/4218/headmerged by juliusmarminge View on GitHub

Carried from another PR

This branch holds two commits. Only the first is this PR's own work.

  • fix(grok): Prevent spurious wake run after in-turn monitors — this PR.
  • fix(acp): Preserve wake evidence across an app-owned wake — carried on behalf of #4499 (fix/delegated-task-parent-wake). This PR introduces the only wakeBuffer and mid-turn-mark clears at the ACP startTurn site, so the exemption has to live here, but it is inert until #4499 lands because nothing else dispatches creationSource: "server". It is kept as a separate commit so it can be reviewed, or skipped, on its own.

Summary

  • Fixes a multiturn bug where the Grok adapter queued a spurious synthetic "Background task completed." continuation run while the original turn was still streaming, after the agent had already reported the monitor result in-turn.
  • Ensures injected <monitor-event> acknowledgement chatter for work already reported in-turn is never retained as wake evidence for later turns.
  • Adds four adapter tests covering the multiturn repro, mid-turn completion deferral, the legitimate unhandled-completion wake, and the settle-without-report hold interaction.

Problem and Fix

Problem and Why it HappenedFix
A x.ai/task_completed ext notification landing mid-turn reached applyLateBackgroundMutation, which had no notion of an active un-finalized root turn. With the running set empty and stale frames in wakeBuffer, it called offerContinuationRun and dispatched a "Background task completed." run (queue_after_active) while the original turn was still streaming its own report.Continuation offers are never made while a root turn is active and un-finalized. Completions that register mid-turn but are not handled in-turn are recorded in a new midTurnUnreportedCompletedTaskIds set, and finalizeTurn offers exactly one continuation after finalize when legitimate evidence remains (settled status completed, no running tasks). The arming also requires the prompt not to have settled, so the settled-held window still uses the pre-existing injected-report path.
After a turn that reported its monitor in-turn, the CLI's injected <monitor-event> turn hit the late-mutation path, which deleted the task id from the in-turn handled set. The subsequent injected ack chatter then failed the handled-chatter guard and was buffered as wake evidence, surviving into later turns (the buffer was intentionally not cleared at turn start).Late monitor-event mutations no longer erase in-turn handled marks, the handled-chatter guard runs before wake buffering, and stale wakeBuffer frames are cleared at non-continuation user-turn start. Frames cleared there cannot be legitimate: a genuinely unhandled completion is tracked by the mid-turn set and offered at finalize instead.

Defensive Fixes

Problem and Why it HappenedFix
In the late-mutation path, suppressPostSettleMonitorPrompt was set true and then unconditionally set false two lines later for terminal mutations on already-ended tasks, making the intent unreadable and the true branch dead.The suppress logic is rewritten as mutually exclusive running/terminal branches.
A stopped run's quarantine cleared the wake buffer and running set but would have left mid-turn unreported completions armed.quarantineStoppedRun also clears midTurnUnreportedCompletedTaskIds.
A completion armed pre-settle into midTurnUnreportedCompletedTaskIds survived the settle-hold: when the CLI's injected report streamed into the held turn, only pendingInjectedReport was cleared, so finalizeTurn still saw the armed id and offered a duplicate continuation right after the report projected (Bugbot round 1).When the injected report chunk streams, the delivered task ids are also removed from midTurnUnreportedCompletedTaskIds. If no report ever streams, the id survives and finalize offers exactly one wake, as before.
A midTurn-only continuation offer is made with an empty wakeBuffer (the buffer cannot grow while the root turn is active), so if the CLI's late frames had not arrived by the wake run's start, the empty drain finalized a blank continuation run immediately (Bugbot round 1).An empty-drain continuation now uses the same 3s deferred-finalize quiet window as a non-empty drain (when the flavor defers finalize for background work), letting late frames attach; flavors without the defer flag keep the immediate finalize so the turn cannot wedge.
This PR adds the only wakeBuffer clear at the start of a non-continuation turn. An orchestrator-injected wake is not a user turn: #4499 (fix/delegated-task-parent-wake) dispatches app-owned delegated-child wakes as creationSource: "server", which is non-continuation, so once both land such a wake would discard this session's pending native wake frames and lose real agent output.acpIsAppOwnedWakeTurn exempts orchestrator-injected wakes from the clear, matching what ClaudeAdapterV2 already does on its own buffer. The exemption is inert on this branch alone, since nothing currently dispatches creationSource: "server"; it only takes effect once #4499 lands, and it is included here because this PR introduces the clear it guards.
finalizeTurn cleared midTurnUnreportedCompletedTaskIds unconditionally, but the offer gate requires the running set to be empty. A task armed pre-settle lost its mark when the turn finalized while a second task was still running, and the second task's bare end-notice frame is excluded from wake evidence, so no continuation was ever offered for either completion (Bugbot round 2).The marks are kept across finalize when the turn settled completed and background work is still running, so the post-finalize gate offers exactly once when the last task ends. Interrupted and failed turns still clear unconditionally, and non-continuation turn start clears too, so kept marks cannot wake after an interrupt or arm a later user turn.

Manual test guide

Browsable scenario guide: <https://nam7nt0rbtm6.postplan.dev/>

Sections that cover this PR:

The carried ACP commit has no guide scenario of its own, since it only takes effect once #4499 lands. It was verified live with a Grok parent running native background work alongside a delegated child; see that PR for the evidence.

Validation

  • vp check: pass (0 errors, 63 pre-existing warnings)
  • vp run typecheck: pass (all packages)
  • Focused suites (AcpAdapterV2.test.ts, GrokAdapterV2.test.ts): 98/98, including 9 new tests
  • Live desktop retest on a rebuilt AppImage containing this commit: the original two-turn repro produced no spurious wake and no replayed acks; legitimate post-settle monitor and detached-command scenarios each produced exactly one continuation; interrupt/steer/queue scenarios stayed clean

Note

High Risk Large changes to orchestration continuation scheduling across many edge cases (settle-hold, multiturn, interrupt, staggered monitors); regressions could miss legitimate post-settle wakes or wedge continuation turns.

Overview Fixes Grok/ACP post-settle continuation logic so in-turn monitor handling no longer triggers spurious "Background task completed." runs while a turn is still streaming.

AcpAdapterV2 now tracks midTurnUnreportedCompletedTaskIds for terminal background completions during an active root turn that were not handled in-turn; it defers offerContinuationRun until finalizeTurn (and still allows one legitimate wake when work was never hydrated). Mid-turn completions no longer offer immediately from applyLateBackgroundMutation, and late monitor-event mutations no longer clear in-turn handled marks. Residual agent_message_chunk / agent_thought_chunk after in-turn-handled work is filtered before wakeBuffer fills, and non-continuation user turns clear stale wakeBuffer at startTurn. Streaming an injected report clears matching mid-turn arms; empty-drain continuation turns use the deferred quiet window when the flavor supports it. acpIsAppOwnedWakeTurn skips those clears for orchestrator creationSource: "server" wakes (for #4499).

Adds extensive AcpAdapterV2.test.ts coverage for multiturn repros, staggered tasks, interrupt, settle-hold, and empty-drain behavior.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d0ae96e7a73a1f7c828058d5da60bd2b58429026. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Note

Fix spurious wake runs triggered by in-turn monitor completions in AcpAdapterV2

  • Introduces midTurnUnreportedCompletedTaskIds to track background tasks that reach a terminal state mid-turn without being reported in-turn, deferring any continuation offer until after finalizeTurn.
  • Residual agent_message_chunk/agent_thought_chunk chatter from monitors after in-turn-handled background work no longer fills wakeBuffer or triggers synthetic continuation runs.
  • Late monitor-event mutations no longer clear in-turn handled marks, preventing duplicate "Background task completed." wake runs.
  • Adds acpIsAppOwnedWakeTurn predicate to detect orchestrator-injected agent/server wake turns; these turns no longer clear pending wake evidence or mid-turn marks.
  • Empty-drain continuation turns now wait the quiet window (when deferFinalizeForBackgroundWork is true) instead of finalizing immediately, allowing late frames to attach.
  • Risk: significant changes to continuation scheduling logic across multiple code paths in AcpAdapterV2.ts.
Macroscope summarized d0ae96e. >
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: bd8e4dda-0bd6-43ee-b141-173861396170

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR modifies complex orchestration state machine logic controlling when wake/continuation runs are offered after background task completion. While well-tested, the changes affect runtime behavior in the orchestration layer and involve intricate state transitions that warrant human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. mwolson(GitHub profile, opens in a new tab) changed the title

    5. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f62b5d474385aeb195c9fa5e1c979ffb44576ea1. Configure [here](https://www.cursor.com/dashboard/bugbot).
    6. juliusmarminge merged this82d7d40

    7. juliusmarminge closed this

Sign in to join this conversation.