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

PiRpcClient.test.ts

562 lines17.9 KB

1import { describe, expect, it } from "@effect/vitest";
2import type { AgentSessionEvent, ModelInfo, RpcResponse } from "@earendil-works/pi-coding-agent";
3​
4import {
5 asPiThinkingLevel,
6 buildPiTurnCommand,
7 classifyPiStdoutMessage,
8 extractAssistantTextDelta,
9 extractAvailableModels,
10 extractForkMessages,
11 extractLastAssistantText,
12 extractReasoningTextDelta,
13 extractSessionFile,
14 parsePiStdoutLine,
15 PI_THINKING_LEVEL_VALUES,
16 piForkSucceeded,
17 piImageContentFromBytes,
18 piModelCapabilities,
19 piModelInfoToServerModel,
20 piModelSlug,
21 piResponseHasCommand,
22 piResponseSucceeded,
23 planPiModelSwitch,
24 resolveForkTargetEntryId,
25 resolvePiThinkingLevel,
26 splitPiModelSlug,
27 tryParsePiJsonObject,
28} from "./PiRpcClient.ts";
29​
30const asEvent = (value: unknown): AgentSessionEvent => value as AgentSessionEvent;
31const asResponse = (value: unknown): RpcResponse => value as RpcResponse;
32const asModelInfo = (value: unknown): ModelInfo => value as ModelInfo;
33const modelSelectionWithThinking = (value: string | undefined) =>
34 ({
35 instanceId: "pi",
36 model: "openai/gpt-5",
37 options: value === undefined ? [] : [{ id: "thinking", value }],
38 }) as unknown as Parameters<typeof resolvePiThinkingLevel>[0];
39​
40describe("tryParsePiJsonObject", () => {
41 it("parses a JSON object line", () => {
42 expect(tryParsePiJsonObject('{"type":"response","id":"1"}')).toEqual({
43 type: "response",
44 id: "1",
45 });
46 });
47​
48 it("ignores blank, non-object, and malformed lines", () => {
49 expect(tryParsePiJsonObject("")).toBeNull();
50 expect(tryParsePiJsonObject(" ")).toBeNull();
51 expect(tryParsePiJsonObject("plain log output")).toBeNull();
52 expect(tryParsePiJsonObject("[1,2,3]")).toBeNull();
53 expect(tryParsePiJsonObject("{ not json }")).toBeNull();
54 });
55});
56​
57describe("classifyPiStdoutMessage / parsePiStdoutLine", () => {
58 it("discriminates a response frame and extracts its correlation id", () => {
59 const message = classifyPiStdoutMessage({ type: "response", id: "req-1", success: true });
60 expect(message).toMatchObject({ _tag: "response", id: "req-1" });
61 });
62​
63 it("treats a response without a string id as undefined", () => {
64 const message = classifyPiStdoutMessage({ type: "response", success: true });
65 expect(message).toMatchObject({ _tag: "response", id: undefined });
66 });
67​
68 it("discriminates an extension_ui_request frame", () => {
69 const message = parsePiStdoutLine(
70 '{"type":"extension_ui_request","id":"ui-1","method":"confirm","title":"bash"}',
71 );
72 expect(message).toMatchObject({ _tag: "extension-ui" });
73 });
74​
75 it("treats any other typed frame as an agent event", () => {
76 const message = parsePiStdoutLine('{"type":"agent_start"}');
77 expect(message).toMatchObject({ _tag: "event" });
78 });
79​
80 it("ignores frames without a usable type discriminator", () => {
81 expect(classifyPiStdoutMessage({ id: "x" })).toBeNull();
82 expect(classifyPiStdoutMessage({ type: "" })).toBeNull();
83 expect(parsePiStdoutLine("not-json")).toBeNull();
84 });
85});
86​
87describe("extractAssistantTextDelta", () => {
88 it("returns the delta for a text_delta assistant message", () => {
89 expect(
90 extractAssistantTextDelta(
91 asEvent({
92 type: "message_update",
93 assistantMessageEvent: { type: "text_delta", delta: "hello" },
94 }),
95 ),
96 ).toBe("hello");
97 });
98​
99 it("hides thinking and non-message events", () => {
100 expect(
101 extractAssistantTextDelta(
102 asEvent({
103 type: "message_update",
104 assistantMessageEvent: { type: "thinking_delta", delta: "secret" },
105 }),
106 ),
107 ).toBeNull();
108 expect(extractAssistantTextDelta(asEvent({ type: "agent_start" }))).toBeNull();
109 });
110});
111​
112describe("extractReasoningTextDelta", () => {
113 it("returns the delta for a thinking_delta assistant message", () => {
114 expect(
115 extractReasoningTextDelta(
116 asEvent({
117 type: "message_update",
118 assistantMessageEvent: { type: "thinking_delta", delta: "reasoning" },
119 }),
120 ),
121 ).toBe("reasoning");
122 });
123​
124 it("returns null for text deltas and other events", () => {
125 expect(
126 extractReasoningTextDelta(
127 asEvent({
128 type: "message_update",
129 assistantMessageEvent: { type: "text_delta", delta: "hi" },
130 }),
131 ),
132 ).toBeNull();
133 expect(extractReasoningTextDelta(asEvent({ type: "turn_start" }))).toBeNull();
134 });
135});
136​
137describe("splitPiModelSlug / piModelSlug", () => {
138 it("splits a provider/id slug keeping extra segments in the id", () => {
139 expect(splitPiModelSlug("openai/gpt-4o")).toEqual({ provider: "openai", id: "gpt-4o" });
140 expect(splitPiModelSlug("openrouter/openai/gpt-4o")).toEqual({
141 provider: "openrouter",
142 id: "openai/gpt-4o",
143 });
144 });
145​
146 it("returns null when there is no interior separator", () => {
147 expect(splitPiModelSlug("gpt-4o")).toBeNull();
148 expect(splitPiModelSlug("/gpt-4o")).toBeNull();
149 expect(splitPiModelSlug("openai/")).toBeNull();
150 });
151​
152 it("round-trips a model into its canonical slug", () => {
153 expect(piModelSlug({ provider: "anthropic", id: "claude-sonnet-4-6" })).toBe(
154 "anthropic/claude-sonnet-4-6",
155 );
156 });
157});
158​
159describe("piModelCapabilities", () => {
160 it("exposes a thinking descriptor for reasoning models", () => {
161 const capabilities = piModelCapabilities(true);
162 expect((capabilities.optionDescriptors ?? []).map((descriptor) => descriptor.id)).toContain(
163 "thinking",
164 );
165 });
166​
167 it("exposes no option descriptors for non-reasoning models", () => {
168 expect(piModelCapabilities(false).optionDescriptors ?? []).toEqual([]);
169 });
170});
171​
172describe("piModelInfoToServerModel", () => {
173 it("maps a ModelInfo to a ServerProviderModel with a canonical slug", () => {
174 const model = piModelInfoToServerModel(
175 asModelInfo({
176 provider: "anthropic",
177 id: "claude-sonnet-4-6",
178 name: "Claude Sonnet 4.6",
179 reasoning: true,
180 }),
181 );
182 expect(model.slug).toBe("anthropic/claude-sonnet-4-6");
183 expect(model.name).toBe("Claude Sonnet 4.6");
184 expect(model.isCustom).toBe(false);
185 expect(
186 (model.capabilities?.optionDescriptors ?? []).map((descriptor) => descriptor.id),
187 ).toContain("thinking");
188 });
189​
190 it("falls back to the model id when no display name is provided", () => {
191 const model = piModelInfoToServerModel(asModelInfo({ provider: "openai", id: "gpt-4o-mini" }));
192 expect(model.name).toBe("gpt-4o-mini");
193 expect(model.capabilities?.optionDescriptors ?? []).toEqual([]);
194 });
195});
196​
197describe("extractSessionFile", () => {
198 it("reads the sessionFile path from a successful get_state response", () => {
199 expect(
200 extractSessionFile(
201 asResponse({ type: "response", success: true, data: { sessionFile: " /tmp/s.json " } }),
202 ),
203 ).toBe("/tmp/s.json");
204 });
205​
206 it("returns undefined for missing / unsuccessful / empty responses", () => {
207 expect(extractSessionFile(undefined)).toBeUndefined();
208 expect(
209 extractSessionFile(asResponse({ type: "response", success: false, data: {} })),
210 ).toBeUndefined();
211 expect(
212 extractSessionFile(
213 asResponse({ type: "response", success: true, data: { sessionFile: "" } }),
214 ),
215 ).toBeUndefined();
216 });
217});
218​
219describe("extractAvailableModels", () => {
220 it("reads the models array from a successful get_available_models response", () => {
221 const models = extractAvailableModels(
222 asResponse({
223 type: "response",
224 success: true,
225 data: { models: [{ provider: "openai", id: "gpt-4o" }] },
226 }),
227 );
228 expect(models).toHaveLength(1);
229 expect(models[0]).toMatchObject({ provider: "openai", id: "gpt-4o" });
230 });
231​
232 it("returns an empty array for missing / unsuccessful / malformed responses", () => {
233 expect(extractAvailableModels(undefined)).toEqual([]);
234 expect(extractAvailableModels(asResponse({ type: "response", success: false }))).toEqual([]);
235 expect(
236 extractAvailableModels(
237 asResponse({ type: "response", success: true, data: { models: "nope" } }),
238 ),
239 ).toEqual([]);
240 });
241});
242​
243describe("piResponseHasCommand", () => {
244 const commandsResponse = (names: ReadonlyArray<string>) =>
245 asResponse({
246 type: "response",
247 command: "get_commands",
248 success: true,
249 data: { commands: names.map((name) => ({ name, source: "extension" })) },
250 });
251​
252 it("detects a registered command by name", () => {
253 expect(
254 piResponseHasCommand(commandsResponse(["t3-approval-gate", "other"]), "t3-approval-gate"),
255 ).toBe(true);
256 });
257​
258 it("returns false when the command is absent", () => {
259 expect(piResponseHasCommand(commandsResponse(["other"]), "t3-approval-gate")).toBe(false);
260 });
261​
262 it("returns false for undefined, failed, or non-get_commands responses", () => {
263 expect(piResponseHasCommand(undefined, "t3-approval-gate")).toBe(false);
264 expect(
265 piResponseHasCommand(
266 asResponse({ type: "response", command: "get_commands", success: false, error: "boom" }),
267 "t3-approval-gate",
268 ),
269 ).toBe(false);
270 expect(
271 piResponseHasCommand(
272 asResponse({ type: "response", command: "get_state", success: true, data: {} }),
273 "t3-approval-gate",
274 ),
275 ).toBe(false);
276 });
277});
278​
279describe("extractLastAssistantText", () => {
280 it("reads the text field from a successful response", () => {
281 expect(
282 extractLastAssistantText(
283 asResponse({
284 type: "response",
285 command: "get_last_assistant_text",
286 success: true,
287 data: { text: "hello" },
288 }),
289 ),
290 ).toBe("hello");
291 });
292​
293 it("returns null for null text, failed, or undefined responses", () => {
294 expect(
295 extractLastAssistantText(
296 asResponse({
297 type: "response",
298 command: "get_last_assistant_text",
299 success: true,
300 data: { text: null },
301 }),
302 ),
303 ).toBeNull();
304 expect(extractLastAssistantText(undefined)).toBeNull();
305 expect(
306 extractLastAssistantText(
307 asResponse({
308 type: "response",
309 command: "get_last_assistant_text",
310 success: false,
311 error: "x",
312 }),
313 ),
314 ).toBeNull();
315 });
316});
317​
318describe("piImageContentFromBytes", () => {
319 it("encodes bytes as raw base64 with the given mime type", () => {
320 const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
321 expect(piImageContentFromBytes({ mimeType: "image/png", bytes })).toEqual({
322 type: "image",
323 data: Buffer.from(bytes).toString("base64"),
324 mimeType: "image/png",
325 });
326 });
327​
328 it("produces raw base64, not a data: URL", () => {
329 const result = piImageContentFromBytes({
330 mimeType: "image/webp",
331 bytes: new Uint8Array([1, 2, 3]),
332 });
333 expect(result.data.startsWith("data:")).toBe(false);
334 });
335});
336​
337describe("buildPiTurnCommand", () => {
338 it("uses steer mid-turn so Pi folds the message into the running turn", () => {
339 expect(buildPiTurnCommand({ isMidTurn: true, message: "keep it short" })).toEqual({
340 type: "steer",
341 message: "keep it short",
342 });
343 });
344​
345 it("uses prompt for a fresh turn", () => {
346 expect(buildPiTurnCommand({ isMidTurn: false, message: "start work" })).toEqual({
347 type: "prompt",
348 message: "start work",
349 });
350 });
351​
352 it("preserves empty messages without switching command type", () => {
353 expect(buildPiTurnCommand({ isMidTurn: true, message: "" })).toEqual({
354 type: "steer",
355 message: "",
356 });
357 });
358​
359 it("attaches images only when the array is non-empty", () => {
360 const images = [{ type: "image" as const, data: "AQ==", mimeType: "image/png" }];
361 expect(buildPiTurnCommand({ isMidTurn: false, message: "hi", images })).toEqual({
362 type: "prompt",
363 message: "hi",
364 images,
365 });
366 expect(buildPiTurnCommand({ isMidTurn: false, message: "hi", images: [] })).toEqual({
367 type: "prompt",
368 message: "hi",
369 });
370 });
371});
372​
373describe("asPiThinkingLevel / resolvePiThinkingLevel", () => {
374 it("keeps descriptor option ids in sync with the ThinkingLevel set", () => {
375 const descriptorIds = (piModelCapabilities(true).optionDescriptors ?? []).flatMap(
376 (descriptor) => (descriptor.type === "select" ? descriptor.options.map((o) => o.id) : []),
377 );
378 expect(descriptorIds).toEqual([...PI_THINKING_LEVEL_VALUES]);
379 });
380​
381 it("resolves each valid thinking level from a model selection", () => {
382 for (const level of PI_THINKING_LEVEL_VALUES) {
383 expect(resolvePiThinkingLevel(modelSelectionWithThinking(level))).toBe(level);
384 expect(asPiThinkingLevel(level)).toBe(level);
385 }
386 });
387​
388 it("returns undefined when the thinking option is absent or unknown", () => {
389 expect(resolvePiThinkingLevel(modelSelectionWithThinking(undefined))).toBeUndefined();
390 expect(resolvePiThinkingLevel(undefined)).toBeUndefined();
391 expect(resolvePiThinkingLevel(modelSelectionWithThinking("turbo"))).toBeUndefined();
392 expect(asPiThinkingLevel(undefined)).toBeUndefined();
393 expect(asPiThinkingLevel("")).toBeUndefined();
394 });
395});
396​
397describe("planPiModelSwitch", () => {
398 it("is a noop when no model is requested or it matches the current model", () => {
399 expect(planPiModelSwitch("openai/gpt-4o", undefined)).toEqual({ kind: "noop" });
400 expect(planPiModelSwitch("openai/gpt-4o", "openai/gpt-4o")).toEqual({ kind: "noop" });
401 });
402​
403 it("plans a switch with split provider/id for a changed slug", () => {
404 expect(planPiModelSwitch("openai/gpt-4o", "anthropic/claude-sonnet-4-6")).toEqual({
405 kind: "switch",
406 provider: "anthropic",
407 modelId: "claude-sonnet-4-6",
408 slug: "anthropic/claude-sonnet-4-6",
409 });
410 expect(planPiModelSwitch(undefined, "openrouter/openai/gpt-4o")).toEqual({
411 kind: "switch",
412 provider: "openrouter",
413 modelId: "openai/gpt-4o",
414 slug: "openrouter/openai/gpt-4o",
415 });
416 });
417​
418 it("flags a malformed slug as invalid", () => {
419 expect(planPiModelSwitch("openai/gpt-4o", "gpt-4o")).toEqual({
420 kind: "invalid",
421 slug: "gpt-4o",
422 });
423 });
424});
425​
426describe("piResponseSucceeded", () => {
427 it("is true only for a matching successful response", () => {
428 expect(
429 piResponseSucceeded(
430 asResponse({ type: "response", command: "set_model", success: true, data: {} }),
431 "set_model",
432 ),
433 ).toBe(true);
434 });
435​
436 it("is false for failed, mismatched-command, non-response, or undefined values", () => {
437 expect(
438 piResponseSucceeded(
439 asResponse({ type: "response", command: "set_model", success: false, error: "no" }),
440 "set_model",
441 ),
442 ).toBe(false);
443 expect(
444 piResponseSucceeded(
445 asResponse({ type: "response", command: "set_thinking_level", success: true }),
446 "set_model",
447 ),
448 ).toBe(false);
449 expect(piResponseSucceeded(undefined, "set_model")).toBe(false);
450 });
451});
452​
453describe("extractForkMessages", () => {
454 const forkResponse = (messages: unknown) =>
455 asResponse({
456 type: "response",
457 command: "get_fork_messages",
458 success: true,
459 data: { messages },
460 });
461​
462 it("reads ordered user fork entries", () => {
463 const result = extractForkMessages(
464 forkResponse([
465 { entryId: "e1", text: "first" },
466 { entryId: "e2", text: "second" },
467 ]),
468 );
469 expect(result).toEqual([
470 { entryId: "e1", text: "first" },
471 { entryId: "e2", text: "second" },
472 ]);
473 });
474​
475 it("defaults missing text to empty string and drops entries without a string entryId", () => {
476 const result = extractForkMessages(
477 forkResponse([{ entryId: "e1" }, { text: "no id" }, { entryId: 42 }]),
478 );
479 expect(result).toEqual([{ entryId: "e1", text: "" }]);
480 });
481​
482 it("distinguishes valid empty history from failed or malformed responses", () => {
483 expect(extractForkMessages(forkResponse([]))).toEqual([]);
484 expect(extractForkMessages(undefined)).toBeUndefined();
485 expect(
486 extractForkMessages(
487 asResponse({ type: "response", command: "get_fork_messages", success: false, error: "x" }),
488 ),
489 ).toBeUndefined();
490 expect(extractForkMessages(forkResponse("nope"))).toBeUndefined();
491 });
492});
493​
494describe("piForkSucceeded", () => {
495 it("is true for success with no cancellation", () => {
496 expect(
497 piForkSucceeded(
498 asResponse({
499 type: "response",
500 command: "fork",
501 success: true,
502 data: { text: "x", cancelled: false },
503 }),
504 ),
505 ).toBe(true);
506 expect(
507 piForkSucceeded(
508 asResponse({
509 type: "response",
510 command: "new_session",
511 success: true,
512 data: { cancelled: false },
513 }),
514 ),
515 ).toBe(true);
516 });
517​
518 it("is false when cancelled, failed, or undefined", () => {
519 expect(
520 piForkSucceeded(
521 asResponse({
522 type: "response",
523 command: "fork",
524 success: true,
525 data: { text: "", cancelled: true },
526 }),
527 ),
528 ).toBe(false);
529 expect(
530 piForkSucceeded(
531 asResponse({ type: "response", command: "fork", success: false, error: "invalid entry" }),
532 ),
533 ).toBe(false);
534 expect(piForkSucceeded(undefined)).toBe(false);
535 });
536});
537​
538describe("resolveForkTargetEntryId", () => {
539 const msgs = (...ids: string[]) => ids.map((entryId) => ({ entryId }));
540​
541 it("returns null when there is nothing to roll back", () => {
542 expect(resolveForkTargetEntryId([], 3)).toBeNull();
543 expect(resolveForkTargetEntryId(msgs("a", "b"), 0)).toBeNull();
544 expect(resolveForkTargetEntryId(msgs("a", "b"), -1)).toBeNull();
545 });
546​
547 it("forks before the (len-numTurns)th user message", () => {
548 expect(resolveForkTargetEntryId(msgs("a", "b", "c", "d", "e"), 2)).toEqual({
549 kind: "fork",
550 entryId: "d",
551 });
552 expect(resolveForkTargetEntryId(msgs("a", "b", "c", "d"), 1)).toEqual({
553 kind: "fork",
554 entryId: "d",
555 });
556 });
557​
558 it("resets to an empty session when rolling back to or past the first message", () => {
559 expect(resolveForkTargetEntryId(msgs("a", "b", "c"), 3)).toEqual({ kind: "reset" });
560 expect(resolveForkTargetEntryId(msgs("a", "b", "c"), 5)).toEqual({ kind: "reset" });
561 });
562});