Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(grok): show Grok plan-mode plans and handle plan approvals over ACP #4233

ClosedEmmanuek5(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromrefs/pull/4233/headopened View on GitHub

Problem

Grok's plan mode was broken in T3 Code. When the Grok CLI finishes planning it intercepts its exit_plan_mode tool and sends a reverse request _x.ai/exit_plan_mode ({sessionId, toolCallId, planContent}) to the ACP client for approval. T3 Code had no handler for it, so the request failed with method-not-found, which Grok surfaces as:

Plan approval could not be completed because the client disconnected. Plan mode remains active; the approval will reappear on reconnect.

The plan never displayed in the UI and the Grok session stayed stuck in plan mode.

Wire protocol (discovered by live-probing grok agent stdio)

  • {outcome: "approved"} → Grok exits plan mode (current_mode_update → default) and implements the plan.
  • Any unrecognized outcome (e.g. "rejected") with a feedback string → "The user wants to revise the plan." + feedback; the turn ends and plan mode stays active.
  • There is no client-side way to toggle plan mode over ACP (no session modes advertised; _x.ai/toggle_plan_mode is rejected). Plan mode is only entered via the agent's own enter_plan_mode tool.

Fix

  • XAiAcpExtension.ts: schema for the request (plain + wrapped forms) and response builders.
  • GrokAdapter.ts:
    • Registers handlers for x.ai/exit_plan_mode / _x.ai/exit_plan_mode.
    • First presentation: emits turn.proposed.completed with the plan markdown (same proposed-plan card flow as Claude/Cursor) and answers with a revise-and-wait response so Grok ends its turn cleanly.
    • Once a plan is captured, the next turn whose interactionMode is not "plan" (the implementation turn started from the plan card) answers approved, so Grok exits plan mode and builds. Plan-mode refinement turns capture the revised plan again.
    • Tracks current_mode_update and, when a turn arrives with interactionMode: "plan" while the Grok session is not in plan mode, prepends an instruction steering Grok into enter_plan_mode - previously T3 Code's plan toggle silently did nothing for Grok.
    • Race recovery: grok-4.5 sometimes emits the plan-file write and exit_plan_mode in one batched response; the CLI's plan-file read then races its own write and planContent arrives null. The adapter remembers the plan-file path from the enter_plan_mode tool output (rawOutput.Entered.plan_file_path) and poll-reads the file when planContent is empty.
  • acp-mock-agent.ts + tests: mock support for the ext request (including the empty-planContent recovery path), adapter tests for capture → refine → approve, and schema unit tests.

Verification

  • Drove the real Grok CLI through the adapter in a temporary integration test: plan captured as a proposed plan on turn 1, "Implement the plan." on turn 2 auto-approved the parked approval, current_mode_update flipped plan → default, and Grok edited the target file. (Test removed before commit - it requires an authenticated local Grok install.)
  • vp test run src/provider/acp/XAiAcpExtension.test.ts - 14/14 pass.
  • New GrokAdapter mock tests follow the existing wrapper pattern (they cannot run on this Windows dev machine - the .sh mock wrapper fails to spawn for all pre-existing GrokAdapter tests too - so they rely on CI).
  • tsgo --noEmit and vp check clean.

Note

Medium Risk Touches Grok session lifecycle and auto-approval of plan exit over ACP; incorrect gating could approve or block plans wrongly, though logic is covered by new tests and path validation limits file-read abuse.

Overview Fixes broken Grok plan mode where unhandled _x.ai/exit_plan_mode reverse requests left sessions stuck and plans invisible in the UI.

ACP extension and adapter: Adds XAiExitPlanModeRequest parsing and approved/rejected response builders in XAiAcpExtension.ts. GrokAdapter registers handlers for x.ai/exit_plan_mode and _x.ai/exit_plan_mode, emits turn.proposed.completed with plan markdown (same card flow as Claude/Cursor), and answers with a revise-and-wait response so Grok ends the turn cleanly. shouldAutoApproveGrokPlan gates auto-approval on a captured plan plus a newer non-plan user prompt (promptSerial / planCapture), so same-turn re-presentations and plan-mode refinement turns capture again instead of approving on the user's behalf.

Plan recovery and steering: Session state tracks planFilePath from EnterPlanMode tool updates and poll-reads the plan file when planContent is empty (CLI write/read race). When the thread is in plan mode but the Grok session is not, prompts get a leading instruction to call enter_plan_mode. extractGrokPlanFilePath only accepts absolute, NUL-free paths.

Tests: Mock agent env flags for exit-plan-mode scenarios; adapter tests for capture → refine → approve, same-turn double presentation, and file recovery; unit tests for extension helpers and approval logic.

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

Note

Add Grok plan-mode plan capture and approval handling over ACP

  • The GrokAdapter now intercepts _x.ai/exit_plan_mode extension requests and captures the proposed plan markdown, emitting a turn.proposed.completed event and responding with a rejected outcome to keep Grok in plan mode until the user acts.
  • Plans are auto-approved only after a fresh non-plan user prompt has occurred since the plan was captured, determined by the new shouldAutoApproveGrokPlan helper.
  • If planContent is missing from the request, the adapter recovers the plan by reading the file path previously reported via EnterPlanMode tool call updates.
  • New helpers in XAiAcpExtension.ts parse both bare and wrapped exit_plan_mode requests and construct approval or capture responses.
  • The ACP mock agent gains T3_ACP_EMIT_XAI_EXIT_PLAN_MODE and related flags to simulate Grok plan-mode exit flows for local testing.
Macroscope summarized 8f927f2.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. 💡 Codex Review

      Here are some automated review suggestions for this pull request.

      Reviewed commit: b1798b070f

      ℹ️ About Codex in GitHub

      Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

      • Open a pull request for review
      • Mark a draft as ready
      • Comment "@codex review".

      If Codex has suggestions, it will comment; otherwise it will react with 👍.

      Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

      @@ -663,3 +705,18 @@
      663705 ),
      664706 { discard: true },
      665707 );
      708+ yield* Effect.forEach(
      709+ ["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"] as const,
      710+ (method) =>
      711+ acp.handleExtRequest(method, XAiExitPlanModeRequest, (params) =>
      712+ mapAcpCallbackFailure(
      713+ Effect.gen(function* () {
      714+ yield* logNative(input.threadId, method, params);
      715+ const ctx = sessions.get(input.threadId);
      716+ const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
      717+ // A plan was already captured and the user came back in a
      718+ // non-plan turn: that is the implementation turn, so let
      719+ // Grok exit plan mode and build.
      720+ if (ctx?.planCaptured === true && ctx.activeInteractionMode !== "plan") {
      721+ ctx.planCaptured = false;
      722+ return makeXAiExitPlanModeApprovedResponse();

      P1 Badge Require a subsequent user turn before approving a captured plan

      When Grok enters plan mode during a normal (default) turn, the first exit_plan_mode request sets planCaptured, but activeInteractionMode remains default. If Grok issues another exit_plan_mode request in that same prompt—for example after processing the rejection feedback and revising the plan—this condition immediately returns approved, allowing implementation before the user has reviewed or accepted the proposed-plan card. Track the turn that captured the plan (or a later user submission) rather than using only the interaction-mode value.

      Useful? React with 👍 / 👎.

      Fixed in 28fd2a6c3 and refined in 0e7464eda: plan captures now record a monotonic prompt serial, and approval requires at least one new non-plan user prompt after the capture. A plan re-presented by Grok within the same prompt is captured again, never auto-approved. Regression tests: same-prompt double presentation (both captured) plus unit coverage of shouldAutoApproveGrokPlan.

    3. Pull request overview

      Fixes Grok “plan mode” integration over ACP by handling the reverse _x.ai/exit_plan_mode extension request, surfacing the plan as a proposed-plan card in the UI, and correctly responding with approval on the subsequent implementation turn.

      Changes:

      • Add ACP extension schema/helpers for exit_plan_mode (plain + wrapped) plus response builders.
      • Update GrokAdapter to capture plans via turn.proposed.completed, track plan/interaction mode state, and recover missing planContent by reading the plan file path from enter_plan_mode.
      • Extend the ACP mock agent and add tests covering capture → refine → approve and the empty-planContent recovery path.

      Reviewed changes

      Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

      Show a summary per file
      FileDescription
      apps/server/src/provider/Layers/GrokAdapter.tsRegisters/handles Grok exit_plan_mode, tracks plan-mode state, and recovers plans from disk when needed.
      apps/server/src/provider/Layers/GrokAdapter.test.tsAdds adapter-level tests for plan capture/refine/approve sequencing and plan-file recovery.
      apps/server/src/provider/acp/XAiAcpExtension.tsIntroduces schema + helpers for Grok’s exit_plan_mode reverse request and response builders.
      apps/server/src/provider/acp/XAiAcpExtension.test.tsAdds unit tests for exit_plan_mode decoding, plan extraction, and response shapes.
      apps/server/scripts/acp-mock-agent.tsAdds mock emission of _x.ai/exit_plan_mode (including empty planContent + plan-file-path race simulation).

      💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

      @@ -198,0 +219,21 @@
      219+ XAiWrappedExitPlanModeParams,
      220+]);
      221+
      222+type XAiExitPlanModeRequestParams = typeof XAiExitPlanModeParams.Type;
      223+export type XAiExitPlanModeRequest = typeof XAiExitPlanModeRequest.Type;
      224+
      225+function unwrapExitPlanModeParams(params: XAiExitPlanModeRequest): XAiExitPlanModeRequestParams {
      226+ return "params" in params ? params.params : params;
      227+}
      228+
      229+export function extractXAiExitPlanModePlan(params: XAiExitPlanModeRequest): string | undefined {
      230+ return trimmed(unwrapExitPlanModeParams(params).planContent ?? undefined);
      231+}
      232+
      233+/**
      234+ * Grok interprets the response outcome as: `approved` exits plan mode and
      235+ * tells the agent to implement the plan; `abandoned` keeps plan mode active
      236+ * and tells the agent the user does not want to exit; any other outcome is
      237+ * treated as "revise" — the tool completes with "The user wants to revise the
      238+ * plan." plus the feedback text, and plan mode stays active.
      239+ */
      copilot-pull-request-reviewer[bot](GitHub profile, opens in a new tab)commented

      The doc comment for exit_plan_mode responses mentions an abandoned outcome, but the XAiExitPlanModeResponse type (and builders) only support approved/rejected. This makes the contract unclear for future maintainers—either support abandoned explicitly or adjust the comment to match the implemented/validated outcomes.

      Fixed in 28fd2a6c3 - the doc now states that abandoned exists in Grok's protocol but is never sent by T3 Code, so the type models only the produced outcomes.

      @@ -36,5 +40,19 @@
      3640 });
      3741
      3842 const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
      43+const decodeXAiExitPlanModeRequest = Schema.decodeUnknownSync(XAiExitPlanModeRequest);
      3944
      4045 describe("XAiAcpExtension", () => {
      46+ it("extracts the plan from the real xAI exit_plan_mode payload shape", () => {
      47+ const decoded = decodeXAiExitPlanModeRequest({
      48+ sessionId: "session-1",
      49+ toolCallId: "tool-call-1",
      50+ planContent: "# Plan\n\n- Step one\n",
      51+ });
      52+
      53+ expect(extractXAiExitPlanModePlan(decoded)).toEqual("# Plan\n\n- Step one");
      54+ });
      55+
      56+ it("extracts the plan from wrapped _x.ai exit_plan_mode payloads", () => {
      57+ const decoded = decodeXAiExitPlanModeRequest({
      58+ method: "x.ai/exit_plan_mode",
      copilot-pull-request-reviewer[bot](GitHub profile, opens in a new tab)commented

      This test case says it covers wrapped _x.ai/exit_plan_mode payloads, but the sample payload uses method: "x.ai/exit_plan_mode". Either rename the test or use the _x.ai/... method to match the intent.

      Fixed in 28fd2a6c3 - the wrapped-payload test now uses the _x.ai/exit_plan_mode method.

      @@ -665,0 +718,21 @@
      718+ // non-plan turn: that is the implementation turn, so let
      719+ // Grok exit plan mode and build.
      720+ if (ctx?.planCaptured === true && ctx.activeInteractionMode !== "plan") {
      721+ ctx.planCaptured = false;
      722+ return makeXAiExitPlanModeApprovedResponse();
      723+ }
      724+ let planMarkdown = extractXAiExitPlanModePlan(params);
      725+ // Grok can batch the plan-file write and exit_plan_mode
      726+ // in one model response; its own plan read then races
      727+ // the write and planContent arrives empty. Recover by
      728+ // reading the plan file the CLI reported on entry.
      729+ if (planMarkdown === undefined && ctx !== undefined) {
      730+ for (
      731+ let attempt = 0;
      732+ attempt < 20 && planMarkdown === undefined;
      733+ attempt += 1
      734+ ) {
      735+ // Re-read per attempt: the enter_plan_mode update that
      736+ // carries the path is processed on a concurrent fiber.
      737+ const planFilePath = ctx.planFilePath;
      738+ if (planFilePath) {

      The plan recovery path reads ctx.planFilePath from a tool-call update and then reads that path directly from disk. Adding minimal validation (absolute path + reject NUL bytes) reduces the risk of unintended path injection and avoids surprising relative-path resolution.

      Added in 28fd2a6c3 (tightened in f392222e5): the agent-supplied path must be NUL-free and rooted at a drive letter or POSIX "/" before the adapter reads it.

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

      Approvability

      Verdict: Needs human review

      This PR introduces significant new Grok plan-mode handling capability (620+ new lines), not a simple fix. Additionally, there's an unresolved P1 review comment identifying a potential bug where plans could be auto-approved before user review. Both the scope and the open correctness concern warrant human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. 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: 983116e7-42ce-48b9-82f2-49a9617db992

      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.
    6. @@ -162,0 +190,21 @@
      190+ */
      191+export function extractGrokPlanFilePath(rawPayload: unknown): string | undefined {
      192+ if (!isRecord(rawPayload)) return undefined;
      193+ const params = isRecord(rawPayload.params) ? rawPayload.params : rawPayload;
      194+ const update = params.update;
      195+ if (!isRecord(update)) return undefined;
      196+ const rawOutput = update.rawOutput;
      197+ if (!isRecord(rawOutput) || rawOutput.type !== "EnterPlanMode") return undefined;
      198+ for (const value of Object.values(rawOutput)) {
      199+ if (!isRecord(value) || typeof value.plan_file_path !== "string") {
      200+ continue;
      201+ }
      202+ const planFilePath = value.plan_file_path.trim();
      203+ // The path is agent-supplied: accept only absolute, NUL-free paths so a
      204+ // malformed value cannot resolve somewhere surprising. Roots are limited
      205+ // to a Windows drive letter or a POSIX "/" — a bare leading backslash is
      206+ // relative on POSIX and rejected.
      207+ if (
      208+ planFilePath.length > 0 &&
      209+ !planFilePath.includes("\0") &&
      210+ /^(?:[A-Za-z]:[\\/]|\/)/.test(planFilePath)

      Windows absolute paths rejected

      Low Severity

      The absolute-path check now requires a drive letter or a leading /, so Windows UNC paths and current-drive roots that start with \ are dropped. When planContent is empty, plan-file recovery never runs and the UI falls back to a placeholder plan.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f392222e553f71889b786419968682866b4fa45f. Configure [here](https://www.cursor.com/dashboard/bugbot).

      Deliberate trade-off after the sibling Macroscope finding (backslash roots are relative on POSIX): Grok stores plan files under the user's home directory on a lettered drive, so UNC/current-drive-relative roots do not occur in practice, and this path only gates the empty-planContent recovery fallback - rejecting it degrades to the placeholder card, never breaks approval. Happy to add platform-aware UNC support if maintainers prefer.

    7. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      There are 3 total unresolved issues (including 1 from previous review).

      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 0e7464edac1496e676d4d91b19bc2a067da94b30. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. Closing in favor of #2829 (orchestration V2).

      #2829 deletes the V1 orchestration layer this PR builds on — apps/server/src/orchestration/**, provider/Layers/*Adapter.ts and provider/Services/** are removed and replaced by apps/server/src/orchestration-v2/**, with the IPC surface renamed to ORCHESTRATION_V2_WS_METHODS. The files this PR touches either no longer exist or are rewritten, so it can't be rebased — it would need reimplementing against the V2 adapters.

      This is not a judgement on the change itself. Several of these are real gaps we still want fixed; the base just moved out from under them.

      Once #2829 merges, please rebase onto main, port the change to the V2 equivalent, and reopen (or open a fresh PR). Ping me and I'll prioritise the review.

    9. juliusmarminge closed this

Sign in to join this conversation.