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