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

status.test.ts

503 lines19.2 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Deferred from "effect/Deferred";
6import * as Fiber from "effect/Fiber";
7import * as TestClock from "effect/testing/TestClock";
8import * as Queue from "effect/Queue";
9import * as Schema from "effect/Schema";
10import * as Sink from "effect/Sink";
11import * as Stream from "effect/Stream";
12import * as ChildProcess from "effect/process/ChildProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14​
15import { checkPiProviderStatus, MINIMUM_PI_VERSION } from "./status.ts";
16​
17const encoder = new TextEncoder();
18const decodeRpcRequest = Schema.decodeSync(
19 Schema.fromJsonString(Schema.Struct({ id: Schema.String, type: Schema.String })),
20);
21const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
22const STARTUP_DIALOG = `${encodeJsonLine({
23 type: "extension_ui_request",
24 id: "ui-1",
25 method: "select",
26 title: "Allow project MCP server “github”?",
27 options: ["Don't allow", "Allow"],
28})}\n`;
29​
30function processHandle(input: {
31 readonly stdout?: string;
32 readonly stderr?: string;
33 readonly exitCode?: number;
34 /** Holds stdout and the exit back until it completes, like a CLI slow to answer. */
35 readonly answered?: Effect.Effect<void>;
36}) {
37 const answered = input.answered ?? Effect.void;
38 const bytes = (value: string | undefined) =>
39 value === undefined || value.length === 0
40 ? Stream.empty
41 : Stream.succeed(encoder.encode(value));
42 return ChildProcessSpawner.makeHandle({
43 pid: ChildProcessSpawner.ProcessId(900_000_001),
44 exitCode: Effect.as(answered, ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
45 isRunning: Effect.succeed(false),
46 kill: () => Effect.void,
47 unref: Effect.succeed(Effect.void),
48 stdin: Sink.drain,
49 stdout: Stream.unwrap(Effect.as(answered, bytes(input.stdout))),
50 stderr: bytes(input.stderr),
51 all: Stream.empty,
52 getInputFd: () => Sink.drain,
53 getOutputFd: () => Stream.empty,
54 });
56​
57function piProbeSpawner(version: string) {
58 return ChildProcessSpawner.make((command) => {
59 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
60 return Effect.succeed(
61 args.includes("--version")
62 ? processHandle({ stdout: `pi ${version}\n` })
63 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
64 );
65 });
67​
68const piRpcProcess = (
69 inventory: unknown,
70 onModelRequest: Effect.Effect<void> = Effect.void,
71 state: unknown = {},
72) =>
73 Effect.gen(function* () {
74 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
75 let stdinBuffer = "";
76 const stdin = Sink.forEach((chunk: Uint8Array) =>
77 Effect.gen(function* () {
78 stdinBuffer += new TextDecoder().decode(chunk);
79 while (true) {
80 const newline = stdinBuffer.indexOf("\n");
81 if (newline === -1) return;
82 const line = stdinBuffer.slice(0, newline);
83 stdinBuffer = stdinBuffer.slice(newline + 1);
84 if (line.length === 0) continue;
85 const request = decodeRpcRequest(line);
86 if (request.type === "get_available_models") {
87 yield* onModelRequest;
88 if (inventory === null) continue;
89 }
90 const data =
91 request.type === "get_available_models"
92 ? inventory
93 : request.type === "get_commands"
94 ? { commands: [] }
95 : request.type === "get_state"
96 ? state
97 : {};
98 yield* Queue.offer(
99 stdout,
100 encoder.encode(
101 `${encodeJsonLine({ type: "response", id: request.id, command: request.type, success: true, data })}\n`,
102 ),
103 );
104 }
105 }),
106 );
107 return ChildProcessSpawner.makeHandle({
108 ...processHandle({}),
109 exitCode: Effect.never,
110 isRunning: Effect.succeed(true),
111 stdin,
112 stdout: Stream.fromQueue(stdout),
113 });
114 });
115​
116/** Makes the extension-free launch exit before answering, like launch args naming an extension provider. */
117const exitsWithoutExtensions = Symbol("exitsWithoutExtensions");
118​
119// Text generation lists models with --no-extensions, so its inventory can differ.
120const piDiscoverySpawner = (
121 inventory: unknown,
122 extensionFreeInventory: unknown = inventory,
123 onExtensionFreeModelRequest: Effect.Effect<void> = Effect.void,
124 options: {
125 readonly version?: string;
126 readonly state?: unknown;
127 readonly authCheck?: string | undefined;
128 /** Without `--no-approve`, print a project-trust dialog and exit 0 as Pi 1.x does. */
129 readonly startupDialog?: boolean;
130 /** What `--no-approve` lists once project-local extensions are skipped. */
131 readonly declinedProjectInventory?: unknown;
132 } = {},
133) =>
134 Effect.succeed(
135 ChildProcessSpawner.make((command) => {
136 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
137 if (args.includes("--version")) {
138 return Effect.succeed(processHandle({ stdout: `pi ${options.version ?? "0.84.3"}\n` }));
139 }
140 if (args[0] === "auth") {
141 const expected = ["auth", "check", "--provider", "openai", "--json", "--no-refresh"];
142 return options.authCheck === undefined || args.join(" ") !== expected.join(" ")
143 ? Effect.die(`Unexpected pi ${args.join(" ")}`)
144 : Effect.succeed(processHandle({ stdout: options.authCheck, exitCode: 1 }));
145 }
146 if (
147 options.startupDialog === true &&
148 !args.includes("--no-extensions") &&
149 !args.includes("--no-approve")
150 ) {
151 return Effect.succeed(processHandle({ stdout: STARTUP_DIALOG }));
152 }
153 if (args.includes("--no-extensions") && extensionFreeInventory === exitsWithoutExtensions) {
154 return Effect.succeed(
155 processHandle({ stderr: 'Error: Unknown provider "demo".', exitCode: 1 }),
156 );
157 }
158 return piRpcProcess(
159 args.includes("--no-extensions")
160 ? extensionFreeInventory
161 : args.includes("--no-approve") && options.declinedProjectInventory !== undefined
162 ? options.declinedProjectInventory
163 : inventory,
164 args.includes("--no-extensions") ? onExtensionFreeModelRequest : Effect.void,
165 options.state,
166 );
167 }),
168 );
169​
170const settings = {
171 enabled: true,
172 binaryPath: "pi",
173 launchArgs: "",
174 customModels: [],
175} as const;
176​
177describe("PiProvider", () => {
178 it.effect("requires session-scoped thinking changes", () =>
179 Effect.gen(function* () {
180 const snapshot = yield* checkPiProviderStatus(settings).pipe(
181 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.2")),
182 );
183 assert.equal(snapshot.status, "error");
184 assert.equal(snapshot.version, "0.84.2");
185 assert.include(snapshot.message ?? "", `Pi ${MINIMUM_PI_VERSION} or newer`);
186 }).pipe(Effect.provide(NodeServices.layer)),
187 );
188​
189 it.effect("keeps compatible Pi selectable when optional discovery fails", () =>
190 Effect.gen(function* () {
191 const snapshot = yield* checkPiProviderStatus(settings).pipe(
192 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.3")),
193 );
194 assert.equal(snapshot.status, "ready");
195 assert.equal(snapshot.auth.status, "unknown");
196 assert.deepEqual(
197 snapshot.models.map((model) => model.slug),
198 ["default"],
199 );
200 assert.include(snapshot.message ?? "", "could not refresh its models and commands");
201 }).pipe(Effect.provide(NodeServices.layer)),
202 );
203​
204 it.effect.each([
205 {
206 label: "answers after 6 s",
207 versionDelay: "6 seconds",
208 status: "ready",
209 version: "0.84.3",
210 message: "could not refresh its models and commands",
211 probesAfterVersion: true,
212 },
213 {
214 label: "never answers",
215 versionDelay: "Infinity",
216 status: "error",
217 version: null,
218 message: "Pi CLI is installed but timed out while running `pi --version`.",
219 probesAfterVersion: false,
220 },
221 ] as const)("gives `pi --version` 10 s when it $label", (row) =>
222 Effect.gen(function* () {
223 const spawned: Array<string> = [];
224 const spawner = ChildProcessSpawner.make((command) => {
225 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
226 spawned.push(args.join(" "));
227 return Effect.succeed(
228 args.includes("--version")
229 ? processHandle({ stdout: "pi 0.84.3\n", answered: Effect.sleep(row.versionDelay) })
230 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
231 );
232 });
233 const fiber = yield* checkPiProviderStatus(settings).pipe(
234 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
235 Effect.forkChild,
236 );
237 yield* TestClock.adjust("10 seconds");
238 const snapshot = yield* Fiber.join(fiber);
239 assert.equal(snapshot.status, row.status);
240 assert.equal(snapshot.version, row.version);
241 assert.include(snapshot.message ?? "", row.message);
242 assert.equal(spawned.length > 1, row.probesAfterVersion);
243 }).pipe(Effect.provide(NodeServices.layer)),
244 );
245​
246 it.effect("reports a known unauthenticated inventory when Pi returns no usable models", () =>
247 Effect.gen(function* () {
248 const spawner = yield* piDiscoverySpawner({ models: [] });
249 const snapshot = yield* checkPiProviderStatus(settings).pipe(
250 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
251 );
252 assert.equal(snapshot.status, "warning");
253 assert.equal(snapshot.auth.status, "unauthenticated");
254 assert.deepEqual(
255 snapshot.models.map((model) => model.slug),
256 ["default"],
257 );
258 }).pipe(Effect.provide(NodeServices.layer)),
259 );
260​
261 it.effect.each([
262 {
263 label: "a pinned model without credentials",
264 version: "1.4.0",
265 activeModel: { provider: "openai", id: "gpt-5" },
266 authCheck: '{"status":"not_ready","provider":"openai","reason":"credentials_not_configured"}',
267 message: "Pi default (openai/gpt-5) has no credentials configured for openai.",
268 },
269 {
270 label: "a pinned model with a runtime --api-key",
271 version: "1.4.0",
272 launchArgs: "--provider openai --model gpt-5 --api-key fake-key",
273 activeModel: { provider: "openai", id: "gpt-5" },
274 authCheck: undefined,
275 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
276 },
277 {
278 label: "a pinned model whose provider auth check cannot find",
279 version: "1.4.0",
280 activeModel: { provider: "openai", id: "gpt-5" },
281 authCheck: '{"status":"not_ready","provider":"openai","reason":"provider_not_found"}',
282 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
283 },
284 {
285 label: "an uncatalogued model id of a provider with credentials",
286 version: "1.4.0",
287 activeModel: { provider: "anthropic", id: "claude-next" },
288 authCheck: undefined,
289 message: undefined,
290 },
291 {
292 label: "an extension model Pi lists as available",
293 version: "1.4.0",
294 activeModel: { provider: "router", id: "auto" },
295 authCheck: undefined,
296 message: undefined,
297 },
298 ])("diagnoses Pi's active model readiness for $label", (row) =>
299 Effect.gen(function* () {
300 const spawner = yield* piDiscoverySpawner(
301 {
302 models: [
303 { provider: "anthropic", id: "claude-sonnet-4" },
304 { provider: "router", id: "auto" },
305 ],
306 },
307 undefined,
308 Effect.void,
309 { version: row.version, state: { model: row.activeModel }, authCheck: row.authCheck },
310 );
311 const snapshot = yield* checkPiProviderStatus({
312 ...settings,
313 launchArgs: row.launchArgs ?? "",
314 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
315 assert.equal(snapshot.status, "ready");
316 assert.equal(snapshot.auth.status, "authenticated");
317 if (row.message === undefined) assert.isUndefined(snapshot.message);
318 else assert.include(snapshot.message ?? "", row.message);
319 }).pipe(Effect.provide(NodeServices.layer)),
320 );
321​
322 it.effect("marks models that only load with Pi extensions as unusable for text generation", () =>
323 Effect.gen(function* () {
324 const spawner = yield* piDiscoverySpawner(
325 {
326 models: [
327 { provider: "anthropic", id: "claude-sonnet-4" },
328 { provider: "demo", id: "demo-model" },
329 ],
330 },
331 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }] },
332 );
333 const snapshot = yield* checkPiProviderStatus(settings).pipe(
334 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
335 );
336 assert.deepEqual(
337 snapshot.models.map((model) => [model.slug, model.supportsTextGeneration]),
338 [
339 ["default", undefined],
340 ["anthropic/claude-sonnet-4", undefined],
341 ["demo/demo-model", false],
342 ],
343 );
344 assert.equal(snapshot.supportsTextGeneration, undefined);
345 }).pipe(Effect.provide(NodeServices.layer)),
346 );
347​
348 it.effect.each([
349 { label: "exits before answering", extensionFreeInventory: exitsWithoutExtensions },
350 { label: "lists no models", extensionFreeInventory: { models: [] } },
351 ])("makes Pi unusable for text generation when Pi without extensions $label", (row) =>
352 Effect.gen(function* () {
353 const spawner = yield* piDiscoverySpawner(
354 { models: [{ provider: "demo", id: "extension-model" }] },
355 row.extensionFreeInventory,
356 );
357 const snapshot = yield* checkPiProviderStatus({
358 ...settings,
359 launchArgs: "--provider demo --model extension-model",
360 customModels: ["local/custom-alias"],
361 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
362 assert.equal(snapshot.status, "ready");
363 assert.equal(snapshot.auth.status, "authenticated");
364 // Pi default and custom models still run in chat, so the picker keeps them.
365 assert.deepEqual(
366 snapshot.models.map((model) => model.slug),
367 ["default", "demo/extension-model", "local/custom-alias"],
368 );
369 assert.equal(snapshot.supportsTextGeneration, false);
370 }).pipe(Effect.provide(NodeServices.layer)),
371 );
372​
373 it.effect("preserves normal discovery when the extension-free model listing times out", () =>
374 Effect.gen(function* () {
375 const modelRequested = yield* Deferred.make<void>();
376 const spawner = yield* piDiscoverySpawner(
377 { models: [{ provider: "demo", id: "demo-model" }] },
378 null,
379 Deferred.succeed(modelRequested, undefined).pipe(Effect.asVoid),
380 );
381 const fiber = yield* checkPiProviderStatus(settings).pipe(
382 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
383 Effect.forkChild,
384 );
385 yield* Deferred.await(modelRequested);
386 yield* TestClock.adjust("5 seconds");
387 const snapshot = yield* Fiber.join(fiber);
388 assert.equal(snapshot.status, "ready");
389 assert.equal(snapshot.auth.status, "authenticated");
390 assert.deepEqual(
391 snapshot.models.map((model) => [model.slug, model.supportsTextGeneration]),
392 [
393 ["default", undefined],
394 ["demo/demo-model", undefined],
395 ],
396 );
397 assert.equal(snapshot.supportsTextGeneration, undefined);
398 assert.include(
399 snapshot.slashCommands.map((command) => command.name),
400 "compact",
401 );
402 }).pipe(Effect.provide(NodeServices.layer)),
403 );
404​
405 it.effect("advertises a model's service tiers beside its thinking levels", () =>
406 Effect.gen(function* () {
407 const spawner = yield* piDiscoverySpawner({
408 models: [
409 {
410 provider: "columbia-codex",
411 id: "gpt-6.1-sol",
412 reasoning: true,
413 serviceTiers: [
414 { id: "priority", name: "Fast", description: "2x speed, increased usage" },
415 { id: "ultrafast", name: "Ultrafast" },
416 ],
417 },
418 { provider: "anthropic", id: "claude-sonnet-4", reasoning: true },
419 ],
420 });
421 const snapshot = yield* checkPiProviderStatus(settings).pipe(
422 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
423 );
424 const descriptors = (slug: string) =>
425 snapshot.models.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? [];
426 assert.deepEqual(
427 descriptors("columbia-codex/gpt-6.1-sol").map((descriptor) => descriptor.id),
428 ["thinking", "serviceTier"],
429 );
430 assert.deepEqual(descriptors("columbia-codex/gpt-6.1-sol")[1], {
431 id: "serviceTier",
432 label: "Service Tier",
433 type: "select",
434 options: [
435 { id: "default", label: "Standard", isDefault: true },
436 { id: "priority", label: "Fast", description: "2x speed, increased usage" },
437 { id: "ultrafast", label: "Ultrafast" },
438 ],
439 currentValue: "default",
440 });
441 assert.deepEqual(
442 descriptors("anthropic/claude-sonnet-4").map((descriptor) => descriptor.id),
443 ["thinking"],
444 );
445 }).pipe(Effect.provide(NodeServices.layer)),
446 );
447​
448 it.effect.each([
449 { launchArgs: "", startupDialog: true, models: ["default", "anthropic/claude-opus"] },
450 { launchArgs: "--approve", startupDialog: true, models: ["default"] },
451 {
452 launchArgs: "",
453 startupDialog: false,
454 models: ["default", "anthropic/claude-opus", "project/local-model"],
455 },
456 ])(
457 "keeps project trust unless a startup dialog blocks discovery (dialog: $startupDialog, launch args '$launchArgs')",
458 (row) =>
459 Effect.gen(function* () {
460 const spawner = yield* piDiscoverySpawner(
461 {
462 models: [
463 { provider: "anthropic", id: "claude-opus" },
464 { provider: "project", id: "local-model" },
465 ],
466 },
467 undefined,
468 undefined,
469 {
470 startupDialog: row.startupDialog,
471 declinedProjectInventory: { models: [{ provider: "anthropic", id: "claude-opus" }] },
472 },
473 );
474 const snapshot = yield* checkPiProviderStatus({
475 ...settings,
476 launchArgs: row.launchArgs,
477 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
478 assert.deepEqual(
479 snapshot.models.map((model) => model.slug),
480 row.models,
481 );
482 }).pipe(Effect.provide(NodeServices.layer)),
483 );
484​
485 // regression: #18498 a malformed model inventory must not restore stale Pi models
486 it.effect.each([
487 ["missing models", {}],
488 ["missing model id", { models: [{ provider: "anthropic" }] }],
489 [
490 "mixed valid and invalid models",
491 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }, { provider: "openrouter" }] },
492 ],
493 ] as const)("reports unknown authentication when Pi discovery returns %s", (_label, inventory) =>
494 Effect.gen(function* () {
495 const spawner = yield* piDiscoverySpawner(inventory);
496 const snapshot = yield* checkPiProviderStatus(settings).pipe(
497 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
498 );
499 assert.equal(snapshot.status, "ready");
500 assert.equal(snapshot.auth.status, "unknown");
501 }).pipe(Effect.provide(NodeServices.layer)),
502 );
503});