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