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

driver.test.ts

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