Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(grok): plan mode via /plan text mapping #5424

ClosedEnzoTironi(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/5424/headopened View on GitHub

What Changed

Map T3 Plan/Build interaction mode onto Grok's /plan slash command on send, and show the composer interaction-mode toggle for Grok (live ACP does not advertise session modes).

Stacked on #5423. Fixes #5419

Why

Grok Build enters plan mode via /plan text, not ACP session modes. Without this mapping, the Plan toggle is a no-op on Grok threads. Complementary to #5409 (plan surface: exit_plan_mode + proposed-plan cards); this PR is plan entry only.

UI Changes

Composer Plan/Build toggle becomes available for Grok (existing control; no new chrome). Screenshot pending when UI PR is rebased clean.

Checklist

  • This PR is small and focused — tip still carries stacked native core (will slim for review)
  • I explained what changed and why
  • UI before/after screenshots
  • Video N/A

Known review findings

  • Empty/attachment-only plan prompts currently skip /plan (should send /plan alone)

Test plan

  • applyGrokPlanModeToPromptText unit tests
  • Composer shows plan toggle for Grok in isolated web test

Model: grok-4.5 (Grok Build)


Note

Medium Risk Large changes to Grok turn/session lifecycle (process restarts, prompt settlement, catalog pubsub); no auth or billing, but regressions could affect live Grok threads and the context meter.

Overview Plan entry (PR focus): Grok no longer relies on ACP session modes for Plan/Build—the provider snapshot enables the composer interaction-mode toggle, and sendTurn maps interactionMode: "plan" to a /plan-prefixed prompt (without double-prefixing). Empty or attachment-only plan sends still skip /plan alone (known gap).

Broader Grok ACP changes in the diff: The adapter and provider layer are aligned with live Grok 0.2.x wire behavior: CLI spawn flags for model, --reasoning-effort, and --always-approve; process restart + session resume when reasoning effort changes mid-thread (blocked while a turn is in flight). Token usage is emitted from usage_update and prompt result _meta for the context meter; session_info_update titles become thread.metadata.updated; initialize/available_commands_update feed slash commands and skills into the provider snapshot (with live snapshot stream updates from GrokDriver). xAI exit_plan_mode is handled as plan approval with turn.proposed.completed. ACP parsing adds thought chunks, usage, commands, config, and session-info updates; the mock agent and tests cover these paths.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2447738ad2782145555cf39037261e223628f019. 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 Plus

      Run ID: 5ae81d2b-494e-44e5-b86d-4bfee745feb7

      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

      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. @@ -181,0 +289,21 @@
      289+ : undefined;
      290+ return preferredMatch?._meta ?? models[0]?._meta;
      291+ };
      292+ const fromSession = pick(
      293+ input.sessionModels?.availableModels,
      294+ input.preferredModelId ?? input.sessionModels?.currentModelId,
      295+ );
      296+ if (fromSession !== undefined) return fromSession;
      297+ const initializeModelState = input.initializeMeta?.modelState;
      298+ if (isRecord(initializeModelState) && Array.isArray(initializeModelState.availableModels)) {
      299+ return pick(
      300+ initializeModelState.availableModels as ReadonlyArray<{
      301+ modelId: string;
      302+ _meta?: unknown;
      303+ }>,
      304+ input.preferredModelId ??
      305+ (typeof initializeModelState.currentModelId === "string"
      306+ ? initializeModelState.currentModelId
      307+ : undefined),
      308+ );
      309+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/GrokAdapter.ts:298

      initializeMeta.modelState.availableModels is only checked with Array.isArray, then each entry is cast to { modelId: string; _meta?: unknown } without validation. If the array contains a malformed entry such as null, pick calls model.modelId inside find and throws, failing session startup instead of ignoring unusable metadata. Validate each entry as a record with a string modelId before passing it to pick.

      Suggested change
      298- if (isRecord(initializeModelState) && Array.isArray(initializeModelState.availableModels)) {
      299- return pick(
      300- initializeModelState.availableModels as ReadonlyArray<{
      301- modelId: string;
      302- _meta?: unknown;
      303- }>,
      304- input.preferredModelId ??
      305- (typeof initializeModelState.currentModelId === "string"
      306- ? initializeModelState.currentModelId
      307- : undefined),
      308- );
      309- }
      298+ const initializeModelState = input.initializeMeta?.modelState;
      299+ if (isRecord(initializeModelState) && Array.isArray(initializeModelState.availableModels)) {
      300++ const models = initializeModelState.availableModels.filter(
      301++ (model): model is { modelId: string; _meta?: unknown } =>
      302++ isRecord(model) && typeof model.modelId === "string",
      303++ );
      304+ return pick(
      305+ models,
      306+ input.preferredModelId ??
      307+ (typeof initializeModelState.currentModelId === "string"
      308+ ? initializeModelState.currentModelId
      309+ : undefined),
      310+ );
      311+ }
      Also found in 1 other location(s)

      apps/server/src/provider/Layers/GrokProvider.ts:285

      initializeMeta.modelState is unchecked metadata but is cast directly to SessionModelState and passed to buildGrokDiscoveredModelsFromSessionModelState. If Grok supplies a malformed or partial _meta.modelState (for example {}), the helper evaluates modelState.availableModels.length and throws, turning an otherwise successful ACP startup into a failed provider health check instead of simply ignoring the fallback metadata.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/GrokAdapter.ts around lines 298-309:
      
      `initializeMeta.modelState.availableModels` is only checked with `Array.isArray`, then each entry is cast to `{ modelId: string; _meta?: unknown }` without validation. If the array contains a malformed entry such as `null`, `pick` calls `model.modelId` inside `find` and throws, failing session startup instead of ignoring unusable metadata. Validate each entry as a record with a string `modelId` before passing it to `pick`.
      
      Also found in 1 other location(s):
      - apps/server/src/provider/Layers/GrokProvider.ts:285 -- `initializeMeta.modelState` is unchecked metadata but is cast directly to `SessionModelState` and passed to `buildGrokDiscoveredModelsFromSessionModelState`. If Grok supplies a malformed or partial `_meta.modelState` (for example `{}`), the helper evaluates `modelState.availableModels.length` and throws, turning an otherwise successful ACP startup into a failed provider health check instead of simply ignoring the fallback metadata.
      
      @@ -140,0 +277,21 @@
      277+ started.initializeResult._meta &&
      278+ typeof started.initializeResult._meta === "object" &&
      279+ !Array.isArray(started.initializeResult._meta)
      280+ ? (started.initializeResult._meta as Record<string, unknown>)
      281+ : undefined;
      282+ const modelsFromSession = buildGrokDiscoveredModelsFromSessionModelState(
      283+ started.sessionSetupResult.models,
      284+ );
      285+ const modelsFromInitialize = buildGrokDiscoveredModelsFromSessionModelState(
      286+ initializeMeta?.modelState as EffectAcpSchema.SessionModelState | undefined,
      287+ );
      288+ const models = modelsFromSession.length > 0 ? modelsFromSession : modelsFromInitialize;
      289+ const initializeCommands = Array.isArray(initializeMeta?.availableCommands)
      290+ ? (
      291+ initializeMeta.availableCommands as ReadonlyArray<{
      292+ readonly name?: unknown;
      293+ readonly description?: unknown;
      294+ readonly input?: unknown;
      295+ }>
      296+ ).flatMap((command) => {
      297+ const name = typeof command.name === "string" ? command.name.trim() : "";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/GrokProvider.ts:296

      When initializeMeta.availableCommands contains null or a primitive element (e.g. ["help", null, 42]), the flatMap callback accesses command.name without first checking that command is an object, which throws a TypeError. This crashes the entire Grok ACP discovery and causes the provider health check to fail instead of skipping the malformed command. Add a guard like typeof command !== "object" || command === null before accessing command.name.

      Suggested change
      296- ).flatMap((command) => {
      297- const name = typeof command.name === "string" ? command.name.trim() : "";
      296+ ).flatMap((command) => {
      297+ if (typeof command !== "object" || command === null) return [];
      298+ const name = typeof command.name === "string" ? command.name.trim() : "";
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/GrokProvider.ts around lines 296-297:
      
      When `initializeMeta.availableCommands` contains `null` or a primitive element (e.g. `["help", null, 42]`), the `flatMap` callback accesses `command.name` without first checking that `command` is an object, which throws a `TypeError`. This crashes the entire Grok ACP discovery and causes the provider health check to fail instead of skipping the malformed command. Add a guard like `typeof command !== "object" || command === null` before accessing `command.name`.
      @@ -181,0 +270,21 @@
      270+/** Live Grok model `_meta.reasoningEffort` after process spawn. */
      271+function reasoningEffortFromMeta(meta: unknown): string | undefined {
      272+ if (!isRecord(meta)) return undefined;
      273+ const raw = meta.reasoningEffort ?? meta.reasoning_effort;
      274+ return typeof raw === "string" && raw.trim() ? raw.trim() : undefined;
      275+}
      276+
      277+function preferredModelMeta(input: {
      278+ readonly sessionModels: EffectAcpSchema.SessionModelState | null | undefined;
      279+ readonly initializeMeta: Record<string, unknown> | undefined;
      280+ readonly preferredModelId: string | undefined;
      281+}): unknown {
      282+ const pick = (
      283+ models: ReadonlyArray<{ modelId: string; _meta?: unknown }> | undefined,
      284+ preferred: string | undefined,
      285+ ): unknown => {
      286+ if (!models || models.length === 0) return undefined;
      287+ const preferredMatch = preferred
      288+ ? models.find((model) => model.modelId === preferred)
      289+ : undefined;
      290+ return preferredMatch?._meta ?? models[0]?._meta;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/GrokAdapter.ts:286

      pick falls back to models[0]._meta when the preferred model is found but has no _meta field, so it returns a different model's metadata. This causes the session to be initialized with the wrong model's totalContextTokens and reasoningEffort, producing an incorrect context window limit and reasoning-effort state. The fallback to models[0]?._meta should only apply when no preferred model matches, not when the matched model lacks _meta.

      Suggested change
      286- if (!models || models.length === 0) return undefined;
      287- const preferredMatch = preferred
      288- ? models.find((model) => model.modelId === preferred)
      289- : undefined;
      290- return preferredMatch?._meta ?? models[0]?._meta;
      286+ if (!models || models.length === 0) return undefined;
      287+ if (preferred) {
      288+ const preferredMatch = models.find((model) => model.modelId === preferred);
      289+ if (preferredMatch) return preferredMatch._meta;
      290+ }
      291+ return models[0]?._meta;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/GrokAdapter.ts around lines 286-290:
      
      `pick` falls back to `models[0]._meta` when the preferred model is found but has no `_meta` field, so it returns a *different* model's metadata. This causes the session to be initialized with the wrong model's `totalContextTokens` and `reasoningEffort`, producing an incorrect context window limit and reasoning-effort state. The fallback to `models[0]?._meta` should only apply when no preferred model matches, not when the matched model lacks `_meta`.
      @@ -106,3 +110,4 @@
      106110 env: processEnv,
      107111 });
      108112
      113+ const commandCatalogRef = yield* Ref.make({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Drivers/GrokDriver.ts:113

      mergeCommandCatalog treats an empty live catalog as "not initialized" and falls back to the previous snapshot's arrays. When onAvailableCommands receives an empty available_commands_update (i.e., the provider removed all commands), the catalog ref is correctly cleared to empty arrays, but mergeCommandCatalog sees length === 0 and keeps the stale slashCommands/skills from the last health probe. Removed commands and skills therefore remain advertised to clients indefinitely instead of being cleared.

      The length > 0 guard conflates "no live data yet" with "live data says empty." Track whether the live catalog has been initialized with a separate boolean flag (or Option), then use the ref arrays unconditionally once initialized.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Drivers/GrokDriver.ts around line 113:
      
      `mergeCommandCatalog` treats an empty live catalog as "not initialized" and falls back to the previous snapshot's arrays. When `onAvailableCommands` receives an empty `available_commands_update` (i.e., the provider removed all commands), the catalog ref is correctly cleared to empty arrays, but `mergeCommandCatalog` sees `length === 0` and keeps the stale `slashCommands`/`skills` from the last health probe. Removed commands and skills therefore remain advertised to clients indefinitely instead of being cleared.
      
      The `length > 0` guard conflates "no live data yet" with "live data says empty." Track whether the live catalog has been initialized with a separate boolean flag (or `Option`), then use the ref arrays unconditionally once initialized.
      @@ -47,0 +86,21 @@
      86+
      87+/**
      88+ * Grok has no ACP session modes on live 0.2.x. Plan mode is entered via the
      89+ * `/plan` slash command (see Grok Build user guide). Map T3 interactionMode
      90+ * onto that command so Plan/Build in the composer does real work.
      91+ */
      92+export function applyGrokPlanModeToPromptText(input: {
      93+ readonly text: string | undefined;
      94+ readonly interactionMode: "plan" | "default" | undefined;
      95+}): string | undefined {
      96+ const trimmed = input.text?.trim();
      97+ if (!trimmed) {
      98+ return trimmed;
      99+ }
      100+ if (input.interactionMode === "plan") {
      101+ if (/^\/plan(?:\s|$)/i.test(trimmed)) {
      102+ return trimmed;
      103+ }
      104+ return `/plan ${trimmed}`;
      105+ }
      106+ return trimmed;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High acp/GrokAcpSupport.ts:96

      When interactionMode is "plan" and the user's text is empty (e.g. an attachment-only prompt), applyGrokPlanModeToPromptText returns an empty string instead of "/plan", so the request runs in default mode despite the caller requesting plan mode. The early return at line 97-99 skips the plan-mode branch entirely for blank text. Consider returning "/plan" when interactionMode is "plan" and the trimmed text is empty.

         const trimmed = input.text?.trim();
      -  if (!trimmed) {
      -    return trimmed;
      -  }
      -  if (input.interactionMode === "plan") {
      +  if (input.interactionMode === "plan") {
      +    if (!trimmed) {
      +      return "/plan";
      +    }
           if (/^\/plan(?:\s|$)/i.test(trimmed)) {
             return trimmed;
           }
           return `/plan ${trimmed}`;
         }
      +  if (!trimmed) {
      +    return trimmed;
      +  }
         return trimmed;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/acp/GrokAcpSupport.ts around lines 96-106:
      
      When `interactionMode` is `"plan"` and the user's text is empty (e.g. an attachment-only prompt), `applyGrokPlanModeToPromptText` returns an empty string instead of `"/plan"`, so the request runs in default mode despite the caller requesting plan mode. The early return at line 97-99 skips the plan-mode branch entirely for blank text. Consider returning `"/plan"` when `interactionMode` is `"plan"` and the trimmed text is empty.
    4. @@ -1206,3 +1704,18 @@
      12061704 }).pipe(
      12071705 Effect.ensuring(
      12081706 Effect.gen(function* () {
      1707+ // Usage must surface even when xAI settled the turn before the prompt RPC.
      1708+ if (yield* Ref.get(promptRpcSucceeded)) {
      1709+ const promptResult = yield* Ref.get(promptResultRef);
      1710+ if (promptResult !== undefined) {
      1711+ yield* withThreadLock(
      1712+ input.threadId,
      1713+ Effect.gen(function* () {
      1714+ const live = sessions.get(input.threadId);
      1715+ if (!live || live.stopped || live.acpSessionId !== prepared.acpSessionId) {
      1716+ return;
      1717+ }
      1718+ yield* offerGrokPromptTokenUsage(live, prepared.turnId, promptResult._meta);
      1719+ }),
      1720+ ).pipe(Effect.catch(() => Effect.void));
      1721+ }

      Duplicate Grok token usage events

      Medium Severity

      Successful session/prompt RPCs can emit duplicate thread.token-usage.updated events. Token usage is published once when the RPC returns and again in the Effect.ensuring block, leading to double-counting in the context meter and activity timeline.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 0c02a1901d2e01e55251c3a934974dcda51a366d. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -867 +1280,21 @@
      8671280 text: event.text,
      1281+ streamKind: event.streamKind,
      1282+ rawPayload: event.rawPayload,
      1283+ }),
      1284+ );
      1285+ return;
      1286+ case "UsageUpdated": {
      1287+ const maxTokens =
      1288+ event.usage.size > 0
      1289+ ? event.usage.size
      1290+ : ctx.contextWindowTokens !== undefined && ctx.contextWindowTokens > 0
      1291+ ? ctx.contextWindowTokens
      1292+ : undefined;
      1293+ yield* offerRuntimeEvent(
      1294+ makeAcpTokenUsageEvent({
      1295+ stamp,
      1296+ provider: PROVIDER,
      1297+ threadId: ctx.threadId,
      1298+ turnId: notificationTurnId,
      1299+ usedTokens: event.usage.used,
      1300+ ...(maxTokens !== undefined ? { maxTokens } : {}),

      Usage updates dropped after turn

      Medium Severity

      New UsageUpdated handling runs only after a guard that requires ctx.activeTurnId. When the turn is settled early (for example via xAI prompt_complete) and activeTurnId is cleared before a late usage_update notification arrives, that usage is discarded even though prompt _meta may not have carried complete token fields.

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

      Verdict: Needs human review

      5 blocking correctness issues found. This PR introduces significant new feature functionality (plan mode, reasoning effort selection, exit plan approval workflows) with ~1900 new lines across multiple files. Multiple unresolved High severity review comments identify potential crashes from malformed metadata and incorrect plan mode behavior for empty prompts.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Review findings from Bugbot/Macroscope for this slice are fixed on the Zoen product tip (zoen/main @ 16474ab0d). Will restack / re-push these PR heads after further slim-slicing. Open remaining: effort restart without session.exited (or adopt #5403 set_model path).

    7. Closing: plan entry + plan surface are included in #5423 (native ACP parity) so we keep one reviewable Grok adapter PR instead of three XXL tips that each dumped the full stack. Issue #5419 remains linked from #5423.

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

      There are 4 total unresolved issues (including 2 from previous reviews).

      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 2447738ad2782145555cf39037261e223628f019. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -47,0 +78,21 @@
      78+ return (
      79+ getProviderOptionStringSelectionValue(selections, "reasoningEffort") ??
      80+ getProviderOptionStringSelectionValue(selections, "reasoning") ??
      81+ getProviderOptionStringSelectionValue(selections, "effort")
      82+ );
      83+}
      84+
      85+
      86+
      87+/**
      88+ * Grok has no ACP session modes on live 0.2.x. Plan mode is entered via the
      89+ * `/plan` slash command (see Grok Build user guide). Map T3 interactionMode
      90+ * onto that command so Plan/Build in the composer does real work.
      91+ */
      92+export function applyGrokPlanModeToPromptText(input: {
      93+ readonly text: string | undefined;
      94+ readonly interactionMode: "plan" | "default" | undefined;
      95+}): string | undefined {
      96+ const trimmed = input.text?.trim();
      97+ if (!trimmed) {
      98+ return trimmed;

      Plan mode skips empty prompts

      High Severity

      When the composer is in Plan mode and the prompt text is empty or whitespace, applyGrokPlanModeToPromptText returns early. This prevents the /plan prefix from being added. As GrokAdapter only includes text for truthy results, attachment-only messages sent in Plan mode reach Grok without the /plan command, causing plan entry to fail.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2447738ad2782145555cf39037261e223628f019. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -913,0 +1368,21 @@
      1368+ }
      1369+ const restart = {
      1370+ cwd: ctx.session.cwd,
      1371+ runtimeMode: ctx.session.runtimeMode,
      1372+ resumeCursor: ctx.session.resumeCursor,
      1373+ };
      1374+ yield* stopSessionInternal(ctx);
      1375+ return { _tag: "restart" as const, ...restart };
      1376+ }
      1377+ return { _tag: "continue" as const };
      1378+ }),
      1379+ );
      1380+ if (restartDecision._tag === "restart") {
      1381+ yield* startSession({
      1382+ threadId: input.threadId,
      1383+ provider: PROVIDER,
      1384+ cwd: restartDecision.cwd,
      1385+ runtimeMode: restartDecision.runtimeMode,
      1386+ ...(restartDecision.resumeCursor ? { resumeCursor: restartDecision.resumeCursor } : {}),
      1387+ ...(input.modelSelection ? { modelSelection: input.modelSelection } : {}),
      1388+ });

      Effort restart emits session exited

      Medium Severity

      Changing Grok reasoning effort mid-sendTurn calls stopSessionInternal, which publishes session.exited and marks the orchestration session stopped, then startSession publishes session.started again—all before the turn’s turn.started for that send completes.

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

Sign in to join this conversation.