Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
3import { expect, it } from "@effect/vitest";
4import * as Crypto from "effect/Crypto";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11
12import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
15
16import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
17import {
18 PUBLISH_AGENT_ACTIVITY_SECRET,
19 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
20 RELAY_URL_SECRET,
21} from "../cloud/config.ts";
22import * as ServerConfig from "../config.ts";
23import * as ServerEnvironment from "./ServerEnvironment.ts";
24
25const isServerEnvironmentIdPersistenceError = Schema.is(
26 ServerEnvironment.ServerEnvironmentIdPersistenceError,
27);
28
29const layerServerEnvironment = (baseDir: string) =>
30 ServerEnvironment.layer.pipe(
31 Layer.provide(ServerSecretStore.layer),
32 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
33 );
34
35const layerEmptySecretStore = Layer.succeed(
36 ServerSecretStore.ServerSecretStore,
37 ServerSecretStore.ServerSecretStore.of({
38 get: () => Effect.succeedNone,
39 set: () => Effect.void,
40 create: () => Effect.void,
41 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
42 remove: () => Effect.void,
43 }),
44);
45
46const makeServerConfig = Effect.fn(function* (baseDir: string) {
47 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
48
49 return {
50 ...derivedPaths,
51 logLevel: "Error",
52 traceMinLevel: "Info",
53 traceTimingEnabled: true,
54 traceBatchWindowMs: 200,
55 traceMaxBytes: 10 * 1024 * 1024,
56 traceMaxFiles: 10,
57 otlpTracesUrl: undefined,
58 otlpMetricsUrl: undefined,
59 otlpLogsUrl: undefined,
60 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
61 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
62 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
63 otelEnvironment: OtelEnvironment.none,
64 cwd: process.cwd(),
65 baseDir,
66 mode: "web",
67 autoBootstrapProjectFromCwd: false,
68 logWebSocketEvents: false,
69 tailscaleServeEnabled: false,
70 tailscaleServePort: 443,
71 port: 0,
72 host: undefined,
73 desktopBootstrapToken: undefined,
74 staticDir: undefined,
75 devUrl: undefined,
76 devAllowedOrigins: [],
77 noBrowser: false,
78 startupPresentation: "browser",
79 } satisfies ServerConfig.ServerConfig["Service"];
80});
81
82it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
83 it.effect("publishes proven install ownership only for manually updated servers", () =>
84 Effect.gen(function* () {
85 const fs = yield* FileSystem.FileSystem;
86 const baseDir = 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.Platform, "linux"),
113 Effect.provideService(HostProcess.Environment, {}),
114 );
115 expect(descriptor.capabilities.serverInstallation).toEqual(
116 mode === "web" ? { kind: "npm-global", prefix } : undefined,
117 );
118 expect(descriptor.capabilities.serverSelfUpdate).toBe(
119 mode === "web" ? undefined : "desktop-managed",
120 );
121 }
122 }),
123 );
124 it.effect.each([
125 { name: "missing", content: undefined },
126 { name: "empty", content: "" },
127 { name: "whitespace-only", content: " \t\n" },
128 ])("concurrent initializers recover a $name environment id file", ({ content }) =>
129 Effect.gen(function* () {
130 const fileSystem = yield* FileSystem.FileSystem;
131 const crypto = yield* Crypto.Crypto;
132 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
133 prefix: "t3-server-environment-concurrent-test-",
134 });
135 const serverConfig = yield* makeServerConfig(baseDir);
136 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
137 if (content !== undefined) {
138 yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
139 }
140 const bothGenerated = yield* Deferred.make<void>();
141 const bothReadEmpty = yield* Deferred.make<void>();
142 const firstInitialized = yield* Deferred.make<void>();
143 let remaining = 2;
144 let emptyReads = 0;
145 const readIdentity = Effect.gen(function* () {
146 const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
147 return yield* identity.getEnvironmentId;
148 }).pipe(
149 Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
150 Effect.provide(Layer.fresh(ServerEnvironment.layerIdentity)),
151 Effect.provideService(ServerConfig.ServerConfig, serverConfig),
152 Effect.provideService(FileSystem.FileSystem, {
153 ...fileSystem,
154 readFileString: (path) =>
155 fileSystem.readFileString(path).pipe(
156 Effect.tap(
157 Effect.fn(function* (value) {
158 if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
159 return;
160 }
161 // Both observe the empty file, but one repairs it after the other has finished.
162 if (++emptyReads === 2) {
163 yield* Deferred.succeed(bothReadEmpty, undefined);
164 yield* Deferred.await(firstInitialized);
165 } else {
166 yield* Deferred.await(bothReadEmpty);
167 }
168 }),
169 ),
170 ),
171 }),
172 Effect.provideService(Crypto.Crypto, {
173 ...crypto,
174 randomUUIDv4: Effect.gen(function* () {
175 const id = yield* crypto.randomUUIDv4;
176 if (--remaining === 0) {
177 yield* Deferred.succeed(bothGenerated, undefined);
178 }
179 yield* Deferred.await(bothGenerated);
180 return id;
181 }),
182 }),
183 );
184
185 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
186 concurrency: "unbounded",
187 });
188 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
189
190 expect(first).toBe(second);
191 expect(persisted.trim()).toBe(first);
192 }),
193 );
194
195 it.effect("persists the environment id across service restarts", () =>
196 Effect.gen(function* () {
197 const fileSystem = yield* FileSystem.FileSystem;
198 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
199 prefix: "t3-server-environment-test-",
200 });
201
202 const first = yield* Effect.gen(function* () {
203 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
204 return yield* serverEnvironment.getDescriptor;
205 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
206 const second = yield* Effect.gen(function* () {
207 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
208 return yield* serverEnvironment.getDescriptor;
209 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
210
211 expect(first.environmentId).toBe(second.environmentId);
212 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
213 expect(second.capabilities.repositoryIdentity).toBe(true);
214 expect(second.capabilities.connectionProbe).toBe(true);
215 expect(second.capabilities.attachmentUploads).toBe(true);
216 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
217 expect(second.capabilities.pullRequests).toBe(true);
218 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
219 expect(second.capabilities.usagePriceOverrides).toBe(true);
220 expect(second.capabilities.threadActiveReorder).toBe(true);
221 expect(second.capabilities.threadTitleRegeneration).toBe(true);
222 expect(second.capabilities.threadPullRequests).toBe(true);
223 expect(second.capabilities.threadPullRequestLinking).toBe(true);
224 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
225 expect(second.capabilities.agentActivityPublishing).toBe(false);
226 }),
227 );
228
229 it.effect("reports agent activity publishing from the current secret state", () =>
230 Effect.gen(function* () {
231 const fileSystem = yield* FileSystem.FileSystem;
232 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
233 prefix: "t3-server-environment-publish-test-",
234 });
235 const layerTest = Layer.mergeAll(
236 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
237 ServerSecretStore.layer,
238 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
239
240 yield* Effect.gen(function* () {
241 const secrets = yield* ServerSecretStore.ServerSecretStore;
242 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
243 const encode = (value: string) => new TextEncoder().encode(value);
244
245 const unlinked = yield* serverEnvironment.getDescriptor;
246 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
247
248 // The opt-in alone is not enough: without relay link credentials no
249 // publish would leave this environment.
250 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
251 const withoutLink = yield* serverEnvironment.getDescriptor;
252 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
253
254 // Empty credentials are as unconfigured as missing ones: the
255 // publisher's truthiness gate skips them, so the capability must not
256 // advertise publishing.
257 yield* secrets.set(RELAY_URL_SECRET, encode(""));
258 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
259 const emptyUrl = yield* serverEnvironment.getDescriptor;
260 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
261
262 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
263 const linked = yield* serverEnvironment.getDescriptor;
264 expect(linked.capabilities.agentActivityPublishing).toBe(true);
265
266 // The toggle changes at runtime, so the same service instance must
267 // reflect a flip without a restart.
268 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
269 const disabled = yield* serverEnvironment.getDescriptor;
270 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
271 }).pipe(Effect.provide(layerTest));
272 }),
273 );
274
275 it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
276 Effect.gen(function* () {
277 const fileSystem = yield* FileSystem.FileSystem;
278 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
279 prefix: "t3-server-environment-desktop-update-test-",
280 });
281 const serverConfig = yield* makeServerConfig(baseDir);
282 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
283
284 const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
285 Effect.gen(function* () {
286 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
287 return yield* serverEnvironment.getDescriptor;
288 }).pipe(
289 Effect.provide(
290 ServerEnvironment.layer.pipe(
291 Layer.provide(ServerSecretStore.layer),
292 Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
293 ),
294 ),
295 );
296
297 const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
298 expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
299 expect(withFd.capabilities.desktopAppUpdate).toBe(true);
300 expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
301 // v2 recovery terminalizes running runs on restart, so continuation
302 // stays unadvertised until the v2 runtime carries the markers.
303 expect(withFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
304
305 const withoutFd = yield* describeWith({ mode: "desktop" });
306 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
307 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
308 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
309 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
310
311 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
312 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
313 }),
314 );
315
316 it.effect("structures persisted environment id filesystem failures", () =>
317 Effect.gen(function* () {
318 const fileSystem = yield* FileSystem.FileSystem;
319 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
320 prefix: "t3-server-environment-error-test-",
321 });
322 const serverConfig = yield* makeServerConfig(baseDir);
323 const environmentIdPath = serverConfig.environmentIdPath;
324 const tempPath = `${environmentIdPath}.tmp`;
325 const methodByOperation = {
326 check: "exists",
327 read: "readFileString",
328 write: "writeFileString",
329 } as const;
330
331 for (const operation of ["check", "read", "write"] as const) {
332 const writeAttempts: string[] = [];
333 const cause = PlatformError.systemError({
334 _tag: "PermissionDenied",
335 module: "FileSystem",
336 method: methodByOperation[operation],
337 description: "permission denied",
338 pathOrDescriptor: environmentIdPath,
339 });
340 const layerFailingFileSystem = FileSystem.layerNoop({
341 exists: () =>
342 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
343 readFileString: () => Effect.fail(cause),
344 makeTempFileScoped: () => Effect.succeed(tempPath),
345 writeFileString: (path) => {
346 writeAttempts.push(path);
347 return Effect.fail(cause);
348 },
349 });
350
351 const error = yield* Effect.gen(function* () {
352 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
353 return yield* serverEnvironment.getDescriptor;
354 }).pipe(
355 Effect.provide(
356 ServerEnvironment.layer.pipe(
357 Layer.provide(layerEmptySecretStore),
358 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), layerFailingFileSystem)),
359 ),
360 ),
361 Effect.flip,
362 );
363
364 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
365 if (!isServerEnvironmentIdPersistenceError(error)) {
366 throw error;
367 }
368 expect(error.operation).toBe(operation);
369 expect(error.environmentIdPath).toBe(environmentIdPath);
370 expect(error.cause).toBe(cause);
371 expect(error.message).toBe(
372 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
373 );
374 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
375 }
376 }),
377 );
378});