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.agentActivityPublishing).toBe(false);
177 }),
178 );
179
180 it.effect("reports agent activity publishing from the current secret state", () =>
181 Effect.gen(function* () {
182 const fileSystem = yield* FileSystem.FileSystem;
183 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
184 prefix: "t3-server-environment-publish-test-",
185 });
186 const testLayer = Layer.mergeAll(
187 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
188 ServerSecretStore.layer,
189 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
190
191 yield* Effect.gen(function* () {
192 const secrets = yield* ServerSecretStore.ServerSecretStore;
193 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
194 const encode = (value: string) => new TextEncoder().encode(value);
195
196 const unlinked = yield* serverEnvironment.getDescriptor;
197 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
198
199 // The opt-in alone is not enough: without relay link credentials no
200 // publish would leave this environment.
201 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
202 const withoutLink = yield* serverEnvironment.getDescriptor;
203 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
204
205 // Empty credentials are as unconfigured as missing ones: the
206 // publisher's truthiness gate skips them, so the capability must not
207 // advertise publishing.
208 yield* secrets.set(RELAY_URL_SECRET, encode(""));
209 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
210 const emptyUrl = yield* serverEnvironment.getDescriptor;
211 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
212
213 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
214 const linked = yield* serverEnvironment.getDescriptor;
215 expect(linked.capabilities.agentActivityPublishing).toBe(true);
216
217 // The toggle changes at runtime, so the same service instance must
218 // reflect a flip without a restart.
219 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
220 const disabled = yield* serverEnvironment.getDescriptor;
221 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
222 }).pipe(Effect.provide(testLayer));
223 }),
224 );
225
226 it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
227 Effect.gen(function* () {
228 const fileSystem = yield* FileSystem.FileSystem;
229 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
230 prefix: "t3-server-environment-desktop-update-test-",
231 });
232 const serverConfig = yield* makeServerConfig(baseDir);
233 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
234
235 const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
236 Effect.gen(function* () {
237 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
238 return yield* serverEnvironment.getDescriptor;
239 }).pipe(
240 Effect.provide(
241 ServerEnvironment.layer.pipe(
242 Layer.provide(ServerSecretStore.layer),
243 Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
244 ),
245 ),
246 );
247
248 const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
249 expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
250 expect(withFd.capabilities.desktopAppUpdate).toBe(true);
251 expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
252 expect(withFd.capabilities.serverUpdateThreadContinuation).toBe(true);
253
254 const withoutFd = yield* describeWith({ mode: "desktop" });
255 expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
256 expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
257 expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
258 expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
259
260 const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
261 expect(web.capabilities.desktopAppUpdate).toBeUndefined();
262 }),
263 );
264
265 it.effect("structures persisted environment id filesystem failures", () =>
266 Effect.gen(function* () {
267 const fileSystem = yield* FileSystem.FileSystem;
268 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
269 prefix: "t3-server-environment-error-test-",
270 });
271 const serverConfig = yield* makeServerConfig(baseDir);
272 const environmentIdPath = serverConfig.environmentIdPath;
273 const tempPath = `${environmentIdPath}.tmp`;
274 const methodByOperation = {
275 check: "exists",
276 read: "readFileString",
277 write: "writeFileString",
278 } as const;
279
280 for (const operation of ["check", "read", "write"] as const) {
281 const writeAttempts: string[] = [];
282 const cause = PlatformError.systemError({
283 _tag: "PermissionDenied",
284 module: "FileSystem",
285 method: methodByOperation[operation],
286 description: "permission denied",
287 pathOrDescriptor: environmentIdPath,
288 });
289 const failingFileSystemLayer = FileSystem.layerNoop({
290 exists: () =>
291 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
292 readFileString: () => Effect.fail(cause),
293 makeTempFileScoped: () => Effect.succeed(tempPath),
294 writeFileString: (path) => {
295 writeAttempts.push(path);
296 return Effect.fail(cause);
297 },
298 });
299
300 const error = yield* Effect.gen(function* () {
301 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
302 return yield* serverEnvironment.getDescriptor;
303 }).pipe(
304 Effect.provide(
305 ServerEnvironment.layer.pipe(
306 Layer.provide(emptySecretStoreLayer),
307 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
308 ),
309 ),
310 Effect.flip,
311 );
312
313 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
314 if (!isServerEnvironmentIdPersistenceError(error)) {
315 throw error;
316 }
317 expect(error.operation).toBe(operation);
318 expect(error.environmentIdPath).toBe(environmentIdPath);
319 expect(error.cause).toBe(cause);
320 expect(error.message).toBe(
321 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
322 );
323 expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
324 }
325 }),
326 );
327});