Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
4import { expect, it } from "@effect/vitest";
5import * as SecureRandom from "effect/crypto/SecureRandom";
6import * as Deferred from "effect/Deferred";
7import * as ConfigProvider from "effect/ConfigProvider";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as TestClock from "effect/testing/TestClock";
14
15import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
18
19import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
20import {
21 PUBLISH_AGENT_ACTIVITY_SECRET,
22 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
23 RELAY_URL_SECRET,
24} from "../cloud/config.ts";
25import * as ServerConfig from "../config.ts";
26import * as ServerEnvironment from "./ServerEnvironment.ts";
27
28const layerServerEnvironment = (baseDir: string) =>
29 ServerEnvironment.layer.pipe(
30 Layer.provide(ServerSecretStore.layer),
31 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
32 );
33
34const layerEmptySecretStore = Layer.succeed(
35 ServerSecretStore.ServerSecretStore,
36 ServerSecretStore.ServerSecretStore.of({
37 get: () => Effect.succeedNone,
38 set: () => Effect.void,
39 create: () => Effect.void,
40 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
41 remove: () => Effect.void,
42 }),
43);
44
45const makeServerConfig = Effect.fn(function* (baseDir: string) {
46 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
47
48 return {
49 ...derivedPaths,
50 logLevel: "Error",
51 traceMinLevel: "Info",
52 traceTimingEnabled: true,
53 traceBatchWindowMs: 200,
54 traceMaxBytes: 10 * 1024 * 1024,
55 traceMaxFiles: 10,
56 otlpTracesUrl: undefined,
57 otlpMetricsUrl: undefined,
58 otlpLogsUrl: undefined,
59 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
60 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
61 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
62 otelEnvironment: OtelEnvironment.none,
63 cwd: process.cwd(),
64 baseDir,
65 mode: "web",
66 autoBootstrapProjectFromCwd: false,
67 logWebSocketEvents: false,
68 tailscaleServeEnabled: false,
69 tailscaleServePort: 443,
70 port: 0,
71 host: undefined,
72 desktopBootstrapToken: undefined,
73 staticDir: undefined,
74 devUrl: undefined,
75 devAllowedOrigins: [],
76 noBrowser: false,
77 startupPresentation: "browser",
78 } satisfies ServerConfig.ServerConfig["Service"];
79});
80
81it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmentLive", (it) => {
82 it.effect("publishes proven install ownership only for manually updated servers", () =>
83 Effect.gen(function* () {
84 const fs = yield* FileSystem.FileSystem;
85 const platform = yield* HostProcess.Platform;
86 const baseDir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
87 const prefix = `${baseDir}/node`;
88 const entry = `${prefix}/lib/node_modules/t3/dist/bin.mjs`;
89 yield* fs.makeDirectory(`${prefix}/lib/node_modules/t3/dist`, { recursive: true });
90 yield* fs.makeDirectory(`${prefix}/bin`, { recursive: true });
91 yield* fs.writeFileString(entry, "");
92 yield* fs.writeFileString(
93 `${prefix}/lib/node_modules/t3/package.json`,
94 '{"name":"t3","version":"0.0.45","bin":{"t3":"./dist/bin.mjs"}}',
95 );
96 yield* fs.symlink(entry, `${prefix}/bin/t3`);
97 const config = yield* makeServerConfig(baseDir);
98 yield* fs.makeDirectory(config.stateDir, { recursive: true });
99 for (const mode of ["web", "desktop"] as const) {
100 const descriptor = yield* Effect.gen(function* () {
101 const environment = yield* ServerEnvironment.ServerEnvironment;
102 return yield* environment.getDescriptor;
103 }).pipe(
104 Effect.provide(
105 ServerEnvironment.layer.pipe(
106 Layer.provide(layerEmptySecretStore),
107 Layer.provide(ServerConfig.layer({ ...config, mode })),
108 ),
109 ),
110 Effect.provideService(HostProcess.Arguments, ["node", entry]),
111 Effect.provideService(HostProcess.IsExecutable, false),
112 Effect.provideService(HostProcess.Environment, {}),
113 );
114 expect(descriptor.capabilities.serverInstallation).toEqual(
115 mode === "web" && platform !== "win32" ? { kind: "npm-global", prefix } : undefined,
116 );
117 expect(descriptor.capabilities.serverSelfUpdate).toBe(
118 mode === "web" ? undefined : "desktop-managed",
119 );
120 expect(descriptor.capabilities).toMatchObject({
121 settledWorktreeCleanup: true,
122 storageCleanupRun: true,
123 projectWorktreeCleanup: true,
124 worktreesDirectory: true,
125 threadAutoSettlementScope: true,
126 });
127 }
128 }),
129 );
130 it.effect.each([
131 { desktopAppUpdate: false, advertised: undefined },
132 { desktopAppUpdate: true, advertised: true },
133 ])(
134 "advertises desktop app updates only when the desktop can install them ($desktopAppUpdate)",
135 ({ desktopAppUpdate, advertised }) =>
136 Effect.gen(function* () {
137 const fs = yield* FileSystem.FileSystem;
138 const baseDir = yield* fs.makeTempDirectoryScoped();
139 const config = yield* makeServerConfig(baseDir);
140 yield* fs.makeDirectory(config.stateDir, { recursive: true });
141 const descriptor = yield* Effect.gen(function* () {
142 const environment = yield* ServerEnvironment.ServerEnvironment;
143 return yield* environment.getDescriptor;
144 }).pipe(
145 Effect.provide(
146 ServerEnvironment.layer.pipe(
147 Layer.provide(layerEmptySecretStore),
148 Layer.provide(
149 ServerConfig.layer({
150 ...config,
151 mode: "desktop",
152 desktopTelemetryControlFd: 5,
153 desktopAppUpdate,
154 }),
155 ),
156 ),
157 ),
158 Effect.provideService(HostProcess.Environment, {}),
159 );
160 const capabilities = descriptor.capabilities;
161 expect({
162 serverSelfUpdate: capabilities.serverSelfUpdate,
163 desktopAppUpdate: capabilities.desktopAppUpdate,
164 desktopAppChannelSwitch: capabilities.desktopAppChannelSwitch,
165 serverSelfUpdateProgress: capabilities.serverSelfUpdateProgress,
166 }).toEqual({
167 serverSelfUpdate: "desktop-managed",
168 desktopAppUpdate: advertised,
169 desktopAppChannelSwitch: advertised,
170 serverSelfUpdateProgress: advertised,
171 });
172 }),
173 );
174 it.effect("names the environment and its machine from the overrides", () =>
175 Effect.gen(function* () {
176 const fileSystem = yield* FileSystem.FileSystem;
177 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
178 prefix: "t3-server-environment-override-test-",
179 });
180 const descriptor = yield* Effect.gen(function* () {
181 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
182 return yield* serverEnvironment.getDescriptor;
183 }).pipe(
184 Effect.provide(
185 layerServerEnvironment(baseDir).pipe(
186 Layer.provide(
187 ConfigProvider.layer(
188 ConfigProvider.fromEnv({
189 env: {
190 T3CODE_ENVIRONMENT_LABEL: " MacBook ",
191 T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop",
192 },
193 }),
194 ),
195 ),
196 ),
197 ),
198 );
199 expect(descriptor.label).toBe("MacBook");
200 expect(descriptor.platform.machine).toBe("laptop");
201 }),
202 );
203 it.effect.each([
204 { platform: "darwin", architecture: "arm64", supported: true },
205 { platform: "linux", architecture: "x64", supported: true },
206 { platform: "linux", architecture: "x64", libc: "musl", supported: false },
207 { platform: "win32", architecture: "arm64", supported: false },
208 { platform: "linux", architecture: "arm", supported: false },
209 ] as const)("advertises voice transcription on $platform-$architecture: $supported", (host) =>
210 Effect.gen(function* () {
211 const fileSystem = yield* FileSystem.FileSystem;
212 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
213 prefix: "t3-server-environment-speech-test-",
214 });
215 const descriptor = yield* Effect.gen(function* () {
216 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
217 return yield* serverEnvironment.getDescriptor;
218 }).pipe(
219 Effect.provide(layerServerEnvironment(baseDir)),
220 Effect.provideService(HostProcess.Platform, host.platform),
221 Effect.provideService(HostProcess.Architecture, host.architecture),
222 Effect.provideService(HostProcess.LinuxLibc, "libc" in host ? host.libc : "gnu"),
223 );
224 expect(descriptor.capabilities.voiceTranscription).toBe(host.supported);
225 }),
226 );
227 it.effect.each([
228 { name: "missing", content: undefined },
229 { name: "empty", content: "" },
230 { name: "whitespace-only", content: " \t\n" },
231 ])("concurrent initializers recover a $name environment id file", ({ content }) =>
232 Effect.gen(function* () {
233 const fileSystem = yield* FileSystem.FileSystem;
234 const random = yield* SecureRandom.SecureRandom;
235 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
236 prefix: "t3-server-environment-concurrent-test-",
237 });
238 const serverConfig = yield* makeServerConfig(baseDir);
239 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
240 if (content !== undefined) {
241 yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
242 }
243 const bothGenerated = yield* Deferred.make<void>();
244 const bothReadEmpty = yield* Deferred.make<void>();
245 const firstInitialized = yield* Deferred.make<void>();
246 let remaining = 2;
247 let emptyReads = 0;
248 const readIdentity = Effect.gen(function* () {
249 const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
250 return yield* identity.getEnvironmentId;
251 }).pipe(
252 Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
253 Effect.provide(Layer.fresh(ServerEnvironment.layerIdentity)),
254 Effect.provideService(ServerConfig.ServerConfig, serverConfig),
255 Effect.provideService(FileSystem.FileSystem, {
256 ...fileSystem,
257 readFileString: (path) =>
258 fileSystem.readFileString(path).pipe(
259 Effect.tap(
260 Effect.fn(function* (value) {
261 if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
262 return;
263 }
264 if (++emptyReads === 2) {
265 yield* Deferred.succeed(bothReadEmpty, undefined);
266 yield* Deferred.await(firstInitialized);
267 } else {
268 yield* Deferred.await(bothReadEmpty);
269 }
270 }),
271 ),
272 ),
273 }),
274 Effect.provideService(SecureRandom.SecureRandom, {
275 ...random,
276 uuidV4: (() =>
277 Effect.gen(function* () {
278 const id = yield* random.uuidV4();
279 if (--remaining === 0) {
280 yield* Deferred.succeed(bothGenerated, undefined);
281 }
282 yield* Deferred.await(bothGenerated);
283 return id;
284 })) as SecureRandom.SecureRandom["Service"]["uuidV4"],
285 }),
286 );
287
288 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
289 concurrency: "unbounded",
290 });
291 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
292
293 expect(first).toBe(second);
294 expect(persisted.trim()).toBe(first);
295 }),
296 );
297
298 it.effect("persists the environment id across service restarts", () =>
299 Effect.gen(function* () {
300 const fileSystem = yield* FileSystem.FileSystem;
301 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
302 prefix: "t3-server-environment-test-",
303 });
304
305 const first = yield* Effect.gen(function* () {
306 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
307 return yield* serverEnvironment.getDescriptor;
308 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
309 const second = yield* Effect.gen(function* () {
310 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
311 return yield* serverEnvironment.getDescriptor;
312 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
313
314 expect(first.environmentId).toBe(second.environmentId);
315 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
316 expect(second.capabilities.repositoryIdentity).toBe(true);
317 expect(second.capabilities.connectionProbe).toBe(true);
318 expect(second.capabilities.attachmentUploads).toBe(true);
319 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
320 expect(second.capabilities.pullRequests).toBe(true);
321 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
322 expect(second.capabilities.usagePriceOverrides).toBe(true);
323 expect(second.capabilities.threadActiveReorder).toBe(true);
324 expect(second.capabilities.threadTitleRegeneration).toBe(true);
325 expect(second.capabilities.threadPullRequests).toBe(true);
326 expect(second.capabilities.threadPullRequestLinking).toBe(true);
327 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
328 expect(second.capabilities.projectProviderInstanceOverrides).toBe(true);
329 expect(second.capabilities.agentActivityPublishing).toBe(false);
330 }),
331 );
332
333 it.effect("reports agent activity publishing from the current secret state", () =>
334 Effect.gen(function* () {
335 const fileSystem = yield* FileSystem.FileSystem;
336 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
337 prefix: "t3-server-environment-publish-test-",
338 });
339 const layerTest = Layer.mergeAll(
340 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
341 ServerSecretStore.layer,
342 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
343
344 yield* Effect.gen(function* () {
345 const secrets = yield* ServerSecretStore.ServerSecretStore;
346 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
347 const encode = (value: string) => new TextEncoder().encode(value);
348
349 const unlinked = yield* serverEnvironment.getDescriptor;
350 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
351
352 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
353 const withoutLink = yield* serverEnvironment.getDescriptor;
354 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
355
356 yield* secrets.set(RELAY_URL_SECRET, encode(""));
357 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
358 const emptyUrl = yield* serverEnvironment.getDescriptor;
359 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
360
361 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
362 const linked = yield* serverEnvironment.getDescriptor;
363 expect(linked.capabilities.agentActivityPublishing).toBe(true);
364
365 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
366 const disabled = yield* serverEnvironment.getDescriptor;
367 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
368 }).pipe(Effect.provide(layerTest));
369 }),
370 );
371
372 // The descriptor is the clients' liveness probe; a stalled secrets read must not hang it.
373 it.effect("answers the descriptor while secret file reads are stalled", () =>
374 Effect.gen(function* () {
375 const fileSystem = yield* FileSystem.FileSystem;
376 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
377 prefix: "t3-server-environment-stalled-secrets-test-",
378 });
379 let stalled = false;
380 let stalledReads = 0;
381 const layerStallableSecretStore = Layer.effect(
382 ServerSecretStore.ServerSecretStore,
383 Effect.map(ServerSecretStore.ServerSecretStore, (secrets) =>
384 ServerSecretStore.ServerSecretStore.of({
385 ...secrets,
386 get: (name) =>
387 stalled
388 ? Effect.sync(() => {
389 stalledReads++;
390 }).pipe(Effect.andThen(Effect.never))
391 : secrets.get(name),
392 }),
393 ),
394 ).pipe(Layer.provide(ServerSecretStore.layer));
395
396 const descriptor = yield* Effect.gen(function* () {
397 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
398 yield* serverEnvironment.getDescriptor;
399 stalled = true;
400 const probe = Effect.gen(function* () {
401 const pending = yield* serverEnvironment.getDescriptor.pipe(
402 Effect.timeoutOption("10 seconds"),
403 Effect.forkChild,
404 );
405 yield* TestClock.adjust("10 seconds");
406 return yield* Fiber.join(pending);
407 });
408 yield* probe;
409 return yield* probe;
410 }).pipe(
411 Effect.provide(
412 ServerEnvironment.layer.pipe(
413 Layer.provide(layerStallableSecretStore),
414 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
415 ),
416 ),
417 );
418
419 expect(Option.isSome(descriptor)).toBe(true);
420 // Both probes wait on the one stalled read instead of each starting another.
421 expect(stalledReads).toBe(1);
422 }),
423 );
424});