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