Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

XAiAcpExtension.test.ts

526 lines16.0 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeURL from "node:url";
5​
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Schema from "effect/Schema";
10import { describe, expect } from "vite-plus/test";
11​
12import {
13 extractGrokPlanMarkdownFromToolCallData,
14 extractXAiAskUserQuestions,
15 extractXAiExitPlanMarkdown,
16 isGrokPlanMarkdownPath,
17 makeXAiAskUserQuestionCancelledResponse,
18 makeXAiAskUserQuestionResponse,
19 makeXAiExitPlanModeCapturedResponse,
20 makeXAiPromptCompletionRuntime,
21 XAI_EMPTY_PLAN_MARKDOWN,
22 XAiAskUserQuestionRequest,
23 XAiExitPlanModeRequest,
24} from "./XAiAcpExtension.ts";
25import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
26​
27const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
28const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
29​
30const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
31 Effect.gen(function* () {
32 const runtime = yield* AcpSessionRuntime.make({
33 spawn: {
34 command: process.execPath,
35 args: [mockAgentPath],
36 env,
37 },
38 cwd: process.cwd(),
39 clientInfo: { name: "t3-test", version: "0.0.0" },
40 authMethodId: "test",
41 });
42 return yield* makeXAiPromptCompletionRuntime(runtime);
43 });
44​
45const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
46​
47describe("XAiAcpExtension", () => {
48 it("extracts questions from the real xAI ask_user_question payload shape", () => {
49 const questions = extractXAiAskUserQuestions({
50 sessionId: "session-1",
51 toolCallId: "tool-call-1",
52 mode: "default",
53 questions: [
54 {
55 id: "scope",
56 question: "Which scope should Grok use?",
57 options: [
58 { label: "Workspace", description: "Use the current workspace" },
59 { label: "Session", description: "Only use this session" },
60 ],
61 },
62 ],
63 });
64​
65 expect(questions).toEqual([
66 {
67 id: "scope",
68 header: "Question",
69 question: "Which scope should Grok use?",
70 multiSelect: false,
71 options: [
72 { label: "Workspace", description: "Use the current workspace" },
73 { label: "Session", description: "Only use this session" },
74 ],
75 },
76 ]);
77 });
78​
79 it("extracts questions from wrapped _x.ai extension payloads", () => {
80 const payload = {
81 method: "_x.ai/ask_user_question",
82 params: {
83 sessionId: "session-1",
84 toolCallId: "tool-call-1",
85 mode: "plan",
86 questions: [
87 {
88 question: "Which changes should be included?",
89 multiSelect: true,
90 options: [{ label: "Tests" }, { label: "Docs" }],
91 },
92 ],
93 },
94 };
95 const decoded = decodeXAiAskUserQuestionRequest(payload);
96 const questions = extractXAiAskUserQuestions(decoded);
97​
98 expect(questions).toEqual([
99 {
100 id: "Which changes should be included?",
101 header: "Question",
102 question: "Which changes should be included?",
103 multiSelect: true,
104 options: [
105 { label: "Tests", description: "Tests" },
106 { label: "Docs", description: "Docs" },
107 ],
108 },
109 ]);
110 });
111​
112 it("treats nullable multiSelect from Grok as single-select", () => {
113 const questions = extractXAiAskUserQuestions({
114 sessionId: "session-1",
115 toolCallId: "tool-call-1",
116 mode: "default",
117 questions: [
118 {
119 question: "Which label should Grok use?",
120 multiSelect: null,
121 options: [
122 { label: "Alpha", description: "Use the Alpha label" },
123 { label: "Beta", description: "Use the Beta label" },
124 { label: "Other", description: "Use the Other label" },
125 ],
126 },
127 ],
128 });
129​
130 expect(questions).toEqual([
131 {
132 id: "Which label should Grok use?",
133 header: "Question",
134 question: "Which label should Grok use?",
135 multiSelect: false,
136 options: [
137 { label: "Alpha", description: "Use the Alpha label" },
138 { label: "Beta", description: "Use the Beta label" },
139 { label: "Other", description: "Use the Other label" },
140 ],
141 },
142 ]);
143 });
144​
145 it("maps UI question ids back to xAI question text in accepted responses", () => {
146 const response = makeXAiAskUserQuestionResponse(
147 {
148 sessionId: "session-1",
149 toolCallId: "tool-call-1",
150 mode: "default",
151 questions: [
152 {
153 id: "scope",
154 question: "Which scope should Grok use?",
155 options: [
156 { label: "workspace", description: "Use the current workspace" },
157 { label: "session", description: "Only use this session" },
158 ],
159 },
160 ],
161 },
162 { scope: "workspace" },
163 );
164​
165 expect(response).toEqual({
166 outcome: "accepted",
167 answers: {
168 "Which scope should Grok use?": ["workspace"],
169 },
170 });
171 });
172​
173 it("orders accepted answers by the original xAI question order", () => {
174 const response = makeXAiAskUserQuestionResponse(
175 {
176 sessionId: "session-1",
177 toolCallId: "tool-call-1",
178 mode: "default",
179 questions: [
180 {
181 id: "first",
182 question: "First question?",
183 options: [{ label: "A", description: "A" }],
184 },
185 {
186 id: "second",
187 question: "Second question?",
188 options: [{ label: "B", description: "B" }],
189 },
190 ],
191 },
192 {
193 second: "B",
194 first: "A",
195 },
196 );
197​
198 expect(Object.keys(response.answers)).toEqual(["First question?", "Second question?"]);
199 expect(response).toMatchObject({
200 outcome: "accepted",
201 answers: {
202 "First question?": ["A"],
203 "Second question?": ["B"],
204 },
205 });
206 });
207​
208 it("encodes typed custom answers as xAI Other annotations", () => {
209 const response = makeXAiAskUserQuestionResponse(
210 {
211 method: "x.ai/ask_user_question",
212 params: {
213 sessionId: "session-1",
214 toolCallId: "tool-call-1",
215 mode: "default",
216 questions: [
217 {
218 question: "Which ice cream flavor?",
219 options: [
220 { label: "vanilla", description: "Vanilla flavor" },
221 { label: "chocolate", description: "Chocolate flavor" },
222 ],
223 },
224 ],
225 },
226 },
227 { "Which ice cream flavor?": "pistachio" },
228 );
229​
230 expect(response).toEqual({
231 outcome: "accepted",
232 answers: {
233 "Which ice cream flavor?": ["Other"],
234 },
235 annotations: {
236 "Which ice cream flavor?": {
237 notes: "pistachio",
238 },
239 },
240 });
241 });
242​
243 it("encodes interrupted dialogs as xAI cancelled responses", () => {
244 expect(makeXAiAskUserQuestionCancelledResponse()).toEqual({
245 outcome: "cancelled",
246 });
247 });
248​
249 it("does not echo preview annotations for multi-select answers", () => {
250 const response = makeXAiAskUserQuestionResponse(
251 {
252 sessionId: "session-1",
253 toolCallId: "tool-call-1",
254 mode: "default",
255 questions: [
256 {
257 question: "Which files should Grok touch?",
258 multiSelect: true,
259 options: [
260 {
261 label: "Tests",
262 description: "Update tests",
263 preview: "test preview",
264 },
265 {
266 label: "Docs",
267 description: "Update docs",
268 preview: "docs preview",
269 },
270 ],
271 },
272 ],
273 },
274 { "Which files should Grok touch?": ["Tests", "Docs"] },
275 );
276​
277 expect(response).toEqual({
278 outcome: "accepted",
279 answers: {
280 "Which files should Grok touch?": ["Tests", "Docs"],
281 },
282 });
283 });
284​
285 it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
286 Effect.gen(function* () {
287 const runtime = yield* makePromptCompletionRuntime({
288 T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
289 });
290 yield* runtime.start();
291​
292 const promptResult = yield* runtime.prompt({
293 prompt: [{ type: "text", text: "hi" }],
294 });
295 const promptId = promptResult._meta?.promptId;
296​
297 expect(typeof promptId).toBe("string");
298 expect(promptResult).toMatchObject({
299 stopReason: "end_turn",
300 _meta: {
301 sessionId: "mock-session-1",
302 promptId,
303 requestId: promptId,
304 },
305 });
306 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
307 );
308​
309 it.effect("fails a hung standard prompt from an xAI rate-limit completion", () =>
310 Effect.gen(function* () {
311 const runtime = yield* makePromptCompletionRuntime({
312 T3_ACP_EMIT_XAI_RATE_LIMIT_THEN_HANG: "1",
313 });
314 yield* runtime.start();
315​
316 const error = yield* Effect.flip(
317 runtime.prompt({
318 prompt: [{ type: "text", text: "hi" }],
319 }),
320 );
321​
322 expect(error).toMatchObject({
323 _tag: "AcpRequestError",
324 code: -32003,
325 errorMessage: "Grok usage limit reached. Try again later.",
326 });
327 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
328 );
329​
330 it.effect("ignores stale xAI completion from an already settled prompt", () =>
331 Effect.gen(function* () {
332 const runtime = yield* makePromptCompletionRuntime({
333 T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
334 });
335 yield* runtime.start();
336​
337 const firstPromptResult = yield* runtime.prompt({
338 prompt: [{ type: "text", text: "first" }],
339 });
340 expect(firstPromptResult).toMatchObject({
341 stopReason: "end_turn",
342 _meta: { promptId: "mock-stale-xai-prompt-1" },
343 });
344​
345 const secondPromptResult = yield* runtime.prompt({
346 prompt: [{ type: "text", text: "second" }],
347 });
348 const secondPromptId = secondPromptResult._meta?.promptId;
349 expect(typeof secondPromptId).toBe("string");
350 expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
351 expect(secondPromptResult).toMatchObject({
352 stopReason: "end_turn",
353 _meta: {
354 promptId: secondPromptId,
355 requestId: secondPromptId,
356 },
357 });
358 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
359 );
360​
361 it("extracts plan markdown from exit_plan_mode payloads", () => {
362 const decode = Schema.decodeUnknownSync(XAiExitPlanModeRequest);
363 const direct = decode({
364 sessionId: "session-1",
365 toolCallId: "exit-1",
366 planContent: "# Plan\n\n- do the thing\n",
367 });
368 expect(extractXAiExitPlanMarkdown(direct)).toBe("# Plan\n\n- do the thing");
369​
370 const wrapped = decode({
371 method: "_x.ai/exit_plan_mode",
372 params: {
373 sessionId: "session-1",
374 toolCallId: "exit-1",
375 planContent: null,
376 },
377 });
378 expect(extractXAiExitPlanMarkdown(wrapped, " # fallback plan ")).toBe("# fallback plan");
379 expect(extractXAiExitPlanMarkdown(wrapped, "")).toBe(XAI_EMPTY_PLAN_MARKDOWN);
380 expect(extractXAiExitPlanMarkdown(wrapped)).toBe(XAI_EMPTY_PLAN_MARKDOWN);
381 });
382​
383 it("builds an abandoned exit_plan_mode response that captures the plan", () => {
384 expect(makeXAiExitPlanModeCapturedResponse()).toEqual({
385 outcome: "abandoned",
386 feedback:
387 "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
388 });
389 });
390​
391 it("identifies Grok plan.md paths and extracts markdown from tool call data", () => {
392 const linuxHost = { platform: "linux" as const, environment: {} };
393 const windowsHost = { platform: "win32" as const, environment: {} };
394 const grokHomeHost = {
395 platform: "linux" as const,
396 environment: { GROK_HOME: "/opt/grok-data" },
397 };
398 const home = NodeOS.homedir().replace(/\\/g, "/");
399 const sessionPlan = `${home}/.grok/sessions/abc/plan.md`;
400 const nestedSessionPlan = `${home}/.grok/sessions/%2Fhome%2Fproj/019fd20e-c563-70a0-b801-a6bc51815a9b/plan.md`;
401 expect(isGrokPlanMarkdownPath(sessionPlan, linuxHost)).toBe(true);
402 expect(isGrokPlanMarkdownPath(nestedSessionPlan, linuxHost)).toBe(true);
403 expect(isGrokPlanMarkdownPath("~/.grok/sessions/abc/plan.md", linuxHost)).toBe(true);
404 expect(isGrokPlanMarkdownPath("/tmp/mock-home/.grok/sessions/sess/plan.md", linuxHost)).toBe(
405 true,
406 );
407 expect(isGrokPlanMarkdownPath("/home/other/.grok/sessions/sess/plan.md", linuxHost)).toBe(true);
408 expect(isGrokPlanMarkdownPath("/HOME/other/.grok/sessions/sess/plan.md", linuxHost)).toBe(
409 false,
410 );
411 expect(isGrokPlanMarkdownPath("C:/Users/other/.grok/sessions/id/plan.md", windowsHost)).toBe(
412 true,
413 );
414 expect(isGrokPlanMarkdownPath("c:/users/OTHER/.GROK/SESSIONS/id/PLAN.MD", windowsHost)).toBe(
415 true,
416 );
417 expect(
418 isGrokPlanMarkdownPath("C:\\Users\\other\\.grok\\sessions\\id\\plan.md", windowsHost),
419 ).toBe(true);
420 expect(isGrokPlanMarkdownPath("/opt/grok-data/sessions/sess/plan.md", grokHomeHost)).toBe(true);
421 expect(
422 isGrokPlanMarkdownPath("/OPT/GROK-DATA/sessions/sess/plan.md", {
423 platform: "win32",
424 environment: { GROK_HOME: "/opt/grok-data" },
425 }),
426 ).toBe(true);
427 expect(isGrokPlanMarkdownPath("/OPT/GROK-DATA/sessions/sess/plan.md", grokHomeHost)).toBe(
428 false,
429 );
430 // Workspace plan.md must not be treated as the session plan file.
431 expect(isGrokPlanMarkdownPath("plan.md", linuxHost)).toBe(false);
432 expect(isGrokPlanMarkdownPath("/repo/docs/plan.md", linuxHost)).toBe(false);
433 expect(isGrokPlanMarkdownPath("/tmp/other.md", linuxHost)).toBe(false);
434 expect(isGrokPlanMarkdownPath("/repo/.grok/sessions/example/plan.md", linuxHost)).toBe(false);
435 expect(
436 isGrokPlanMarkdownPath(`${home}/project/.grok/sessions/example/plan.md`, linuxHost),
437 ).toBe(false);
438 expect(
439 isGrokPlanMarkdownPath("/home/other/.grok/sessions/../../project/plan.md", linuxHost),
440 ).toBe(false);
441 expect(
442 isGrokPlanMarkdownPath("/home/other/.grok/sessions/foo/../../../project/plan.md", linuxHost),
443 ).toBe(false);
444​
445 expect(
446 extractGrokPlanMarkdownFromToolCallData(
447 {
448 rawInput: {
449 file_path: sessionPlan,
450 content: "# From rawInput\n\n- a\n",
451 },
452 },
453 linuxHost,
454 ),
455 ).toBe("# From rawInput\n\n- a");
456​
457 expect(
458 extractGrokPlanMarkdownFromToolCallData(
459 {
460 content: [
461 {
462 type: "diff",
463 path: sessionPlan,
464 oldText: "",
465 newText: "# From diff\n\n- b\n",
466 },
467 ],
468 },
469 linuxHost,
470 ),
471 ).toBe("# From diff\n\n- b");
472​
473 expect(
474 extractGrokPlanMarkdownFromToolCallData(
475 {
476 rawInput: { file_path: sessionPlan, content: "" },
477 content: [
478 {
479 type: "diff",
480 path: sessionPlan,
481 oldText: "",
482 newText: "# From diff after empty rawInput\n",
483 },
484 ],
485 },
486 linuxHost,
487 ),
488 ).toBe("# From diff after empty rawInput");
489​
490 expect(
491 extractGrokPlanMarkdownFromToolCallData(
492 {
493 rawInput: { file_path: sessionPlan, content: "" },
494 },
495 linuxHost,
496 ),
497 ).toBe("");
498​
499 expect(
500 extractGrokPlanMarkdownFromToolCallData(
501 {
502 content: [{ type: "diff", path: sessionPlan, oldText: "# old", newText: "" }],
503 },
504 linuxHost,
505 ),
506 ).toBe("");
507​
508 expect(
509 extractGrokPlanMarkdownFromToolCallData(
510 {
511 rawInput: { file_path: "/tmp/readme.md", content: "nope" },
512 },
513 linuxHost,
514 ),
515 ).toBeUndefined();
516​
517 expect(
518 extractGrokPlanMarkdownFromToolCallData(
519 {
520 rawInput: { file_path: "/repo/docs/plan.md", content: "# Project plan\n" },
521 },
522 linuxHost,
523 ),
524 ).toBeUndefined();
525 });
526});