Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(grok): Harden ACP resume with replay-idle load readiness #3156

Mergedmwolson(GitHub profile, opens in a new tab)merged 7 commits intomain fromrefs/pull/3156/headmerged by juliusmarminge View on GitHub

Summary

Closes #3560.

  • Race session/prompt against xAI _x.ai/session/prompt_complete so Grok turns settle when the standard ACP RPC remains stranded.
  • Make Stop interrupt the wedged prompt, settle the active turn exactly once, and return the session to ready.
  • Resume Grok sessions without replay flooding by dropping replay updates and using replay-idle load readiness when session/load never returns.
  • Keep one strict root-turn boundary: an AcpSessionRuntime only accepts session/update events for its started root session, and Grok drains those accepted events before emitting turn.completed.
  • Keep the actual running turn unfolded in the web timeline when latestTurn temporarily regresses.

Deliberate scope

This is a narrow V1 Grok/ACP bridge. Child-session chunks are ignored instead of being flattened into the parent transcript. After merge, the V2 follow-up can route those chunks through its existing subagent lineage and progress model.

The earlier projection, reducer, shared-message, markdown-throttling, sidebar, and generic orchestration workarounds have been removed. turn.completed remains the canonical terminal barrier, and ProviderRuntimeIngestion retains its strict provider-independent finalization behavior.

Validation

  • vp check passes with 7 unrelated existing mobile warnings.
  • vp run typecheck passes.
  • vp test packages/effect-acp/src/client.test.ts apps/server/src/provider/Layers/CursorAdapter.test.ts apps/server/src/provider/Layers/GrokAdapter.test.ts apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts apps/server/src/provider/acp/AcpRuntimeModel.test.ts apps/web/src/components/ChatView.logic.test.ts apps/web/src/components/chat/MessagesTimeline.logic.test.ts apps/web/src/components/chat/MessagesTimeline.test.tsx: 8 files, 130 tests passed.

Note

Harden Grok ACP turn resumption with replay-idle load readiness and atomic prompt settlement

  • Session load on resume now races between the session/load RPC and a replay-idle timer (waitForSessionLoadReplayIdle), completing as soon as replayed notifications go quiet for a configurable gap; replayed and child-session updates are dropped during load.
  • Prompt settlement is now atomic and context-validated via settlePromptInFlight: late or cross-session completions are ignored, interrupted turns cannot be revived by late RPC results, and multiple in-flight prompts for the same turn merge with only the last settling the turn.
  • interruptTurn now accepts a specific turnId, pre-marks it in interruptedTurnIds, cancels outstanding prompt slots, and moves the session to ready without emitting spurious terminal events.
  • xAI prompt completion fallback (makeXAiPromptCompletionRuntime) races the native ACP prompt RPC against _x.ai/session/prompt_complete notifications, tags requests with promptId/requestId, dedupes completed IDs, and aborts pending fallbacks on cancel.
  • AcpSessionRuntime serializes concurrent prompts, adds drainEvents/EventStreamBarrier for queue synchronization, and resolves an interrupted prompt to { stopReason: 'cancelled' } instead of hanging.
  • MessagesTimeline and ChatView now propagate runningTurnId so fold behavior tracks the active turn rather than a regressed latestTurn, and interrupt actions include the active turn ID.
  • Risk: turn.completed events may now carry a null stopReason when the xAI provider omits one from its notification.
Macroscope summarized bf4b5b5.

Note

High Risk Changes core Grok turn lifecycle, cancel/settlement ordering, and ACP event routing—areas where race bugs directly affect user-visible transcripts and session readiness.

Overview Hardens the Grok ACP bridge so turns can finish when the standard session/prompt RPC hangs, resumes do not flood the transcript, and Stop/cancel races do not double-settle or leak late updates.

The ACP session runtime now ignores replay and foreign-session session/update traffic, can complete session/load when replay goes idle (not only when the RPC returns), serializes prompts, interrupts in-flight prompt fibers on cancel, and adds drainEvents / EventStreamBarrier so consumers flush queued events before terminal settlement. xAI _x.ai/session/prompt_complete is wired via makeXAiPromptCompletionRuntime to race the native prompt, track promptIds, and synthesize cancelled/missing-stop-reason responses.

GrokAdapter gains centralized settlePromptInFlight, interruptedTurnIds, turn-scoped interruptTurn, event draining before turn.completed, and drops streaming for cancelled turns. The mock ACP agent and effect-acp client tests cover hang, stale completion, load replay, and mixed extension notification batches.

Web: interrupt sends the session’s active running turnId; the timeline prefers runningTurnId over a regressed latestTurn so the live turn stays unfolded.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bf4b5b513749f6dd774063d93de6f518ca8f0d8f. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).
    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

      Run ID: e88888ef-ddd4-4d21-8038-d79d0f20e24e

      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

      1 blocking correctness issue found. Introduces significant runtime behavior changes to Grok session and prompt lifecycle management, including new prompt settlement logic, session resume replay-idle detection, and xAI prompt completion fallback. The complexity and cross-cutting nature of these infrastructure changes 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. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/session-logic.ts:1359

      In deriveTimelineEntries, assistant messages are now sorted by message.updatedAt instead of createdAt. If a replay or chunk update bumps updatedAt on a completed assistant message after the user has already sent a follow-up, that older assistant response sorts below the newer user message. This misorders the transcript and breaks downstream turn grouping that expects messages to follow the original creation order.

      ✅ Resolved in b1691165cdde9d7bc35f6e0e607c68575b87af5f

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

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/8d6d53ba076859c8dc8374c2033bdd0743018e27/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L850

      When turnChanged is true (assistant message starts a new turn), nextAttachments still falls back to previousMessage?.attachments if event.payload.attachments is undefined. This causes a rebound turn without attachments to inherit stale files from the previous turn.

      Also found in 1 other location(s)

      packages/client-runtime/src/state/threadReducer.ts:225

      When assistantSegmentTurnChanged(existingMessage, message) is true, the reducer resets the message text and timestamps for the reused assistant segment but leaves attachments untouched unless the incoming event also carries attachments. If the previous turn's assistant segment had attachments and the replayed segment for the new turn omits them, the old attachments are carried into the new turn's message and shown on the wrong response.

      ✅ Resolved in b1691165cdde9d7bc35f6e0e607c68575b87af5f

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

      🟠 High

      https://github.com/pingdotgg/t3code/blob/8d6d53ba076859c8dc8374c2033bdd0743018e27/apps/server/src/provider/Layers/GrokAdapter.ts#L1032

      interruptTurn never clears ctx.session.status from "running" or resets activeTurnId. After a user presses Stop, listSessions() continues to report the session as running indefinitely because the only state cleanup path is the sendTurn ensuring block, which may never execute if the prompt RPC is hung.

      ✅ Resolved in facb77dc9c255451aa41a0f6e529cf2ccf2c67cc

    7. Addressed in facb77dc9: interruptTurn now calls settlePromptInFlight(..., { completedStopReason: "cancelled" }) after session/cancel, so Grok sessions return to ready and activeTurnId clears when the user presses Stop.

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

      🟠 High src/orchestrationMessages.ts:39

      When a completed assistant message has turnId: null and the first streaming delta arrives with a real turnId, isLateStreamingOnCompletedAssistant returns true because assistantSegmentTurnChanged returns false for the transition from null to a real ID. This causes the delta to be discarded as "late streaming," preventing the stored assistant message from ever receiving its valid turnId. Consider changing the logic so that a transition from null to a non-null turnId is accepted rather than dropped.

      Also found in 1 other location(s)

      apps/server/src/orchestration/Layers/ProjectionPipeline.ts:842

      When a reused assistant messageId is rebound to a new turn but the persisted row still has turnId: null (which already happens for assistant rows in ProjectionPipeline.test.ts), assistantSegmentTurnChanged(...) at line 842 returns false. The code then treats the new streaming chunk as a continuation of the old message, appending the new text to the replayed text and preserving the old createdAt, so the new turn shows corrupted assistant content instead of starting a fresh message row.

      ✅ Resolved in f5e28f6ffd39ce52837ca433d351ff675c1c3144

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

      🟠 High

      https://github.com/pingdotgg/t3code/blob/facb77dc9c255451aa41a0f6e529cf2ccf2c67cc/apps/server/src/provider/Layers/GrokAdapter.ts#L841

      After a turn completes, streamingTurnId is set but never cleared when the next turn starts. resolveNotificationTurnId returns streamingTurnId if present, so all subsequent AssistantItem*, ToolCallUpdated, ContentDelta, and plan events for the new turn are emitted with the previous turn's ID. Consider clearing streamingTurnId when starting a new turn (around where activeTurnId is assigned in sendTurn).

      ✅ Resolved in b1691165cdde9d7bc35f6e0e607c68575b87af5f

    9. Fixed in cb4146d72. deriveTimelineEntries now sorts assistant rows by stable createdAt instead of mutable updatedAt. Projection resets createdAt only when a rebound starts (first null-turn chunk) or when turnChanged confirms a new turn binding, so late streaming bumps no longer reorder completed assistants below later user prompts.

    10. Fixed in cb4146d72. On turnChanged, omitted attachments no longer inherit from the prior row. ProjectionPipeline, projector, and threadReducer all clear attachments unless the incoming event explicitly carries them (DB upsert passes an empty array to avoid COALESCE retention).

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

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    12. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

Sign in to join this conversation.