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

driver.test.ts

265 lines10.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
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 TestClock from "effect/testing/TestClock";
13import * as HttpClient from "effect/http/HttpClient";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16​
17import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
18import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
20import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
21import type { PiSettings } from "../settings.ts";
22import { PiDriver } from "./driver.ts";
23​
24const layerTest = Layer.mergeAll(
25 TestProviderHost.layer({
26 cwd: "/machine",
27 settings: { ...DEFAULT_SERVER_SETTINGS, enableProviderUpdateChecks: false },
28 runBackgroundWork: false,
29 }),
30 IdAllocator.layer,
31 McpProviderSessions.layer,
32 ProviderLatestVersions.layer,
33 Layer.succeed(
34 HttpClient.HttpClient,
35 HttpClient.make(() => Effect.die("Unexpected HTTP")),
36 ),
37).pipe(Layer.provideMerge(NodeServices.layer));
38​
39const decodeRequest = Schema.decodeSync(
40 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
41);
42const encoder = new TextEncoder();
43const personalSkill = {
44 name: "skill:personal",
45 source: "skill",
46 sourceInfo: { scope: "user", path: "/home/.pi/agent/skills/personal/SKILL.md" },
47};
48​
49const makePiSpawner = Effect.fnUntraced(function* (
50 discovery: { readonly state?: unknown; readonly models?: ReadonlyArray<unknown> } = {},
51) {
52 const pendingCommand = yield* Deferred.make<void>();
53 const launches: Array<ChildProcess.StandardCommand> = [];
54 const spawner = ChildProcessSpawner.make((command) =>
55 Effect.gen(function* () {
56 assert.isTrue(ChildProcess.isStandardCommand(command));
57 if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("Unexpected pipeline");
58 launches.push(command);
59 const version = command.args.includes("--version");
60 const stdout = yield* Queue.unbounded<Uint8Array>();
61 const cwd = command.options.cwd;
62 return ChildProcessSpawner.makeHandle({
63 // Outside the valid PID range, so transport cleanup cannot signal a real process.
64 pid: ChildProcessSpawner.ProcessId(999_999_999),
65 exitCode: version ? Effect.succeed(ChildProcessSpawner.ExitCode(0)) : Effect.never,
66 isRunning: Effect.succeed(!version),
67 kill: () => Effect.void,
68 unref: Effect.succeed(Effect.void),
69 stdin: Sink.forEach((chunk: Uint8Array) => {
70 const request = decodeRequest(new TextDecoder().decode(chunk).trim());
71 if (cwd === "/pending" && request.type === "get_commands") {
72 return Deferred.succeed(pendingCommand, undefined).pipe(Effect.asVoid);
73 }
74 const failed = cwd === "/failed" && request.type === "get_commands";
75 const data =
76 request.type === "get_commands"
77 ? {
78 commands: [
79 personalSkill,
80 ...(cwd === "/machine"
81 ? []
82 : [
83 {
84 name: `skill:${cwd?.slice(1)}`,
85 source: "skill",
86 sourceInfo: {
87 scope: "project",
88 path: `${cwd}/.agents/skills/SKILL.md`,
89 },
90 },
91 { name: `prompt-${cwd?.slice(1)}`, source: "prompt" },
92 ]),
93 ],
94 }
95 : request.type === "get_available_models"
96 ? { models: discovery.models ?? [{ provider: "test", id: "model" }] }
97 : request.type === "get_state"
98 ? (discovery.state ?? {})
99 : {};
100 return Queue.offer(
101 stdout,
102 encoder.encode(
103 `${JSON.stringify({ type: "response", id: request.id, success: !failed, data, ...(failed ? { error: "commands unavailable" } : {}) })}\n`,
104 ),
105 ).pipe(Effect.asVoid);
106 }),
107 stdout: version ? Stream.succeed(encoder.encode("pi 1.0.2\n")) : Stream.fromQueue(stdout),
108 stderr: Stream.empty,
109 all: Stream.empty,
110 getInputFd: () => Sink.drain,
111 getOutputFd: () => Stream.empty,
112 });
113 }),
114 );
115 return { spawner, launches, pendingCommand };
116});
117​
118const create = (config: Partial<PiSettings> = {}, enabled = true) =>
119 PiDriver.create({
120 instanceId: ProviderInstanceId.make("pi-workspace-test"),
121 displayName: "My Pi",
122 accentColor: "#abcdef",
123 environment: [{ name: "PI_CODING_AGENT_DIR", value: "/isolated-pi", sensitive: false }],
124 enabled,
125 config: { ...PiDriver.defaultConfig(), binaryPath: "custom-pi", ...config },
126 });
127​
128it.layer(layerTest)("PiDriver workspace discovery", (it) => {
129 it.effect("keeps each workspace's skills and commands separate from the machine catalog", () =>
130 Effect.gen(function* () {
131 const { spawner, launches } = yield* makePiSpawner();
132 const instance = yield* create({ launchArgs: '--approve --skill "extra skill"' }).pipe(
133 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
134 );
135 yield* instance.snapshot.refresh;
136 assert.isDefined(instance.snapshotForCwd);
137 const [first, second] = yield* Effect.all(
138 [instance.snapshotForCwd!("/first"), instance.snapshotForCwd!("/second")],
139 { concurrency: "unbounded" },
140 );
141 assert.deepEqual(
142 first.skills.map((skill) => skill.name),
143 ["personal", "first"],
144 );
145 assert.deepEqual(
146 second.skills.map((skill) => skill.name),
147 ["personal", "second"],
148 );
149 assert.deepEqual(
150 first.slashCommands.map((command) => command.name),
151 ["compact", "prompt-first"],
152 );
153 const machine = yield* instance.snapshot.getSnapshot;
154 assert.deepEqual(
155 machine.skills.map((skill) => skill.name),
156 ["personal"],
157 );
158 assert.deepEqual(
159 machine.slashCommands.map((command) => command.name),
160 ["compact"],
161 );
162 assert.equal(first.instanceId, instance.instanceId);
163 assert.equal(first.displayName, "My Pi");
164 assert.equal(first.accentColor, "#abcdef");
165 assert.deepEqual(first.models, machine.models);
166 const workspaceLaunch = launches.find((launch) => launch.options.cwd === "/first");
167 assert.isDefined(workspaceLaunch);
168 assert.equal(workspaceLaunch!.command, "custom-pi");
169 assert.includeMembers(
170 [...workspaceLaunch!.args],
171 ["--approve", "--skill", "extra skill", "--no-session"],
172 );
173 assert.equal(workspaceLaunch!.options.env?.PI_CODING_AGENT_DIR, "/isolated-pi");
174 }).pipe(Effect.scoped),
175 );
176​
177 it.effect("does not run a disabled provider's workspace probe", () =>
178 Effect.gen(function* () {
179 const instance = yield* create({}, false).pipe(
180 Effect.provideService(
181 ChildProcessSpawner.ChildProcessSpawner,
182 ChildProcessSpawner.make(() => Effect.die("Disabled Pi must not spawn")),
183 ),
184 );
185 assert.isDefined(instance.snapshotForCwd);
186 const workspace = yield* instance.snapshotForCwd!("/first");
187 assert.isFalse(workspace.enabled);
188 assert.deepEqual(workspace.skills, []);
189 }).pipe(Effect.scoped),
190 );
191​
192 it.effect.each([true, false])(
193 "limits discovered thinking defaults to the known active model, known=%s",
194 (known) =>
195 Effect.gen(function* () {
196 const { spawner } = yield* makePiSpawner({
197 state: {
198 thinkingLevel: "high",
199 ...(known ? { model: { provider: "test", id: "model" } } : {}),
200 },
201 models: [
202 { provider: "test", id: "model", reasoning: true },
203 { provider: "other", id: "model", reasoning: true },
204 { provider: "test", id: "other", reasoning: true },
205 ],
206 });
207 const instance = yield* create().pipe(
208 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
209 );
210 yield* instance.snapshot.refresh;
211 const snapshot = yield* instance.snapshot.getSnapshot;
212 assert.deepEqual(
213 snapshot.models.map((model) => [
214 model.slug,
215 (model.capabilities?.optionDescriptors ?? []).flatMap((descriptor) =>
216 descriptor.type === "select"
217 ? descriptor.options.filter((option) => option.isDefault).map((option) => option.id)
218 : [],
219 ),
220 ]),
221 [
222 ["default", []],
223 ["test/model", known ? ["high"] : []],
224 ["other/model", []],
225 ["test/other", []],
226 ],
227 );
228 }).pipe(Effect.scoped),
229 );
230​
231 it.effect(
232 "fails command discovery instead of returning an empty successful workspace catalog",
233 () =>
234 Effect.gen(function* () {
235 const { spawner } = yield* makePiSpawner();
236 const instance = yield* create().pipe(
237 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
238 );
239 yield* instance.snapshot.refresh;
240 assert.isDefined(instance.snapshotForCwd);
241 const error = yield* Effect.flip(instance.snapshotForCwd!("/failed"));
242 assert.equal(error._tag, "ProviderDriverError");
243 assert.equal(error.instanceId, instance.instanceId);
244 assert.deepEqual(
245 (yield* instance.snapshot.getSnapshot).skills.map((skill) => skill.name),
246 ["personal"],
247 );
248 }).pipe(Effect.scoped),
249 );
250​
251 it.effect("times out workspace discovery that needs interactive input", () =>
252 Effect.gen(function* () {
253 const { spawner, pendingCommand } = yield* makePiSpawner();
254 const instance = yield* create().pipe(
255 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
256 );
257 const probe = yield* instance.snapshotForCwd!("/pending").pipe(Effect.flip, Effect.forkChild);
258 yield* Deferred.await(pendingCommand);
259 yield* TestClock.adjust("15 seconds");
260 const error = yield* Fiber.join(probe);
261 assert.equal(error._tag, "ProviderDriverError");
262 assert.include(error.detail, "workspace commands");
263 }).pipe(Effect.scoped),
264 );
265});