diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index 5230712f03..2a887270a9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -120,8 +120,8 @@ export interface AcpAdapterV2ExtensionContext { readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]; /** * Session-scoped background-task lifecycle reported via extension - * notifications (e.g. Grok `_x.ai/task_backgrounded` after a soft cancel - * detaches foreground work). Mutations for non-root sessions are ignored. + * notifications (e.g. Grok `x.ai/task_backgrounded`; older builds use the + * underscore alias). Mutations for non-root sessions are ignored. */ readonly applyBackgroundTaskMutation: (mutation: { readonly sessionId: string; @@ -225,8 +225,9 @@ export interface AcpAdapterV2Flavor { /** * Optional parse of root-session synthetic text announcing a background * subagent's end ("Background subagent "" ... completed successfully"). - * The agent may never hydrate via get_command_or_subagent_output, so this - * notice can be the only terminal signal for the subagent row. + * Older builds may never hydrate via get_command_or_subagent_output, so this + * remains a terminal fallback. Current Grok additionally emits structured + * `subagent_finished` session notifications. */ readonly extractSubagentEndNotice?: (text: string) => | { diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts index 4b34b2b98f..b89be38a8a 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts @@ -160,14 +160,14 @@ export function makeGrokAcpAdapterFlavor(options: GrokAdapterV2Options): AcpAdap // prompt while Grok continued, freezing T3 projection mid-turn. settleRootTurnWhenIdle: false, interruptPromptOnCancel: false, - // User Stop (requestRuntimeRestart) still hard-kills the process group - // and respawns: Grok `session/cancel` is detach-and-continue (the CLI - // re-runs cancelled foreground work as a background task no client RPC - // can kill, E3 harness 2026-07-18), so only a process kill truly stops - // work. Non-Stop interrupts (mid-prompt steering, restart_active) omit - // requestRuntimeRestart and stay soft: the session survives in the same - // process, cancelled work backgrounds, and the model itself decides via - // kill_command_or_subagent whether it keeps running. + // User Stop (requestRuntimeRestart) still hard-kills the process group and + // respawns so existing background tasks stop too. Older 0.2.x builds could + // detach a cancelled foreground command (E3 harness 2026-07-18); current + // source kills foreground work but intentionally preserves already- + // backgrounded tasks. Non-Stop interrupts (mid-prompt steering, + // restart_active) omit requestRuntimeRestart and stay soft: session/cancel + // carries cancelTrigger=ctrl_c, the session survives, and background work + // remains available to the replacement turn. restartRuntimeAfterInterrupt: true, terminateRuntimeProcessGroupOnInterrupt: true, // Steering restarts on a settled turn additionally skip session/cancel so diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index f013cb9d48..b6c5222cf2 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -319,8 +319,9 @@ describe("AcpSessionRuntime", () => { ), ); - it.effect("releases a fully silent prompt when session/cancel is requested", () => - Effect.gen(function* () { + it.effect("releases a fully silent prompt and forwards configured cancel metadata", () => { + const protocolEvents: Array = []; + return Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; yield* runtime.start(); @@ -332,6 +333,19 @@ describe("AcpSessionRuntime", () => { yield* TestClock.adjust("500 millis"); yield* runtime.cancel; + yield* Effect.yieldNow; + yield* Effect.yieldNow; + + expect( + protocolEvents.some( + (event) => + event.direction === "outgoing" && + event.stage === "raw" && + typeof event.payload === "string" && + event.payload.includes('"method":"session/cancel"') && + event.payload.includes('"cancelTrigger":"ctrl_c"'), + ), + ).toBe(true); const firstPromptResult = yield* Fiber.join(promptFiber); expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" }); @@ -353,12 +367,20 @@ describe("AcpSessionRuntime", () => { cwd: process.cwd(), clientInfo: { name: "t3-test", version: "0.0.0" }, authMethodId: "test", + cancelMeta: { cancelTrigger: "ctrl_c" }, + protocolLogging: { + logOutgoing: true, + logger: (event) => + Effect.sync(() => { + protocolEvents.push(event); + }), + }, }), ), Effect.scoped, Effect.provide(NodeServices.layer), - ), - ); + ); + }); it.effect("segments assistant text around ACP tool calls", () => Effect.gen(function* () { diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index e77b29c70e..3a1cdea5a6 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -73,6 +73,8 @@ export interface AcpSessionRuntimeOptions { readonly sessionLoadTimeout?: Duration.Input; readonly sessionLoadReplayIdleGap?: Duration.Input; readonly interruptPromptOnCancel?: boolean; + /** Optional provider metadata forwarded on `session/cancel`. */ + readonly cancelMeta?: EffectAcpSchema.CancelNotification["_meta"]; readonly ownDetachedProcessGroup?: boolean; readonly ownDescendantProcessGroups?: boolean; readonly processGroupPlatform?: NodeJS.Platform; @@ -2155,15 +2157,23 @@ export const make = ( ), cancel: getStartedState.pipe( Effect.flatMap((started) => - Effect.gen(function* () { - const activePromptFiber = yield* Ref.get(activePromptFiberRef); - if (Option.isSome(activePromptFiber)) { - yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore); - } - yield* acp.agent - .cancel({ sessionId: started.sessionId }) - .pipe(Effect.ignore, Effect.forkIn(runtimeScope)); - }), + options.interruptPromptOnCancel === false + ? acp.agent.cancel({ + sessionId: started.sessionId, + ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }), + }) + : Effect.gen(function* () { + const activePromptFiber = yield* Ref.get(activePromptFiberRef); + if (Option.isSome(activePromptFiber)) { + yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore); + } + yield* acp.agent + .cancel({ + sessionId: started.sessionId, + ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }), + }) + .pipe(Effect.ignore, Effect.forkIn(runtimeScope)); + }), ), ), ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}), diff --git a/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts b/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts index 7ca3d72a12..1341377ed9 100644 --- a/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts +++ b/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts @@ -67,7 +67,7 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () = }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("switches to another advertised model and completes a prompt", () => + it.effect("switches when another model is advertised and completes a prompt", () => Effect.gen(function* () { const runtime = yield* makeProbeRuntime; const started = yield* runtime.start(); @@ -75,10 +75,13 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () = const targetModel = models?.availableModels.find( ({ modelId }) => modelId !== models.currentModelId, )?.modelId; - expect(targetModel).toBeDefined(); - if (!targetModel) return; - yield* runtime.setSessionModel(targetModel).pipe(Effect.timeout("20 seconds")); + // Model availability is account-dependent. Exercise a real switch when + // possible, but a single-model catalog is valid and must still reach the + // prompt check below. + if (targetModel !== undefined) { + yield* runtime.setSessionModel(targetModel).pipe(Effect.timeout("20 seconds")); + } const result = yield* runtime .prompt({ prompt: [{ type: "text", text: "Respond with exactly: grok switch ok" }] }) .pipe(Effect.timeout("60 seconds")); diff --git a/apps/server/src/provider/acp/GrokAcpSupport.ts b/apps/server/src/provider/acp/GrokAcpSupport.ts index 017fcf7edc..6842c37f7f 100644 --- a/apps/server/src/provider/acp/GrokAcpSupport.ts +++ b/apps/server/src/provider/acp/GrokAcpSupport.ts @@ -81,6 +81,9 @@ export const makeGrokAcpRuntime = ( ...input, spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment), authMethodId: resolveGrokAuthMethodId(input.environment), + // Current Grok treats Ctrl+C cancellation as a barrier against stale + // background-task wake prompts until the next genuine user turn. + cancelMeta: { ...input.cancelMeta, cancelTrigger: "ctrl_c" }, ...grokAcpRuntimeProcessOwnership(processGroupPlatform), }).pipe( Layer.provide( diff --git a/apps/server/src/provider/acp/XAiAcpExtension.test.ts b/apps/server/src/provider/acp/XAiAcpExtension.test.ts index f4d3e1359c..31117a995c 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.test.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.test.ts @@ -20,6 +20,7 @@ import { makeXAiAskUserQuestionResponse, makeXAiPromptCompletionRuntime, normalizeXAiAcpToolCallState, + registerXAiBackgroundTaskTracking, resolveXAiAcpToolTitle, xAiBackgroundTaskLifecycleMutation, xAiPromptCompleteFromSessionUpdate, @@ -710,6 +711,57 @@ describe("XAiAcpExtension", () => { ).toBeNull(); }); + it.effect("tracks canonical Grok task lifecycle notifications", () => + Effect.gen(function* () { + const handlers = new Map Effect.Effect>(); + const mutations: Array<{ + readonly sessionId: string; + readonly taskId: string; + readonly status: "running" | "completed"; + }> = []; + const runtime = { + handleExtNotification: ( + method: string, + _schema: unknown, + handler: (notification: unknown) => Effect.Effect, + ) => { + handlers.set(method, handler); + return Effect.void; + }, + } as unknown as Pick; + + yield* registerXAiBackgroundTaskTracking(runtime, (mutation) => + Effect.sync(() => mutations.push(mutation)), + ); + + const backgrounded = handlers.get("x.ai/task_backgrounded"); + const completed = handlers.get("x.ai/task_completed"); + expect(backgrounded).toBeDefined(); + expect(completed).toBeDefined(); + yield* backgrounded!({ + sessionId: "session-1", + update: { + sessionUpdate: "task_backgrounded", + tool_call_id: "call-bg-1", + task_id: "task-bg-1", + }, + }); + yield* completed!({ + sessionId: "session-1", + update: { + sessionUpdate: "task_completed", + task_snapshot: { task_id: "task-bg-1" }, + }, + }); + expect(mutations).toEqual([ + { sessionId: "session-1", taskId: "task-bg-1", status: "running" }, + { sessionId: "session-1", taskId: "task-bg-1", status: "completed" }, + ]); + expect(handlers.has("_x.ai/task_backgrounded")).toBe(true); + expect(handlers.has("_x.ai/task_completed")).toBe(true); + }), + ); + it("detects persistent Monitor start ACKs", () => { expect( isXAiPersistentMonitor({ @@ -1187,7 +1239,7 @@ describe("XAiAcpExtension", () => { .prompt({ prompt: [{ type: "text", text: "hi" }] }) .pipe(Effect.forkChild); yield* Effect.yieldNow; - const promptCompleteHandler = handlers.get("_x.ai/session/prompt_complete"); + const promptCompleteHandler = handlers.get("x.ai/session/prompt_complete"); expect(promptCompleteHandler).toBeDefined(); yield* promptCompleteHandler!({ sessionId: "root-session", @@ -1195,6 +1247,7 @@ describe("XAiAcpExtension", () => { }); const response = yield* Fiber.join(promptFiber); expect(response.stopReason).toBe("end_turn"); + expect(handlers.has("_x.ai/session/prompt_complete")).toBe(true); }), ); @@ -1249,6 +1302,52 @@ describe("XAiAcpExtension", () => { }), ); + it.effect("settles a hung prompt from released _x.ai/session_notification turns", () => + Effect.gen(function* () { + const handlers = new Map Effect.Effect>(); + const hungPrompt = yield* Deferred.make(); + const baseRuntime = { + start: () => + Effect.succeed({ + sessionId: "root-session", + initializeResult: {}, + sessionSetupResult: {}, + modelConfigId: undefined, + }), + prompt: () => Deferred.await(hungPrompt), + cancel: Effect.void, + handleExtNotification: ( + method: string, + _schema: unknown, + handler: (notification: unknown) => Effect.Effect, + ) => { + handlers.set(method, handler); + return Effect.void; + }, + handleExtRequest: () => Effect.void, + } as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"]; + + const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime); + const promptFiber = yield* runtime + .prompt({ prompt: [{ type: "text", text: "hi" }] }) + .pipe(Effect.forkChild); + yield* Effect.yieldNow; + const sessionNotificationHandler = handlers.get("_x.ai/session_notification"); + expect(sessionNotificationHandler).toBeDefined(); + yield* sessionNotificationHandler!({ + sessionId: "root-session", + update: { + sessionUpdate: "turn_completed", + prompt_id: "t3-xai-prompt-1", + stop_reason: "end_turn", + }, + }); + const response = yield* Fiber.join(promptFiber); + expect(response.stopReason).toBe("end_turn"); + expect(handlers.has("_x.ai/session/update")).toBe(true); + }), + ); + it.effect("ignores turn_completed for non-pending prompt ids and task completions", () => Effect.gen(function* () { const handlers = new Map Effect.Effect>(); diff --git a/apps/server/src/provider/acp/XAiAcpExtension.ts b/apps/server/src/provider/acp/XAiAcpExtension.ts index 3ad86010c7..40e9ed83b4 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.ts @@ -24,10 +24,14 @@ const XAiPromptCompleteNotification = Schema.Struct({ type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type; /** - * Live Grok CLI (0.2.x) emits root turn completion as an extension session - * update, not as top-level `_x.ai/session/prompt_complete`: - * `{ method: "_x.ai/session/update", params: { sessionId, update: { + * Grok persists root turn completion as an extension session update: + * `{ params: { sessionId, update: { * sessionUpdate: "turn_completed", prompt_id, stop_reason } } }`. + * The open-source runtime forwards it as `x.ai/session_notification` and + * stores/replays it as `_x.ai/session/update`; released 0.2.106 forwards the + * underscore alias `_x.ai/session_notification`. Current source also emits + * the fire-and-forget canonical `x.ai/session/prompt_complete`, while released + * builds use the underscore alias. */ const XAiSessionUpdateNotification = Schema.Struct({ sessionId: Schema.String, @@ -324,7 +328,7 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState): /** * A finished kill_command_or_subagent call is the genuine end signal for every - * task id it names: the Grok CLI emits no `_x.ai/task_completed` for a killed + * task id it names: the Grok CLI emits no `x.ai/task_completed` for a killed * task. A failed kill usually means the task was already gone, so it ends the * id too (failing open to a continuation beats pinning the running set). */ @@ -392,36 +396,32 @@ export function xAiBackgroundTaskLifecycleMutation( } /** - * Grok `session/cancel` is detach-and-continue: the CLI reaps the foreground - * tool shell, then re-runs the command as a background task - * (`_x.ai/task_backgrounded`) that executes to completion - * (`_x.ai/task_completed`). Soft interrupts keep the process alive, so those - * tasks must be tracked like monitors: residual frames buffer instead of - * waking synthetic continuations, and pending-background-work stays truthful - * until the task ends (or the model kills it via kill_command_or_subagent). + * Grok task lifecycle notifications use canonical `x.ai/task_*` methods in + * current builds; older 0.2.x builds used `_x.ai/task_*`. Interactive cancel + * preserves tasks that were already backgrounded (and some older builds could + * background the cancelled foreground command), so both spellings must be + * tracked. Residual frames then buffer instead of waking synthetic + * continuations, and pending-background-work stays truthful until the task + * ends (or the model kills it via kill_command_or_subagent). */ export const registerXAiBackgroundTaskTracking = ( runtime: Pick, apply: (mutation: XAiBackgroundTaskLifecycleMutation) => Effect.Effect, ): Effect.Effect => - Effect.gen(function* () { - yield* runtime.handleExtNotification( - "_x.ai/task_backgrounded", - XAiTaskLifecycleNotification, - (notification) => { - const mutation = xAiBackgroundTaskLifecycleMutation(notification, "running"); + Effect.forEach( + [ + ["x.ai/task_backgrounded", "running"], + ["_x.ai/task_backgrounded", "running"], + ["x.ai/task_completed", "completed"], + ["_x.ai/task_completed", "completed"], + ] as const, + ([method, status]) => + runtime.handleExtNotification(method, XAiTaskLifecycleNotification, (notification) => { + const mutation = xAiBackgroundTaskLifecycleMutation(notification, status); return mutation === null ? Effect.void : apply(mutation); - }, - ); - yield* runtime.handleExtNotification( - "_x.ai/task_completed", - XAiTaskLifecycleNotification, - (notification) => { - const mutation = xAiBackgroundTaskLifecycleMutation(notification, "completed"); - return mutation === null ? Effect.void : apply(mutation); - }, - ); - }); + }), + { discard: true }, + ); /** * Grok ACP often sends `title: "Tool"` even when rawInput has a useful @@ -1139,8 +1139,9 @@ const rememberCompletedXAiPromptId = ( /** * Grok-specific ACP runtime wrapper. Races `session/prompt` against root-matched * terminal notifications: - * - `_x.ai/session/update` + `turn_completed` + matching `prompt_id` (current CLI) - * - `_x.ai/session/prompt_complete` (legacy / alternate builds) + * - session notification/update + `turn_completed` + matching `prompt_id` + * - `x.ai/session/prompt_complete` (open-source fire-and-forget signal) + * - `_x.ai/session/prompt_complete` (released-build alias) * * Pending entries are keyed by root sessionId + T3-injected promptId, so * foreign/child sessions and `task-completed-*` ids do not settle the root turn. @@ -1164,22 +1165,28 @@ export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletion notification, }).pipe(Effect.catch(() => Effect.void)); - yield* runtime.handleExtNotification( - "_x.ai/session/prompt_complete", - XAiPromptCompleteNotification, - settleFromPromptComplete, + yield* Effect.forEach( + ["x.ai/session/prompt_complete", "_x.ai/session/prompt_complete"] as const, + (method) => + runtime.handleExtNotification( + method, + XAiPromptCompleteNotification, + settleFromPromptComplete, + ), + { discard: true }, ); - yield* runtime.handleExtNotification( - "_x.ai/session/update", - XAiSessionUpdateNotification, - (notification) => { - const complete = xAiPromptCompleteFromSessionUpdate(notification); - if (complete === null) { - return Effect.void; - } - return settleFromPromptComplete(complete); - }, + yield* Effect.forEach( + ["x.ai/session_notification", "_x.ai/session_notification", "_x.ai/session/update"] as const, + (method) => + runtime.handleExtNotification(method, XAiSessionUpdateNotification, (notification) => { + const complete = xAiPromptCompleteFromSessionUpdate(notification); + if (complete === null) { + return Effect.void; + } + return settleFromPromptComplete(complete); + }), + { discard: true }, ); return {