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

providerInstallation.test.ts

280 lines10.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import {
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ProviderInstallState,
7} from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Effect from "effect/Effect";
10import * as Deferred from "effect/Deferred";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Stream from "effect/Stream";
15​
16import * as ServerSettings from "../serverSettings.ts";
17import * as CodexInstallation from "./CodexInstallation.ts";
18import * as AntigravityInstallation from "./AntigravityInstallation.ts";
19import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
20import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
21import * as ProviderInstallation from "./providerInstallation.ts";
22import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
23import * as ProviderRegistry from "./ProviderRegistry.ts";
24​
25const instanceId = ProviderInstanceId.make("antigravity");
26const driver = ProviderDriverKind.make("antigravity");
27const state: ProviderInstallState = {
28 driver,
29 operationId: null,
30 phase: "idle",
31 downloadedBytes: 0,
32 totalBytes: null,
33 version: null,
34 installedVersion: null,
35 canRemove: false,
36 message: null,
37};
38​
39function instance(kind = driver, id = instanceId): ProviderInstance {
40 return {
41 instanceId: id,
42 driverKind: kind,
43 enabled: false,
44 displayName: undefined,
45 continuationIdentity: { driverKind: kind, continuationKey: instanceId },
46 get orchestrationAdapter(): never {
47 throw new Error("Installation must not start a provider session.");
48 },
49 get snapshot(): never {
50 throw new Error("Installation routing must not probe the provider.");
51 },
52 get textGeneration(): never {
53 throw new Error("Installation must not generate text.");
54 },
55 };
57​
58const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* (
59 input: {
60 instance?: ProviderInstance;
61 others?: ReadonlyArray<ProviderInstance>;
62 settings?: Parameters<typeof ServerSettings.layerTest>[0];
63 /** The states an install passes through, whoever started it. */
64 installStates?: ReadonlyArray<ProviderInstallState>;
65 } = {},
66) {
67 const calls: string[] = [];
68 const observed = yield* Deferred.make<void>();
69 let protectedPaths: ReadonlyArray<string> = [];
70 const configured = input.instance ?? instance();
71 const all = [configured, ...(input.others ?? [])];
72 const refreshedInstances: ProviderInstanceId[] = [];
73 const dependencies = Layer.mergeAll(
74 ServerSettings.layerTest(input.settings),
75 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
76 getInstance: (id) => Effect.succeed(all.find((entry) => entry.instanceId === id)),
77 listInstances: Effect.succeed(all),
78 }),
79 Layer.mock(ProviderRegistry.ProviderRegistry)({
80 refreshInstance: (id) =>
81 Effect.sync(() => {
82 calls.push("refresh");
83 refreshedInstances.push(id);
84 return [];
85 }),
86 }),
87 Layer.mock(CodexInstallation.CodexInstallation)({
88 managedDirectory: "/unused-managed-codex",
89 start: Effect.sync(() => {
90 calls.push("codex-start");
91 return { ...state, driver: ProviderDriverKind.make("codex") };
92 }),
93 cancel: () =>
94 Effect.sync(() => {
95 calls.push("codex-cancel");
96 return { ...state, driver: ProviderDriverKind.make("codex") };
97 }),
98 state: Effect.succeed({ ...state, driver: ProviderDriverKind.make("codex") }),
99 changes: Stream.succeed({ ...state, driver: ProviderDriverKind.make("codex") }),
100 checkForUpdate: Effect.void,
101 remove: (paths) =>
102 Effect.sync(() => {
103 protectedPaths = paths ?? [];
104 calls.push("codex-remove");
105 }),
106 }),
107 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
108 managedDirectory: "/unused-managed-runtime",
109 checkForUpdate: Effect.void,
110 invalidateUpdateCheck: Effect.void,
111 start: Effect.sync(() => {
112 calls.push("start");
113 return { ...state, operationId: "install-1", phase: "downloading" as const };
114 }),
115 cancel: () =>
116 Effect.sync(() => {
117 calls.push("cancel");
118 return state;
119 }),
120 state: Effect.succeed(state),
121 // Ends after its last state is handled, so `observed` marks the end of the service's watch.
122 changes: Stream.fromIterable(input.installStates ?? [state]).pipe(
123 Stream.ensuring(Deferred.succeed(observed, undefined)),
124 ),
125 remove: (paths) =>
126 Effect.sync(() => {
127 protectedPaths = paths ?? [];
128 calls.push("remove");
129 }),
130 }),
131 );
132 const context = yield* Layer.build(ProviderInstallation.layer.pipe(Layer.provide(dependencies)));
133 const router = yield* Effect.service(ProviderInstallation.ProviderInstallation).pipe(
134 Effect.provide(context),
135 );
136 return {
137 router,
138 calls,
139 observed,
140 refreshedInstances,
141 protectedPaths: () => protectedPaths,
142 };
143});
144​
145const installed = (operationId: string, phase: ProviderInstallState["phase"]) => ({
146 ...state,
147 operationId,
148 phase,
149 installedVersion: phase === "succeeded" ? "1.5.8" : null,
150});
151​
152describe("provider installation routing", () => {
153 it.effect.each([
154 { phase: "succeeded", enabled: true, checkFails: false, expectedChecks: 1 },
155 { phase: "succeeded", enabled: true, checkFails: true, expectedChecks: 1 },
156 { phase: "succeeded", enabled: false, checkFails: false, expectedChecks: 0 },
157 { phase: "cancelled", enabled: true, checkFails: false, expectedChecks: 0 },
158 { phase: "failed", enabled: true, checkFails: false, expectedChecks: 0 },
159 ] as const)(
160 "checks account access once after an installation is $phase, enabled=$enabled, checkFails=$checkFails",
161 ({ phase, enabled, checkFails, expectedChecks }) =>
162 Effect.gen(function* () {
163 let checks = 0;
164 // No client starts this install: the provider update flow runs the installer itself.
165 const harness = yield* makeHarness({
166 installStates: [
167 installed("install-1", "downloading"),
168 installed("install-1", phase),
169 { ...installed("install-1", phase), version: "1.5.8" },
170 ],
171 instance: Object.assign(instance(), {
172 enabled,
173 refreshModels: () =>
174 Effect.sync(() => {
175 checks++;
176 }).pipe(
177 Effect.andThen(
178 checkFails
179 ? Effect.fail(
180 new ProviderDriverError({
181 driver,
182 instanceId,
183 detail: "Sign in required.",
184 }),
185 )
186 : Effect.void,
187 ),
188 ),
189 }),
190 });
191 yield* Deferred.await(harness.observed);
192 assert.strictEqual(checks, expectedChecks);
193 assert.deepEqual(harness.calls, expectedChecks > 0 ? ["refresh"] : []);
194 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
195 );
196​
197 it.effect("checks every enabled instance on the managed runtime after each install", () =>
198 Effect.gen(function* () {
199 const checked: string[] = [];
200 const managed = (id: string, enabled: boolean) =>
201 Object.assign(instance(driver, ProviderInstanceId.make(id)), {
202 enabled,
203 refreshModels: () =>
204 Effect.sync(() => {
205 checked.push(id);
206 }),
207 });
208 const work = managed("antigravity_work", true);
209 const personal = managed("antigravity_personal", true);
210 const harness = yield* makeHarness({
211 installStates: [installed("install-1", "succeeded"), installed("install-2", "succeeded")],
212 // The disabled default instance is listed first, as server.getConfig lists it.
213 instance: managed("antigravity", false),
214 others: [managed("antigravity_custom", true), work, personal],
215 settings: {
216 providerInstances: {
217 [ProviderInstanceId.make("antigravity_custom")]: {
218 driver,
219 config: { binaryPath: "/external/agy" },
220 },
221 },
222 },
223 });
224 yield* Deferred.await(harness.observed);
225 const eachInstall = [work.instanceId, personal.instanceId];
226 assert.deepEqual(checked, [...eachInstall, ...eachInstall]);
227 assert.deepEqual(harness.refreshedInstances, [...eachInstall, ...eachInstall]);
228 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
229 );
230​
231 it.effect("keeps external installs manual without hiding shared install status", () =>
232 Effect.gen(function* () {
233 const harness = yield* makeHarness({
234 settings: {
235 providerInstances: {
236 [ProviderInstanceId.make("antigravity")]: {
237 driver: ProviderDriverKind.make("antigravity"),
238 config: { binaryPath: "/external/agy" },
239 },
240 },
241 },
242 });
243 const start = yield* Effect.flip(harness.router.start({ instanceId }));
244 const remove = yield* Effect.flip(harness.router.remove({ instanceId }));
245 assert.include(start.detail, "custom executable");
246 assert.include(remove.detail, "custom executable");
247 const observed = yield* Stream.runCollect(harness.router.subscribe({ instanceId }));
248 assert.deepEqual(Array.from(observed), [state]);
249 assert.deepEqual(harness.calls, []);
250 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
251 );
252​
253 it.effect("protects another instance's binary found through its own PATH", () =>
254 Effect.gen(function* () {
255 const fs = yield* FileSystem.FileSystem;
256 const path = yield* Path.Path;
257 const platform = yield* HostProcess.Platform;
258 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-install-route-" });
259 const binary = platform === "win32" ? "agy-test.exe" : "agy-test";
260 const executable = path.join(directory, binary);
261 yield* fs.writeFileString(executable, "test");
262 yield* fs.chmod(executable, 0o755);
263 const other = ProviderInstanceId.make("antigravity-work");
264 const harness = yield* makeHarness({
265 settings: {
266 providerInstances: {
267 [other]: {
268 driver,
269 config: { binaryPath: binary },
270 environment: [{ name: "PATH", value: directory, sensitive: false }],
271 },
272 },
273 },
274 });
275 yield* harness.router.remove({ instanceId });
276 assert.include(harness.protectedPaths(), executable);
277 assert.deepEqual(harness.calls, ["remove", "refresh"]);
278 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
279 );
280});