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