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

driver.test.ts

191 lines7.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { ProviderInstanceId } from "@t3tools/contracts";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import * as HttpClient from "effect/http/HttpClient";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13​
14import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
15import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
16import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
17import { GrokDriver } from "./driver.ts";
18import { resolveLatestProviderVersion } from "@t3tools/provider-core/server/maintenanceResolver";
19​
20import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
21import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
22​
23const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
24 Layer.provideMerge(NodeServices.layer),
25 Layer.provideMerge(IdAllocator.layer),
26 Layer.provideMerge(McpProviderSessions.layer),
27 Layer.provideMerge(ProviderLatestVersions.layer),
28 Layer.provideMerge(
29 Layer.succeed(
30 ProviderEventLoggers.ProviderEventLoggers,
31 ProviderEventLoggers.NoOpProviderEventLoggers,
32 ),
33 ),
34 Layer.provideMerge(
35 Layer.succeed(
36 HttpClient.HttpClient,
37 HttpClient.make(() => Effect.die("Disabled Grok must not make an HTTP request")),
38 ),
39 ),
40);
41​
42const noSpawner = ChildProcessSpawner.make(() =>
43 Effect.die("Disabled Grok must not spawn a process"),
44);
45​
46/** Answers every spawn with `onSpawn(command, args)` on stdout, like a stub `brew`. */
47function stdoutSpawner(onSpawn: (command: string, args: ReadonlyArray<string>) => string) {
48 return ChildProcessSpawner.make((command) => {
49 const { command: executable, args } = command as unknown as {
50 readonly command: string;
51 readonly args: ReadonlyArray<string>;
52 };
53 return Effect.succeed(
54 ChildProcessSpawner.makeHandle({
55 pid: ChildProcessSpawner.ProcessId(1),
56 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
57 isRunning: Effect.succeed(false),
58 kill: () => Effect.void,
59 unref: Effect.succeed(Effect.void),
60 stdin: Sink.drain,
61 stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))),
62 stderr: Stream.empty,
63 all: Stream.empty,
64 getInputFd: () => Sink.drain,
65 getOutputFd: () => Stream.empty,
66 }),
67 );
68 });
70​
71// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
72const windowsHost = HostProcess.Platform.defaultValue() === "win32";
73​
74it.layer(layerTest)("GrokDriver", (it) => {
75 // Each case puts a stub `brew` at `<prefix>/bin/brew` beside the Grok binary.
76 const homebrewCases = [
77 {
78 name: "upgrades a Homebrew grok-build cask through brew",
79 binary: ["Caskroom", "grok-build", "1.2.3,456", "grok"],
80 reportedPrefix: "own",
81 brewArgs: [["--prefix"]],
82 latestVersion: "1.2.4",
83 update: (brewPath: string, _binaryPath: string) => ({
84 command: "brew upgrade --cask grok-build",
85 executable: brewPath,
86 args: ["upgrade", "--cask", "grok-build"],
87 lockKey: "homebrew",
88 }),
89 },
90 {
91 // `grok update` would install a second copy beside the cask.
92 name: "stays manual-only for a cask another brew prefix owns",
93 binary: ["Caskroom", "grok-build", "1.2.3", "grok"],
94 reportedPrefix: "/opt/homebrew",
95 brewArgs: [["--prefix"]],
96 latestVersion: undefined,
97 update: () => null,
98 },
99 {
100 // A formula keg such as `node` holding an npm global is not Grok's owner.
101 name: "keeps grok update for an npm global inside a Homebrew node keg",
102 binary: [
103 "Cellar",
104 "node",
105 "22",
106 "lib",
107 "node_modules",
108 "@xai-official",
109 "grok",
110 "bin",
111 "grok",
112 ],
113 reportedPrefix: "own",
114 brewArgs: [],
115 latestVersion: undefined,
116 update: (_brewPath: string, binaryPath: string) => ({
117 executable: binaryPath,
118 args: ["update"],
119 lockKey: "grok",
120 }),
121 },
122 ] as const;
123​
124 for (const testCase of homebrewCases) {
125 it.effect.skipIf(windowsHost)(testCase.name, () => {
126 const brewArgs: Array<ReadonlyArray<string>> = [];
127 let prefix = "";
128 return Effect.gen(function* () {
129 const fs = yield* FileSystem.FileSystem;
130 const path = yield* Path.Path;
131 prefix = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-grok-brew-" }));
132 const brewPath = path.join(prefix, "bin", "brew");
133 const binaryPath = path.join(prefix, ...testCase.binary);
134 for (const executable of [brewPath, binaryPath]) {
135 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
136 yield* fs.writeFileString(executable, "#!/bin/sh\n");
137 yield* fs.chmod(executable, 0o755);
138 }
139​
140 const instance = yield* GrokDriver.create({
141 instanceId: ProviderInstanceId.make("grok-homebrew"),
142 displayName: "Grok test",
143 enabled: false,
144 environment: [],
145 config: { ...GrokDriver.defaultConfig(), binaryPath },
146 });
147 const capabilities = yield* instance.snapshot.resolveMaintenance();
148​
149 const update = testCase.update(brewPath, binaryPath);
150 expect(brewArgs).toEqual(testCase.brewArgs);
151 expect(capabilities.update).toEqual(update && expect.objectContaining(update));
152 if (testCase.latestVersion !== undefined) {
153 expect(yield* resolveLatestProviderVersion(capabilities)).toBe(testCase.latestVersion);
154 expect(brewArgs).toEqual([...testCase.brewArgs, ["info", "--json=v2", "grok-build"]]);
155 }
156 }).pipe(
157 Effect.provideService(
158 ChildProcessSpawner.ChildProcessSpawner,
159 stdoutSpawner((command, args) => {
160 expect(command).toBe(`${prefix}/bin/brew`);
161 brewArgs.push(args);
162 if (args[0] === "--prefix") {
163 return `${testCase.reportedPrefix === "own" ? prefix : testCase.reportedPrefix}\n`;
164 }
165 return JSON.stringify({ casks: [{ version: "1.2.4,789" }] });
166 }),
167 ),
168 Effect.scoped,
169 );
170 });
171 }
172​
173 it.effect("stays manual-only when the configured executable does not exist", () =>
174 Effect.gen(function* () {
175 const fs = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-grok-missing-" });
178 const instance = yield* GrokDriver.create({
179 instanceId: ProviderInstanceId.make("grok-missing"),
180 displayName: "Grok test",
181 enabled: false,
182 environment: [],
183 config: { ...GrokDriver.defaultConfig(), binaryPath: path.join(tempDir, "grok") },
184 });
185 expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
186 }).pipe(
187 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawner),
188 Effect.scoped,
189 ),
190 );
191});