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