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