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