@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,643 lines 52.3 KB
Raw
1 import { it } from "@effect/vitest";
2 import * as Deferred from "effect/Deferred";
3 import * as Effect from "effect/Effect";
4 import * as Fiber from "effect/Fiber";
5 import * as Schema from "effect/Schema";
6 import { describe, expect } from "vite-plus/test";
7
8 import {
9 XAiExitPlanModeRequest,
10 XAI_EMPTY_PLAN_MARKDOWN,
11 isGrokPlanMarkdownPath,
12 extractXAiExitPlanMarkdown,
13 extractGrokPlanMarkdownFromToolCallData,
14 extractXAiAcpBackgroundToolMutation,
15 extractXAiAcpSubagentEndNotice,
16 extractXAiAcpSubagentUpdate,
17 extractXAiAskUserQuestions,
18 extractXAiBackgroundTaskCompletion,
19 extractXAiKilledBackgroundTasks,
20 extractXAiMonitorTaskId,
21 isXAiMonitorTool,
22 makeXAiAskUserQuestionResponse,
23 makeXAiPromptCompletionRuntime,
24 normalizeXAiAcpToolCallState,
25 xAiBackgroundTaskLifecycleMutation,
26 xAiPromptCompleteFromSessionUpdate,
27 xAiSubagentFinishedNotice,
28 XAiAskUserQuestionRequest,
29 } from "./xaiAcpExtension.ts";
30 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
31 import {
32 type AcpToolCallState,
33 extractMcpToolCallIdentity,
34 mergeToolCallState,
35 parseSessionUpdateEvent,
36 } from "@t3tools/provider-acp/server/runtimeModel";
37 import { compactDynamicToolOutput, htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
38
39 const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
40
41 describe("xAiPromptCompleteFromSessionUpdate", () => {
42 it("ignores non-turn updates and task-completed prompt ids", () => {
43 expect(
44 xAiPromptCompleteFromSessionUpdate({
45 sessionId: "root",
46 update: { sessionUpdate: "hook_execution", prompt_id: "t3-xai-prompt-1" },
47 }),
48 ).toBeNull();
49 expect(
50 xAiPromptCompleteFromSessionUpdate({
51 sessionId: "root",
52 update: {
53 sessionUpdate: "turn_completed",
54 prompt_id: "task-completed-call-abc",
55 stop_reason: "end_turn",
56 },
57 }),
58 ).toBeNull();
59 expect(
60 xAiPromptCompleteFromSessionUpdate({
61 sessionId: "root",
62 update: { sessionUpdate: "turn_completed", stop_reason: "end_turn" },
63 }),
64 ).toBeNull();
65 });
66 });
67
68 function parseRecordedToolCallUpdate(update: Record<string, unknown>): AcpToolCallState {
69 const [event] = parseSessionUpdateEvent({
70 sessionId: "01a0d660-c1bb-7842-91a3-02d91dc8b0d2",
71 update,
72 } as Parameters<typeof parseSessionUpdateEvent>[0]).events;
73 if (event?._tag !== "ToolCallUpdated") throw new Error("expected a tool call update");
74 return event.toolCall;
75 }
76
77 describe("XAiAcpExtension", () => {
78 it("recognizes Grok Task starts as native subagents", () => {
79 expect(
80 extractXAiAcpSubagentUpdate({
81 toolCallId: "task-1",
82 title: "Task",
83 status: "inProgress",
84 data: {
85 rawInput: {
86 description: "Explore server architecture",
87 prompt: "Audit apps/server.",
88 subagent_type: "generalPurpose",
89 model: "composer-2.5-fast",
90 },
91 },
92 }),
93 ).toEqual({
94 nativeTaskId: "task-1",
95 prompt: "Audit apps/server.",
96 title: "Explore server architecture",
97 model: "composer-2.5-fast",
98 status: "running",
99 childSessionId: null,
100 result: null,
101 suppressNormalTool: true,
102 });
103 });
104
105 it("extracts Grok child session lineage from completed Task output", () => {
106 expect(
107 extractXAiAcpSubagentUpdate({
108 toolCallId: "task-1",
109 title: "Task",
110 status: "completed",
111 data: {
112 rawInput: {
113 description: "Explore server architecture",
114 prompt: "Audit apps/server.",
115 subagent_type: "generalPurpose",
116 },
117 rawOutput: {
118 type: "Text",
119 text: [
120 "Server audit complete.",
121 "",
122 "Agent ID: 019f0220-e192-7c41-9e9d-b406bc3459c8 (resume supported)",
123 ].join("\n"),
124 },
125 },
126 }),
127 ).toEqual({
128 nativeTaskId: "task-1",
129 prompt: "Audit apps/server.",
130 title: "Explore server architecture",
131 model: null,
132 status: "completed",
133 childSessionId: "019f0220-e192-7c41-9e9d-b406bc3459c8",
134 result: "Server audit complete.",
135 suppressNormalTool: true,
136 });
137 });
138
139 it("keeps async spawn_subagent ACKs running and binds subagent_id", () => {
140 expect(
141 extractXAiAcpSubagentUpdate({
142 toolCallId: "call-spawn-1",
143 title: "spawn_subagent",
144 status: "completed",
145 data: {
146 rawInput: {
147 description: "Demo subagent wait and ls",
148 prompt: "Wait then ls.",
149 subagent_type: "general-purpose",
150 },
151 rawOutput: {
152 type: "Text",
153 text: [
154 "Subagent started in background.",
155 "subagent_id: 019f44a6-4820-7402-925d-bc862ee711dd",
156 "type: general-purpose",
157 "description: Demo subagent wait and ls",
158 "",
159 'Use get_command_or_subagent_output with task_ids=["019f44a6-4820-7402-925d-bc862ee711dd"] and timeout_ms to wait for results.',
160 ].join("\n"),
161 },
162 },
163 }),
164 ).toEqual({
165 nativeTaskId: "call-spawn-1",
166 prompt: "Wait then ls.",
167 title: "Demo subagent wait and ls",
168 model: null,
169 status: "running",
170 childSessionId: "019f44a6-4820-7402-925d-bc862ee711dd",
171 result: null,
172 suppressNormalTool: true,
173 });
174 });
175
176 it("hydrates subagent completion from get_command_or_subagent_output", () => {
177 expect(
178 extractXAiAcpSubagentUpdate({
179 toolCallId: "call-get-1",
180 title: "get_command_or_subagent_output",
181 status: "completed",
182 data: {
183 rawInput: {
184 task_ids: ["019f44a6-4820-7402-925d-bc862ee711dd"],
185 timeout_ms: 30000,
186 },
187 rawOutput: {
188 type: "Text",
189 text: [
190 "=== Task 019f44a6-4820-7402-925d-bc862ee711dd ===",
191 "Status: completed",
192 "Exit Code: 0",
193 "",
194 "=== Output ===",
195 "SUBAGENT_MARKER: 35 entries",
196 ].join("\n"),
197 },
198 },
199 }),
200 ).toEqual({
201 nativeTaskId: "call-get-1",
202 prompt: "",
203 title: null,
204 model: null,
205 status: "completed",
206 childSessionId: "019f44a6-4820-7402-925d-bc862ee711dd",
207 result: "SUBAGENT_MARKER: 35 entries",
208 suppressNormalTool: true,
209 });
210 });
211
212 it("attributes multi-task get_output envelopes to the result task_id", () => {
213 expect(
214 extractXAiAcpSubagentUpdate({
215 toolCallId: "call-get-multi",
216 title: "get_command_or_subagent_output",
217 status: "completed",
218 data: {
219 rawInput: {
220 task_ids: [
221 "019f44a6-4820-7402-925d-bc862ee711dd",
222 "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
223 ],
224 timeout_ms: 30000,
225 },
226 rawOutput: {
227 type: "TaskOutput",
228 Result: {
229 task_id: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
230 status: "completed",
231 exit_code: 0,
232 output: "SECOND_SUB_DONE\n",
233 },
234 },
235 },
236 }),
237 ).toMatchObject({
238 childSessionId: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
239 status: "completed",
240 result: "SECOND_SUB_DONE",
241 });
242 });
243
244 it("does not treat a subagent_id mentioned in result text as the completed identity", () => {
245 const requestedTaskId = "019f44a6-4820-7402-925d-bc862ee711dd";
246 const mentionedTaskId = "019f44b0-1b73-7f32-bb1b-1ff696f536e3";
247 const toolCall = {
248 toolCallId: "call-get-mentioned-id",
249 title: "get_command_or_subagent_output",
250 status: "completed" as const,
251 data: {
252 rawInput: {
253 variant: "TaskOutput",
254 task_ids: [requestedTaskId],
255 },
256 rawOutput: {
257 type: "TaskOutput",
258 Result: {
259 status: "completed",
260 exit_code: 0,
261 output: `Audited subagent_id: ${mentionedTaskId}; no issues found.`,
262 },
263 },
264 },
265 };
266
267 expect(extractXAiAcpSubagentUpdate(toolCall)).toMatchObject({
268 childSessionId: requestedTaskId,
269 status: "completed",
270 });
271 expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([
272 {
273 taskId: requestedTaskId,
274 status: "completed",
275 appendOutput: `Audited subagent_id: ${mentionedTaskId}; no issues found.`,
276 },
277 ]);
278 });
279
280 it("does not leak raw machine tags when get_output is only meta/result blocks", () => {
281 const metaOnlyToolCall = {
282 toolCallId: "call-get-meta-only",
283 title: "get_command_or_subagent_output",
284 status: "completed" as const,
285 data: {
286 rawInput: {
287 variant: "TaskOutput",
288 task_ids: ["019f44b0-1b73-7f32-bb1b-1ff696f536e3"],
289 timeout_ms: 20000,
290 },
291 rawOutput: {
292 type: "TaskOutput",
293 Result: {
294 task_id: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
295 status: "completed",
296 exit_code: 0,
297 output:
298 "<subagent_meta>id=019f44b0-1b73-7f32-bb1b-1ff696f536e3</subagent_meta>\n<subagent_result>done</subagent_result>\n",
299 },
300 },
301 },
302 };
303 expect(extractXAiAcpSubagentUpdate(metaOnlyToolCall)).toEqual({
304 nativeTaskId: "call-get-meta-only",
305 prompt: "",
306 title: null,
307 model: null,
308 status: "completed",
309 childSessionId: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
310 result: null,
311 suppressNormalTool: true,
312 });
313 expect(extractXAiBackgroundTaskCompletion(metaOnlyToolCall)).toEqual([
314 {
315 taskId: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
316 status: "completed",
317 appendOutput: "",
318 },
319 ]);
320 });
321
322 it("tracks text Monitor ACKs with generic titles and description-only input", () => {
323 const toolCall = {
324 toolCallId: "call-mon-generic-text",
325 title: "Tool",
326 status: "completed" as const,
327 data: {
328 rawInput: {
329 command: "echo mon_line_1",
330 description: "Demo monitor without variant",
331 },
332 rawOutput: {
333 type: "Text",
334 text: "Monitor started (task 019f44a5-87d1-7640-8e35-6a4667ffc873, timeout 36000000ms).\nYou will be notified on each event.",
335 },
336 },
337 };
338
339 const normalized = normalizeXAiAcpToolCallState(toolCall);
340 expect(isXAiMonitorTool(normalized)).toBe(true);
341 expect(normalized.status).toBe("inProgress");
342 expect(extractXAiMonitorTaskId(normalized)).toBe("019f44a5-87d1-7640-8e35-6a4667ffc873");
343 });
344
345 // regression: #23714 Recorded from Grok 1.0.77 calling stdio MCP tools through `use_tool`.
346 it("rewrites use_tool MCP calls and results into the generic ACP MCP shapes", () => {
347 const meta = { "x.ai/tool": { version: 1, name: "use_tool", kind: "use_tool" } };
348 const grokCall = (
349 toolCallId: string,
350 tool: string,
351 toolInput: Record<string, unknown>,
352 completion: Record<string, unknown>,
353 ) => {
354 const rawInput = { tool_name: tool, tool_input: toolInput };
355 const updates = [
356 { sessionUpdate: "tool_call", toolCallId, title: "use_tool", rawInput, _meta: meta },
357 {
358 sessionUpdate: "tool_call_update",
359 toolCallId,
360 kind: "other",
361 title: tool,
362 rawInput: { variant: "UseTool", ...rawInput },
363 _meta: meta,
364 },
365 { sessionUpdate: "tool_call_update", toolCallId, ...completion },
366 ];
367 let state: AcpToolCallState | undefined;
368 for (const update of updates) {
369 state = normalizeXAiAcpToolCallState(
370 mergeToolCallState(state, parseRecordedToolCallUpdate(update)),
371 );
372 }
373 return state!;
374 };
375 const page = { attachmentId: "abc-html", title: "T", height: 300 };
376
377 const rendered = grokCall(
378 "call-85597c6c-6fb8-4c9c-a6a8-12c4a74ebc96-1",
379 "t3-code__html_render",
380 { path: "a.html" },
381 {
382 status: "completed",
383 rawOutput: {
384 type: "MCP",
385 tool_name: "html_render",
386 server_name: "t3-code",
387 output: { OkayOutput: JSON.stringify({ htmlRender: page, message: "Shown" }) },
388 },
389 },
390 );
391 expect(extractMcpToolCallIdentity(rendered)).toEqual({
392 server: "t3-code",
393 tool: "html_render",
394 });
395 expect(rendered.data.rawInput).toMatchObject({ arguments: { path: "a.html" } });
396 expect(
397 htmlRenderFromToolItem({ toolName: "t3-code.html_render", output: rendered.data.rawOutput }),
398 ).toEqual(page);
399
400 const failed = grokCall(
401 "call-2baebdc5-2446-4ac2-9652-85f97a76a05b-2",
402 "pencil__browser",
403 { action: "load-page" },
404 {
405 status: "failed",
406 rawOutput: {
407 type: "MCP",
408 tool_name: "browser",
409 server_name: "pencil",
410 output: { Error: "Page not found" },
411 is_error: true,
412 },
413 },
414 );
415 expect(extractMcpToolCallIdentity(failed)).toEqual({ server: "pencil", tool: "browser" });
416 expect(compactDynamicToolOutput(failed.data.rawOutput)?.isError).toBe(true);
417 });
418
419 it("keeps Monitor ticks running while Grok reports them in progress", () => {
420 // Grok 1.0.41 ticks report in_progress with exit_code 0; only _x.ai/task_completed ends the monitor.
421 const command = "for i in 1 2 3; do sleep 8; echo tick $i; done";
422 const started = parseRecordedToolCallUpdate({
423 sessionUpdate: "tool_call_update",
424 toolCallId: "call-6b025a4e-621c-4526-a579-ba86ada2669c-0",
425 kind: "other",
426 title: "Start monitor: Watch three ticks eight seconds apart",
427 locations: [],
428 rawInput: {
429 variant: "Monitor",
430 command,
431 description: "Watch three ticks eight seconds apart",
432 timeout_ms: 36000000,
433 persistent: false,
434 },
435 });
436 const tick = parseRecordedToolCallUpdate({
437 sessionUpdate: "tool_call_update",
438 toolCallId: "call-6b025a4e-621c-4526-a579-ba86ada2669c-0",
439 status: "in_progress",
440 content: [{ type: "content", content: { type: "text", text: "tick 1\n" } }],
441 rawOutput: {
442 type: "Bash",
443 output: [116, 105, 99, 107, 32, 49, 10],
444 output_for_prompt: "tick 1\n",
445 exit_code: 0,
446 command,
447 truncated: false,
448 signal: null,
449 timed_out: false,
450 description: null,
451 current_dir: "<workspace>",
452 output_file: "",
453 total_bytes: 7,
454 },
455 });
456 const toolCall = normalizeXAiAcpToolCallState(mergeToolCallState(started, tick));
457 expect(isXAiMonitorTool(toolCall)).toBe(true);
458 expect(toolCall.status).toBe("inProgress");
459 });
460
461 it("finishes monitors from the recorded task_completed snapshot", () => {
462 const completed = {
463 sessionId: "01a0d660-c1bb-7842-91a3-02d91dc8b0d2",
464 update: {
465 sessionUpdate: "task_completed",
466 task_snapshot: {
467 task_id: "01a0d660-f98d-7ef3-a291-97af1c2b6455",
468 command: "for i in 1 2 3; do sleep 8; echo tick $i; done",
469 display_command: "[monitor] Watch three tick echoes",
470 output: "tick 1\ntick 2\ntick 3\n",
471 exit_code: 0,
472 kind: "monitor",
473 description: "Watch three tick echoes",
474 },
475 },
476 };
477 expect(xAiBackgroundTaskLifecycleMutation(completed, "completed")).toEqual({
478 sessionId: "01a0d660-c1bb-7842-91a3-02d91dc8b0d2",
479 taskId: "01a0d660-f98d-7ef3-a291-97af1c2b6455",
480 status: "completed",
481 output: "tick 1\ntick 2\ntick 3\n",
482 report: { kind: "monitor", label: "Watch three tick echoes" },
483 });
484 expect(
485 xAiBackgroundTaskLifecycleMutation(
486 {
487 ...completed,
488 update: { ...completed.update, task_snapshot: { task_id: "t", exit_code: 2 } },
489 },
490 "completed",
491 )?.status,
492 ).toBe("failed");
493 });
494
495 it("detects Monitor start ACKs from structured rawOutput when title is generic", () => {
496 const toolCall = {
497 toolCallId: "call-mon-generic-title",
498 title: "Tool",
499 status: "completed" as const,
500 data: {
501 rawInput: {
502 command: "echo mon_line",
503 description: "Demo monitor without variant",
504 },
505 rawOutput: {
506 type: "Monitor",
507 taskId: "019f44a5-87d1-7640-8e35-6a4667ffc873",
508 timeoutMs: 36000000,
509 persistent: false,
510 },
511 },
512 };
513 expect(isXAiMonitorTool(toolCall)).toBe(true);
514 expect(normalizeXAiAcpToolCallState(toolCall).status).toBe("inProgress");
515 expect(extractXAiMonitorTaskId(toolCall)).toBe("019f44a5-87d1-7640-8e35-6a4667ffc873");
516 });
517
518 it("completes status-less Bash results despite generic titles", () => {
519 const toolCall = {
520 toolCallId: "call-wake-1",
521 title: "Tool",
522 data: {
523 rawInput: {},
524 rawOutput: {
525 type: "Bash",
526 output: Array.from(new TextEncoder().encode("STREAM_1\nSTREAM_DONE\n")),
527 output_for_prompt: "STREAM_1\nSTREAM_DONE\n",
528 exit_code: 0,
529 command: "for i in 1 2; do echo STREAM_$i; done; echo STREAM_DONE",
530 },
531 },
532 };
533 expect(isXAiMonitorTool(toolCall)).toBe(false);
534 const normalized = normalizeXAiAcpToolCallState(toolCall);
535 expect(normalized.status).toBe("completed");
536 expect(normalized.title).toBe("for i in 1 2; do echo STREAM_$i; done; echo STREAM_DONE");
537 expect(
538 normalizeXAiAcpToolCallState({
539 ...toolCall,
540 data: {
541 ...toolCall.data,
542 rawOutput: {
543 ...toolCall.data.rawOutput,
544 command: `git commit -m "${"x".repeat(61)}🎉 ship it"`,
545 },
546 },
547 }).title,
548 ).toBe(`git commit -m "${"x".repeat(61)}...`);
549 expect(
550 normalizeXAiAcpToolCallState({
551 ...toolCall,
552 data: {
553 ...toolCall.data,
554 rawOutput: { ...toolCall.data.rawOutput, exit_code: 2 },
555 },
556 }).status,
557 ).toBe("failed");
558 });
559
560 it("keeps empty successful Bash updates running until native output or turn settlement", () => {
561 const normalized = normalizeXAiAcpToolCallState({
562 toolCallId: "call-bash-permission-ack",
563 title: "Ran command",
564 status: "completed",
565 data: {
566 rawInput: { command: "sleep 40" },
567 rawOutput: { type: "Bash", exit_code: 0 },
568 },
569 });
570 expect(normalized.status).toBe("inProgress");
571 });
572
573 it("completes structured command TaskOutput ids without treating them as subagents", () => {
574 // Oracle: BackgroundTaskStarted and TaskOutput from the Grok hang incident.
575 const toolCall: AcpToolCallState = {
576 toolCallId: "call-poll",
577 title: "get_command_or_subagent_output",
578 status: "completed",
579 data: {
580 rawInput: {
581 variant: "TaskOutput",
582 task_ids: ["call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29"],
583 },
584 rawOutput: {
585 type: "TaskOutput",
586 Result: {
587 task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
588 status: "completed",
589 exit_code: 0,
590 output: "done",
591 },
592 },
593 },
594 };
595 expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([
596 {
597 taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
598 status: "completed",
599 appendOutput: "done",
600 },
601 ]);
602 expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();
603 });
604
605 it("keeps the normal tool frame for a command result from a mixed-ID poll", () => {
606 // Oracle: review 4325739061 requires the result ID to override requested subagent IDs.
607 const toolCall: AcpToolCallState = {
608 toolCallId: "call-mixed-poll",
609 title: "get_command_or_subagent_output",
610 status: "completed",
611 data: {
612 rawInput: {
613 variant: "TaskOutput",
614 task_ids: [
615 "019f44a6-4820-7402-925d-bc862ee711dd",
616 "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
617 ],
618 },
619 rawOutput: {
620 type: "TaskOutput",
621 Result: {
622 task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
623 status: "completed",
624 exit_code: 0,
625 output: "done",
626 },
627 },
628 },
629 };
630 expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();
631 expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([
632 {
633 taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
634 status: "completed",
635 appendOutput: "done",
636 },
637 ]);
638 });
639
640 it("hydrates monitor completion from a standalone TaskOutput frame without rawInput", () => {
641 expect(
642 extractXAiBackgroundTaskCompletion({
643 toolCallId: "call-c29e64dd-ce5d-4eac-a6ca-c20513fefac3-1",
644 title: "[monitor] Stream numbered markers every 3s (019f54a0)",
645 status: "completed",
646 data: {
647 rawOutput: {
648 type: "TaskOutput",
649 Result: {
650 task_id: "019f54a0-06a8-77f2-8214-e24937cad564",
651 command: "[monitor] Stream numbered markers every 3s",
652 status: "completed",
653 exit_code: 0,
654 output: "STREAM_1\nSTREAM_DONE\n",
655 },
656 },
657 },
658 }),
659 ).toMatchObject([
660 {
661 taskId: "019f54a0-06a8-77f2-8214-e24937cad564",
662 status: "completed",
663 },
664 ]);
665 });
666
667 it("hydrates every requested monitor when TaskOutput has no result task_id", () => {
668 expect(
669 extractXAiBackgroundTaskCompletion({
670 toolCallId: "call-get-multi-mon",
671 title: "get_command_or_subagent_output",
672 status: "completed",
673 data: {
674 rawInput: {
675 variant: "TaskOutput",
676 task_ids: [
677 "019f44a6-4820-7402-925d-bc862ee711dd",
678 "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
679 ],
680 },
681 rawOutput: {
682 type: "TaskOutput",
683 Result: {
684 status: "completed",
685 exit_code: 0,
686 output: "BOTH_DONE\n",
687 },
688 },
689 },
690 }),
691 ).toEqual([
692 {
693 taskId: "019f44a6-4820-7402-925d-bc862ee711dd",
694 status: "completed",
695 appendOutput: "BOTH_DONE",
696 },
697 {
698 taskId: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
699 status: "completed",
700 appendOutput: "BOTH_DONE",
701 },
702 ]);
703 });
704
705 it("keeps every requested monitor running when a completed poll has no terminal task status", () => {
706 expect(
707 extractXAiBackgroundTaskCompletion({
708 toolCallId: "call-get-running-monitors",
709 title: "get_command_or_subagent_output",
710 status: "completed",
711 data: {
712 rawInput: {
713 variant: "TaskOutput",
714 task_ids: [
715 "019f44a6-4820-7402-925d-bc862ee711dd",
716 "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
717 ],
718 },
719 rawOutput: {
720 type: "TaskOutput",
721 Result: {
722 output: "No task has reached a terminal state.",
723 },
724 },
725 },
726 }),
727 ).toEqual([
728 {
729 taskId: "019f44a6-4820-7402-925d-bc862ee711dd",
730 status: "running",
731 appendOutput: "No task has reached a terminal state.",
732 },
733 {
734 taskId: "019f44b0-1b73-7f32-bb1b-1ff696f536e3",
735 status: "running",
736 appendOutput: "No task has reached a terminal state.",
737 },
738 ]);
739 });
740
741 it("treats Exit Code: -1 text envelopes as failed", () => {
742 expect(
743 extractXAiBackgroundTaskCompletion({
744 toolCallId: "call-get-neg",
745 title: "get_command_or_subagent_output",
746 status: "completed",
747 data: {
748 rawInput: {
749 variant: "TaskOutput",
750 task_ids: ["019f44b8-8e98-7c80-a40e-df1e26a5f9e3"],
751 },
752 rawOutput: {
753 type: "Text",
754 text: ["=== Task 019f44b8-8e98-7c80-a40e-df1e26a5f9e3 ===", "Exit Code: -1"].join("\n"),
755 },
756 },
757 }),
758 ).toMatchObject([
759 {
760 taskId: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3",
761 status: "failed",
762 },
763 ]);
764 });
765
766 // KillTask replies can report killed and already_exited outcomes.
767 it.each([
768 { rawInput: { task_id: "call-bg-1" }, rawOutput: { type: "KillTask" } },
769 { rawInput: { task_id: "call-bg-1" }, rawOutput: { type: "KillTask", outcome: "killed" } },
770 { rawInput: { variant: "KillTask", task_id: "call-bg-1" } },
771 {
772 rawInput: { variant: "KillTask", task_id: "call-bg-1" },
773 rawOutput: { type: "KillTask", outcome: "already_exited" },
774 },
775 ])("closes a background command from structured KillTask fields: %j", (data) => {
776 expect(
777 extractXAiKilledBackgroundTasks({
778 toolCallId: "call-kill",
779 title: "kill call-bg-1 (killed)",
780 status: "completed",
781 data,
782 }),
783 ).toEqual([{ taskId: "call-bg-1", status: "completed", appendOutput: "" }]);
784 expect(
785 extractXAiAcpSubagentUpdate({
786 toolCallId: "call-kill",
787 title: "kill call-bg-1 (killed)",
788 status: "completed",
789 data,
790 }),
791 ).toBeUndefined();
792 });
793
794 // Native child status still comes from its lifecycle/result path, not the kill RPC.
795 it.each(["Kill", "KillTask"])(
796 "keeps %s aimed at a native child out of child result parsing",
797 (variant) => {
798 expect(
799 extractXAiAcpSubagentUpdate({
800 toolCallId: "call-kill-child",
801 title: "kill 019f44b8-8e98-7c80-a40e-df1e26a5f9e3 (killed)",
802 status: "completed",
803 data: {
804 rawInput: { variant, task_id: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3" },
805 rawOutput: { type: "KillTask", outcome: "killed" },
806 },
807 }),
808 ).toBeUndefined();
809 },
810 );
811
812 // A successful RPC is not proof of a successful kill when its outcome says otherwise.
813 it.each([
814 { type: "KillTask", outcome: "failed" },
815 { type: "KillTask", Result: { task_id: "call-bg-1", outcome: "error" } },
816 ])("ignores a KillTask whose outcome is not a kill: %j", (rawOutput) => {
817 expect(
818 extractXAiKilledBackgroundTasks({
819 toolCallId: "call-kill",
820 title: "kill call-bg-1 (failed)",
821 status: "completed",
822 data: {
823 rawInput: { variant: "KillTask", task_id: "call-bg-1" },
824 rawOutput,
825 },
826 }),
827 ).toEqual([]);
828 });
829
830 it.each(["failed", "inProgress"] as const)(
831 "does not close the target of a %s KillTask call",
832 (status) => {
833 expect(
834 extractXAiKilledBackgroundTasks({
835 toolCallId: "call-kill",
836 title: "kill call-bg-1 (killed)",
837 status,
838 data: {
839 rawInput: { variant: "KillTask", task_id: "call-bg-1" },
840 rawOutput: { type: "KillTask", outcome: "killed" },
841 },
842 }),
843 ).toEqual([]);
844 },
845 );
846
847 it("tombstones confirmed kills and ignores failed kill calls", () => {
848 expect(
849 extractXAiKilledBackgroundTasks({
850 toolCallId: "call-kill-1",
851 title: "kill_command_or_subagent",
852 status: "completed",
853 data: {
854 rawInput: {
855 variant: "Kill",
856 task_ids: ["call-bg-1", "call-bg-2", "call-bg-1"],
857 },
858 },
859 }),
860 ).toEqual([
861 { taskId: "call-bg-1", status: "completed", appendOutput: "" },
862 { taskId: "call-bg-2", status: "completed", appendOutput: "" },
863 ]);
864 expect(
865 extractXAiKilledBackgroundTasks({
866 toolCallId: "call-kill-2",
867 title: "Tool",
868 status: "failed",
869 data: { rawInput: { variant: "kill", task_id: "call-bg-3" } },
870 }),
871 ).toEqual([]);
872 expect(
873 extractXAiKilledBackgroundTasks({
874 toolCallId: "call-kill-3",
875 title: "kill_command_or_subagent",
876 status: "inProgress",
877 data: { rawInput: { task_ids: ["call-bg-4"] } },
878 }),
879 ).toEqual([]);
880 expect(
881 extractXAiKilledBackgroundTasks({
882 toolCallId: "call-get",
883 title: "get_command_or_subagent_output",
884 status: "completed",
885 data: { rawInput: { variant: "TaskOutput", task_ids: ["call-bg-5"] } },
886 }),
887 ).toEqual([]);
888 });
889
890 it("maps task lifecycle notifications to background mutations", () => {
891 expect(
892 xAiBackgroundTaskLifecycleMutation(
893 {
894 sessionId: "session-1",
895 update: {
896 sessionUpdate: "task_backgrounded",
897 tool_call_id: "call-bg-1",
898 task_id: "call-bg-1",
899 },
900 },
901 "running",
902 ),
903 ).toEqual({ sessionId: "session-1", taskId: "call-bg-1", status: "running" });
904 expect(
905 xAiBackgroundTaskLifecycleMutation(
906 {
907 sessionId: "session-1",
908 update: {
909 sessionUpdate: "task_completed",
910 task_snapshot: { task_id: "call-bg-1" },
911 },
912 },
913 "completed",
914 ),
915 ).toEqual({ sessionId: "session-1", taskId: "call-bg-1", status: "completed" });
916 expect(
917 xAiBackgroundTaskLifecycleMutation(
918 { sessionId: "session-1", update: { sessionUpdate: "task_completed" } },
919 "completed",
920 ),
921 ).toBeNull();
922 });
923
924 it("keeps a standalone TaskOutput completion terminal through normalize", () => {
925 expect(
926 normalizeXAiAcpToolCallState({
927 toolCallId: "call-c29e64dd-ce5d-4eac-a6ca-c20513fefac3-1",
928 title: "[monitor] Stream numbered markers every 3s (019f54a0)",
929 status: "completed",
930 data: {
931 rawOutput: {
932 type: "TaskOutput",
933 Result: {
934 task_id: "019f54a0-06a8-77f2-8214-e24937cad564",
935 status: "completed",
936 exit_code: 0,
937 output: "STREAM_DONE\n",
938 },
939 },
940 },
941 }).status,
942 ).toBe("completed");
943 });
944
945 it("parses monitor event lines and end reminders", () => {
946 expect(
947 extractXAiAcpBackgroundToolMutation(
948 '<monitor-event task_id="019f44a5-87d1-7640-8e35-6a4667ffc873">\n[Demo] mon_line_1\n</monitor-event>',
949 ),
950 ).toEqual([
951 {
952 taskId: "019f44a5-87d1-7640-8e35-6a4667ffc873",
953 status: "running",
954 appendOutput: "[Demo] mon_line_1\n",
955 },
956 ]);
957 expect(
958 extractXAiAcpBackgroundToolMutation(
959 [
960 "<system-reminder>",
961 'Monitor "019f44a5-87d1-7640-8e35-6a4667ffc873" ended: [monitor ended: exited (code 0)].',
962 "Description: Demo monitor",
963 "</system-reminder>",
964 ].join("\n"),
965 ),
966 ).toMatchObject([
967 {
968 taskId: "019f44a5-87d1-7640-8e35-6a4667ffc873",
969 status: "completed",
970 },
971 ]);
972 expect(
973 extractXAiAcpBackgroundToolMutation(
974 [
975 "<system-reminder>",
976 'Monitor "019f44a5-87d1-7640-8e35-6a4667ffc873" ended: [monitor ended: exited (code 0)].',
977 "Description: watch error logs for failed deploys",
978 "error: nothing found",
979 "</system-reminder>",
980 ].join("\n"),
981 ),
982 ).toMatchObject([
983 {
984 taskId: "019f44a5-87d1-7640-8e35-6a4667ffc873",
985 status: "completed",
986 },
987 ]);
988 });
989
990 it("parses batched monitor event blocks as running mutations", () => {
991 expect(
992 extractXAiAcpBackgroundToolMutation(
993 [
994 "3 monitor events from 1 monitor (use get_command_or_subagent_output to identify each monitor):",
995 "",
996 '<monitor description="Stream STREAM_i every 3s" task_id="019f545d-4d39-7001-b1c8-c7744c448ec1">',
997 "[1] STREAM_7",
998 "[2] STREAM_8",
999 "[3] STREAM_9",
1000 "</monitor>",
1001 ].join("\n"),
1002 ),
1003 ).toEqual([
1004 {
1005 taskId: "019f545d-4d39-7001-b1c8-c7744c448ec1",
1006 status: "running",
1007 appendOutput: "[1] STREAM_7\n[2] STREAM_8\n[3] STREAM_9\n",
1008 },
1009 ]);
1010 });
1011
1012 it("parses the subagent completed reminder as an end notice", () => {
1013 expect(
1014 extractXAiAcpSubagentEndNotice(
1015 [
1016 "<system-reminder>",
1017 'Background subagent "019f5470-bf92-7a90-afb3-5a6cea5b34a3" (general-purpose: "Run sleep then echo token") completed successfully.',
1018 "Duration: 28.8s | Tool calls: 1 | Turns: 1",
1019 'Use get_task_output("019f5470-bf92-7a90-afb3-5a6cea5b34a3") to see the full output.',
1020 "</system-reminder>",
1021 ].join("\n"),
1022 ),
1023 ).toEqual({
1024 childSessionId: "019f5470-bf92-7a90-afb3-5a6cea5b34a3",
1025 status: "completed",
1026 });
1027 });
1028
1029 it("ignores prompt text that merely mentions subagents", () => {
1030 expect(
1031 extractXAiAcpSubagentEndNotice("Live-test post-settle subagent completion."),
1032 ).toBeUndefined();
1033 expect(
1034 extractXAiAcpSubagentEndNotice(
1035 'Background subagent "019f5470-bf92-7a90-afb3-5a6cea5b34a3" (general-purpose: "Run sleep then echo token") is still running.',
1036 ),
1037 ).toBeUndefined();
1038 });
1039
1040 it("does not treat nested parentheses in the title as the outcome verb", () => {
1041 expect(
1042 extractXAiAcpSubagentEndNotice(
1043 'Background subagent "019f5470-bf92-7a90-afb3-5a6cea5b34a3" (general-purpose: "Check (backend) failed tests") is still running.',
1044 ),
1045 ).toBeUndefined();
1046 expect(
1047 extractXAiAcpSubagentEndNotice(
1048 'Background subagent "019f5470-bf92-7a90-afb3-5a6cea5b34a3" (general-purpose: "Check (backend) failed tests") completed successfully.',
1049 ),
1050 ).toEqual({
1051 childSessionId: "019f5470-bf92-7a90-afb3-5a6cea5b34a3",
1052 status: "completed",
1053 });
1054 });
1055
1056 it("extracts questions from the real xAI ask_user_question payload shape", () => {
1057 const questions = extractXAiAskUserQuestions({
1058 sessionId: "session-1",
1059 toolCallId: "tool-call-1",
1060 mode: "default",
1061 questions: [
1062 {
1063 id: "scope",
1064 question: "Which scope should Grok use?",
1065 options: [
1066 { label: "Workspace", description: "Use the current workspace" },
1067 { label: "Session", description: "Only use this session" },
1068 ],
1069 },
1070 ],
1071 });
1072
1073 expect(questions).toEqual([
1074 {
1075 id: "scope",
1076 header: "Question",
1077 question: "Which scope should Grok use?",
1078 multiSelect: false,
1079 options: [
1080 { label: "Workspace", description: "Use the current workspace" },
1081 { label: "Session", description: "Only use this session" },
1082 ],
1083 },
1084 ]);
1085 });
1086
1087 it("extracts questions from wrapped _x.ai extension payloads", () => {
1088 const payload = {
1089 method: "_x.ai/ask_user_question",
1090 params: {
1091 sessionId: "session-1",
1092 toolCallId: "tool-call-1",
1093 mode: "plan",
1094 questions: [
1095 {
1096 question: "Which changes should be included?",
1097 multiSelect: true,
1098 options: [{ label: "Tests" }, { label: "Docs" }],
1099 },
1100 ],
1101 },
1102 };
1103 const decoded = decodeXAiAskUserQuestionRequest(payload);
1104 const questions = extractXAiAskUserQuestions(decoded);
1105
1106 expect(questions).toEqual([
1107 {
1108 id: "Which changes should be included?",
1109 header: "Question",
1110 question: "Which changes should be included?",
1111 multiSelect: true,
1112 options: [
1113 { label: "Tests", description: "Tests" },
1114 { label: "Docs", description: "Docs" },
1115 ],
1116 },
1117 ]);
1118 });
1119
1120 it("treats nullable multiSelect from Grok as single-select", () => {
1121 const questions = extractXAiAskUserQuestions({
1122 sessionId: "session-1",
1123 toolCallId: "tool-call-1",
1124 mode: "default",
1125 questions: [
1126 {
1127 question: "Which label should Grok use?",
1128 multiSelect: null,
1129 options: [
1130 { label: "Alpha", description: "Use the Alpha label" },
1131 { label: "Beta", description: "Use the Beta label" },
1132 { label: "Other", description: "Use the Other label" },
1133 ],
1134 },
1135 ],
1136 });
1137
1138 expect(questions).toEqual([
1139 {
1140 id: "Which label should Grok use?",
1141 header: "Question",
1142 question: "Which label should Grok use?",
1143 multiSelect: false,
1144 options: [
1145 { label: "Alpha", description: "Use the Alpha label" },
1146 { label: "Beta", description: "Use the Beta label" },
1147 { label: "Other", description: "Use the Other label" },
1148 ],
1149 },
1150 ]);
1151 });
1152
1153 it("maps UI question ids back to xAI question text in accepted responses", () => {
1154 const response = makeXAiAskUserQuestionResponse(
1155 {
1156 sessionId: "session-1",
1157 toolCallId: "tool-call-1",
1158 mode: "default",
1159 questions: [
1160 {
1161 id: "scope",
1162 question: "Which scope should Grok use?",
1163 options: [
1164 { label: "workspace", description: "Use the current workspace" },
1165 { label: "session", description: "Only use this session" },
1166 ],
1167 },
1168 ],
1169 },
1170 { scope: "workspace" },
1171 );
1172
1173 expect(response).toEqual({
1174 outcome: "accepted",
1175 answers: {
1176 "Which scope should Grok use?": ["workspace"],
1177 },
1178 });
1179 });
1180
1181 it("encodes typed custom answers as xAI Other annotations", () => {
1182 const response = makeXAiAskUserQuestionResponse(
1183 {
1184 method: "x.ai/ask_user_question",
1185 params: {
1186 sessionId: "session-1",
1187 toolCallId: "tool-call-1",
1188 mode: "default",
1189 questions: [
1190 {
1191 question: "Which ice cream flavor?",
1192 options: [
1193 { label: "vanilla", description: "Vanilla flavor" },
1194 { label: "chocolate", description: "Chocolate flavor" },
1195 ],
1196 },
1197 ],
1198 },
1199 },
1200 { "Which ice cream flavor?": "pistachio" },
1201 );
1202
1203 expect(response).toEqual({
1204 outcome: "accepted",
1205 answers: {
1206 "Which ice cream flavor?": ["Other"],
1207 },
1208 annotations: {
1209 "Which ice cream flavor?": {
1210 notes: "pistachio",
1211 },
1212 },
1213 });
1214 });
1215
1216 it("does not echo preview annotations for multi-select answers", () => {
1217 const response = makeXAiAskUserQuestionResponse(
1218 {
1219 sessionId: "session-1",
1220 toolCallId: "tool-call-1",
1221 mode: "default",
1222 questions: [
1223 {
1224 question: "Which files should Grok touch?",
1225 multiSelect: true,
1226 options: [
1227 {
1228 label: "Tests",
1229 description: "Update tests",
1230 preview: "test preview",
1231 },
1232 {
1233 label: "Docs",
1234 description: "Update docs",
1235 preview: "docs preview",
1236 },
1237 ],
1238 },
1239 ],
1240 },
1241 { "Which files should Grok touch?": ["Tests", "Docs"] },
1242 );
1243
1244 expect(response).toEqual({
1245 outcome: "accepted",
1246 answers: {
1247 "Which files should Grok touch?": ["Tests", "Docs"],
1248 },
1249 });
1250 });
1251
1252 it.effect("settles a hung prompt from a root-session prompt_complete notification", () =>
1253 Effect.gen(function* () {
1254 const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
1255 const hungPrompt = yield* Deferred.make<never>();
1256 const baseRuntime = {
1257 start: () =>
1258 Effect.succeed({
1259 sessionId: "root-session",
1260 initializeResult: {},
1261 sessionSetupResult: {},
1262 modelConfigId: undefined,
1263 }),
1264 prompt: () => Deferred.await(hungPrompt),
1265 cancel: Effect.void,
1266 handleExtNotification: (
1267 method: string,
1268 _schema: unknown,
1269 handler: (notification: unknown) => Effect.Effect<void>,
1270 ) => {
1271 handlers.set(method, handler);
1272 return Effect.void;
1273 },
1274 handleExtRequest: () => Effect.void,
1275 } as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
1276
1277 const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
1278 const promptFiber = yield* runtime
1279 .prompt({ prompt: [{ type: "text", text: "hi" }] })
1280 .pipe(Effect.forkChild);
1281 yield* Effect.yieldNow;
1282 const promptCompleteHandler = handlers.get("x.ai/session/prompt_complete");
1283 expect(promptCompleteHandler).toBeDefined();
1284 yield* promptCompleteHandler!({
1285 sessionId: "root-session",
1286 stopReason: "end_turn",
1287 });
1288 const response = yield* Fiber.join(promptFiber);
1289 expect(response.stopReason).toBe("end_turn");
1290 expect(handlers.has("_x.ai/session/prompt_complete")).toBe(true);
1291 }),
1292 );
1293
1294 it.effect("fails a hung prompt from an xAI rate-limit completion (#8358)", () =>
1295 Effect.gen(function* () {
1296 const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
1297 const hungPrompt = yield* Deferred.make<never>();
1298 const baseRuntime = {
1299 start: () =>
1300 Effect.succeed({
1301 sessionId: "root-session",
1302 initializeResult: {},
1303 sessionSetupResult: {},
1304 modelConfigId: undefined,
1305 }),
1306 prompt: () => Deferred.await(hungPrompt),
1307 cancel: Effect.void,
1308 handleExtNotification: (
1309 method: string,
1310 _schema: unknown,
1311 handler: (notification: unknown) => Effect.Effect<void>,
1312 ) => {
1313 handlers.set(method, handler);
1314 return Effect.void;
1315 },
1316 handleExtRequest: () => Effect.void,
1317 } as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
1318
1319 const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
1320 const promptFiber = yield* runtime
1321 .prompt({ prompt: [{ type: "text", text: "hi" }] })
1322 .pipe(Effect.forkChild);
1323 yield* Effect.yieldNow;
1324
1325 const promptCompleteHandler = handlers.get("x.ai/session/prompt_complete");
1326 expect(promptCompleteHandler).toBeDefined();
1327 yield* promptCompleteHandler!({
1328 sessionId: "root-session",
1329 stopReason: "rate_limit",
1330 });
1331 const error = yield* Fiber.join(promptFiber).pipe(Effect.flip);
1332 expect(error).toMatchObject({
1333 _tag: "AcpRequestError",
1334 code: -32003,
1335 errorMessage: "Grok usage limit reached. Try again later.",
1336 });
1337 }),
1338 );
1339
1340 it("maps subagent_finished to a notice only for statuses Grok defines", () => {
1341 const finished = (update: Record<string, unknown>) =>
1342 xAiSubagentFinishedNotice({
1343 sessionId: "root-session",
1344 update: {
1345 sessionUpdate: "subagent_finished",
1346 subagent_id: "child-session",
1347 child_session_id: "child-session",
1348 tool_calls: 2,
1349 turns: 1,
1350 duration_ms: 23734,
1351 ...update,
1352 } as never,
1353 });
1354 expect(finished({ status: "completed", output: "SUBAGENT_DONE", will_wake: true })).toEqual({
1355 sessionId: "root-session",
1356 childSessionId: "child-session",
1357 status: "completed",
1358 result: "SUBAGENT_DONE",
1359 });
1360 expect(finished({ status: "failed", error: "tool crashed" })).toMatchObject({
1361 status: "failed",
1362 result: "tool crashed",
1363 });
1364 expect(
1365 finished({ status: "cancelled", error: "interrupted by process restart" }),
1366 ).toMatchObject({ status: "cancelled", result: "interrupted by process restart" });
1367 expect(finished({ status: "failed", output: "partial" })).toMatchObject({ result: null });
1368 expect(finished({ status: "timed_out" })).toBeNull();
1369 expect(finished({})).toBeNull();
1370 expect(finished({ status: "completed", child_session_id: undefined })).toBeNull();
1371 });
1372
1373 it.effect("settles a hung prompt from released _x.ai/session_notification turns", () =>
1374 Effect.gen(function* () {
1375 const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
1376 const hungPrompt = yield* Deferred.make<never>();
1377 const baseRuntime = {
1378 start: () =>
1379 Effect.succeed({
1380 sessionId: "root-session",
1381 initializeResult: {},
1382 sessionSetupResult: {},
1383 modelConfigId: undefined,
1384 }),
1385 prompt: () => Deferred.await(hungPrompt),
1386 cancel: Effect.void,
1387 handleExtNotification: (
1388 method: string,
1389 _schema: unknown,
1390 handler: (notification: unknown) => Effect.Effect<void>,
1391 ) => {
1392 handlers.set(method, handler);
1393 return Effect.void;
1394 },
1395 handleExtRequest: () => Effect.void,
1396 } as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
1397
1398 const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
1399 const promptFiber = yield* runtime
1400 .prompt({ prompt: [{ type: "text", text: "hi" }] })
1401 .pipe(Effect.forkChild);
1402 yield* Effect.yieldNow;
1403 const sessionNotificationHandler = handlers.get("_x.ai/session_notification");
1404 expect(sessionNotificationHandler).toBeDefined();
1405 yield* sessionNotificationHandler!({
1406 sessionId: "root-session",
1407 update: {
1408 sessionUpdate: "turn_completed",
1409 prompt_id: "t3-xai-prompt-1",
1410 stop_reason: "end_turn",
1411 },
1412 });
1413 const response = yield* Fiber.join(promptFiber);
1414 expect(response.stopReason).toBe("end_turn");
1415 expect(handlers.has("_x.ai/session/update")).toBe(true);
1416 }),
1417 );
1418
1419 it.effect("injects promptId and requestId into prompt _meta", () =>
1420 Effect.gen(function* () {
1421 let capturedMeta: Record<string, unknown> | null | undefined;
1422 const baseRuntime = {
1423 start: () => Effect.succeed({ sessionId: "session-1" }),
1424 prompt: (payload: { readonly _meta?: Record<string, unknown> | null }) => {
1425 capturedMeta = payload._meta ?? null;
1426 return Effect.succeed({ stopReason: "end_turn" as const });
1427 },
1428 cancel: Effect.void,
1429 handleExtNotification: () => Effect.void,
1430 handleExtRequest: () => Effect.void,
1431 } as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
1432
1433 const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
1434 yield* runtime.prompt({ prompt: [{ type: "text", text: "hi" }] });
1435
1436 expect(typeof capturedMeta?.promptId).toBe("string");
1437 expect(capturedMeta).toMatchObject({
1438 promptId: capturedMeta?.promptId,
1439 requestId: capturedMeta?.promptId,
1440 });
1441 }),
1442 );
1443
1444 it.effect("cancels pending completions without restarting a stalled runtime", () =>
1445 Effect.gen(function* () {
1446 const hungStart = yield* Deferred.make<never>();
1447 const hungPrompt = yield* Deferred.make<never>();
1448 let startCount = 0;
1449 let cancelCalled = false;
1450 const baseRuntime = {
1451 start: () => {
1452 startCount += 1;
1453 return startCount === 1
1454 ? Effect.succeed({
1455 sessionId: "root-session",
1456 initializeResult: {},
1457 sessionSetupResult: {},
1458 modelConfigId: undefined,
1459 })
1460 : Deferred.await(hungStart);
1461 },
1462 prompt: () => Deferred.await(hungPrompt),
1463 cancel: Effect.sync(() => {
1464 cancelCalled = true;
1465 }),
1466 handleExtNotification: () => Effect.void,
1467 handleExtRequest: () => Effect.void,
1468 } as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
1469
1470 const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
1471 const promptFiber = yield* runtime
1472 .prompt({ prompt: [{ type: "text", text: "hi" }] })
1473 .pipe(Effect.forkChild);
1474 yield* Effect.yieldNow;
1475
1476 yield* runtime.cancel;
1477
1478 expect(cancelCalled).toBe(true);
1479 expect(startCount).toBe(1);
1480 expect((yield* Fiber.join(promptFiber)).stopReason).toBe("cancelled");
1481 }),
1482 );
1483 });
1484
1485 describe("Grok exit_plan_mode capture (#8358)", () => {
1486 it("extracts plan markdown from exit_plan_mode payloads", () => {
1487 const decode = Schema.decodeUnknownSync(XAiExitPlanModeRequest);
1488 const direct = decode({
1489 sessionId: "session-1",
1490 toolCallId: "exit-1",
1491 planContent: "# Plan\n\n- do the thing\n",
1492 });
1493 expect(extractXAiExitPlanMarkdown(direct)).toBe("# Plan\n\n- do the thing");
1494
1495 const wrapped = decode({
1496 method: "_x.ai/exit_plan_mode",
1497 params: {
1498 sessionId: "session-1",
1499 toolCallId: "exit-1",
1500 planContent: null,
1501 },
1502 });
1503 expect(extractXAiExitPlanMarkdown(wrapped, " # fallback plan ")).toBe("# fallback plan");
1504 expect(extractXAiExitPlanMarkdown(wrapped, "")).toBe(XAI_EMPTY_PLAN_MARKDOWN);
1505 expect(extractXAiExitPlanMarkdown(wrapped)).toBe(XAI_EMPTY_PLAN_MARKDOWN);
1506 });
1507 it("identifies Grok plan.md paths and extracts markdown from tool call data", () => {
1508 const home = "/home/ada";
1509 const linuxHost = { platform: "linux" as const, environment: {}, homeDirectory: home };
1510 const windowsHost = { platform: "win32" as const, environment: {}, homeDirectory: home };
1511 const grokHomeHost = {
1512 platform: "linux" as const,
1513 environment: { GROK_HOME: "/opt/grok-data" },
1514 homeDirectory: home,
1515 };
1516 const sessionPlan = `${home}/.grok/sessions/abc/plan.md`;
1517 const nestedSessionPlan = `${home}/.grok/sessions/%2Fhome%2Fproj/019fd20e-c563-70a0-b801-a6bc51815a9b/plan.md`;
1518 expect(isGrokPlanMarkdownPath(sessionPlan, linuxHost)).toBe(true);
1519 expect(isGrokPlanMarkdownPath(nestedSessionPlan, linuxHost)).toBe(true);
1520 expect(isGrokPlanMarkdownPath("~/.grok/sessions/abc/plan.md", linuxHost)).toBe(true);
1521 expect(isGrokPlanMarkdownPath("/tmp/mock-home/.grok/sessions/sess/plan.md", linuxHost)).toBe(
1522 true,
1523 );
1524 expect(isGrokPlanMarkdownPath("/home/other/.grok/sessions/sess/plan.md", linuxHost)).toBe(true);
1525 expect(isGrokPlanMarkdownPath("/HOME/other/.grok/sessions/sess/plan.md", linuxHost)).toBe(
1526 false,
1527 );
1528 expect(isGrokPlanMarkdownPath("C:/Users/other/.grok/sessions/id/plan.md", windowsHost)).toBe(
1529 true,
1530 );
1531 expect(isGrokPlanMarkdownPath("c:/users/OTHER/.GROK/SESSIONS/id/PLAN.MD", windowsHost)).toBe(
1532 true,
1533 );
1534 expect(
1535 isGrokPlanMarkdownPath("C:\\Users\\other\\.grok\\sessions\\id\\plan.md", windowsHost),
1536 ).toBe(true);
1537 expect(isGrokPlanMarkdownPath("/opt/grok-data/sessions/sess/plan.md", grokHomeHost)).toBe(true);
1538 expect(
1539 isGrokPlanMarkdownPath("/OPT/GROK-DATA/sessions/sess/plan.md", {
1540 platform: "win32",
1541 environment: { GROK_HOME: "/opt/grok-data" },
1542 homeDirectory: home,
1543 }),
1544 ).toBe(true);
1545 expect(isGrokPlanMarkdownPath("/OPT/GROK-DATA/sessions/sess/plan.md", grokHomeHost)).toBe(
1546 false,
1547 );
1548 expect(isGrokPlanMarkdownPath("plan.md", linuxHost)).toBe(false);
1549 expect(isGrokPlanMarkdownPath("/repo/docs/plan.md", linuxHost)).toBe(false);
1550 expect(isGrokPlanMarkdownPath("/tmp/other.md", linuxHost)).toBe(false);
1551 expect(isGrokPlanMarkdownPath("/repo/.grok/sessions/example/plan.md", linuxHost)).toBe(false);
1552 expect(
1553 isGrokPlanMarkdownPath(`${home}/project/.grok/sessions/example/plan.md`, linuxHost),
1554 ).toBe(false);
1555 expect(
1556 isGrokPlanMarkdownPath("/home/other/.grok/sessions/../../project/plan.md", linuxHost),
1557 ).toBe(false);
1558 expect(
1559 isGrokPlanMarkdownPath("/home/other/.grok/sessions/foo/../../../project/plan.md", linuxHost),
1560 ).toBe(false);
1561
1562 expect(
1563 extractGrokPlanMarkdownFromToolCallData(
1564 {
1565 rawInput: {
1566 file_path: sessionPlan,
1567 content: "# From rawInput\n\n- a\n",
1568 },
1569 },
1570 linuxHost,
1571 ),
1572 ).toBe("# From rawInput\n\n- a");
1573
1574 expect(
1575 extractGrokPlanMarkdownFromToolCallData(
1576 {
1577 content: [
1578 {
1579 type: "diff",
1580 path: sessionPlan,
1581 oldText: "",
1582 newText: "# From diff\n\n- b\n",
1583 },
1584 ],
1585 },
1586 linuxHost,
1587 ),
1588 ).toBe("# From diff\n\n- b");
1589
1590 expect(
1591 extractGrokPlanMarkdownFromToolCallData(
1592 {
1593 rawInput: { file_path: sessionPlan, content: "" },
1594 content: [
1595 {
1596 type: "diff",
1597 path: sessionPlan,
1598 oldText: "",
1599 newText: "# From diff after empty rawInput\n",
1600 },
1601 ],
1602 },
1603 linuxHost,
1604 ),
1605 ).toBe("# From diff after empty rawInput");
1606
1607 expect(
1608 extractGrokPlanMarkdownFromToolCallData(
1609 {
1610 rawInput: { file_path: sessionPlan, content: "" },
1611 },
1612 linuxHost,
1613 ),
1614 ).toBe("");
1615
1616 expect(
1617 extractGrokPlanMarkdownFromToolCallData(
1618 {
1619 content: [{ type: "diff", path: sessionPlan, oldText: "# old", newText: "" }],
1620 },
1621 linuxHost,
1622 ),
1623 ).toBe("");
1624
1625 expect(
1626 extractGrokPlanMarkdownFromToolCallData(
1627 {
1628 rawInput: { file_path: "/tmp/readme.md", content: "nope" },
1629 },
1630 linuxHost,
1631 ),
1632 ).toBeUndefined();
1633
1634 expect(
1635 extractGrokPlanMarkdownFromToolCallData(
1636 {
1637 rawInput: { file_path: "/repo/docs/plan.md", content: "# Project plan\n" },
1638 },
1639 linuxHost,
1640 ),
1641 ).toBeUndefined();
1642 });
1643 });