Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as PlatformError from "effect/PlatformError";
8import * as Schema from "effect/Schema";
9
10import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
11import {
12 PUBLISH_AGENT_ACTIVITY_SECRET,
13 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
14 RELAY_URL_SECRET,
15} from "../cloud/config.ts";
16import * as ServerConfig from "../config.ts";
17import * as ServerEnvironment from "./ServerEnvironment.ts";
18
19const isServerEnvironmentIdPersistenceError = Schema.is(
20 ServerEnvironment.ServerEnvironmentIdPersistenceError,
21);
22
23const makeServerEnvironmentLayer = (baseDir: string) =>
24 ServerEnvironment.layer.pipe(
25 Layer.provide(ServerSecretStore.layer),
26 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
27 );
28
29const emptySecretStoreLayer = Layer.succeed(
30 ServerSecretStore.ServerSecretStore,
31 ServerSecretStore.ServerSecretStore.of({
32 get: () => Effect.succeed(Option.none()),
33 set: () => Effect.void,
34 create: () => Effect.void,
35 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
36 remove: () => Effect.void,
37 }),
38);
39
40const makeServerConfig = Effect.fn(function* (baseDir: string) {
41 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
42
43 return {
44 ...derivedPaths,
45 logLevel: "Error",
46 traceMinLevel: "Info",
47 traceTimingEnabled: true,
48 traceBatchWindowMs: 200,
49 traceMaxBytes: 10 * 1024 * 1024,
50 traceMaxFiles: 10,
51 otlpTracesUrl: undefined,
52 otlpMetricsUrl: undefined,
53 otlpExportIntervalMs: 10_000,
54 otlpServiceName: "t3-server",
55 cwd: process.cwd(),
56 baseDir,
57 mode: "web",
58 autoBootstrapProjectFromCwd: false,
59 logWebSocketEvents: false,
60 tailscaleServeEnabled: false,
61 tailscaleServePort: 443,
62 port: 0,
63 host: undefined,
64 desktopBootstrapToken: undefined,
65 staticDir: undefined,
66 devUrl: undefined,
67 devAllowedOrigins: [],
68 noBrowser: false,
69 startupPresentation: "browser",
70 } satisfies ServerConfig.ServerConfig["Service"];
71});
72
73it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
74 it.effect("persists the environment id across service restarts", () =>
75 Effect.gen(function* () {
76 const fileSystem = yield* FileSystem.FileSystem;
77 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
78 prefix: "t3-server-environment-test-",
79 });
80
81 const first = yield* Effect.gen(function* () {
82 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
83 return yield* serverEnvironment.getDescriptor;
84 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
85 const second = yield* Effect.gen(function* () {
86 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
87 return yield* serverEnvironment.getDescriptor;
88 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
89
90 expect(first.environmentId).toBe(second.environmentId);
91 expect(second.capabilities.repositoryIdentity).toBe(true);
92 expect(second.capabilities.connectionProbe).toBe(true);
93 expect(second.capabilities.attachmentUploads).toBe(true);
94 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
95 expect(second.capabilities.pullRequests).toBe(true);
96 expect(second.capabilities.threadTitleRegeneration).toBe(true);
97 expect(second.capabilities.threadPullRequestLinking).toBe(true);
98 expect(second.capabilities.agentActivityPublishing).toBe(false);
99 }),
100 );
101
102 it.effect("reports agent activity publishing from the current secret state", () =>
103 Effect.gen(function* () {
104 const fileSystem = yield* FileSystem.FileSystem;
105 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
106 prefix: "t3-server-environment-publish-test-",
107 });
108 const testLayer = Layer.mergeAll(
109 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
110 ServerSecretStore.layer,
111 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
112
113 yield* Effect.gen(function* () {
114 const secrets = yield* ServerSecretStore.ServerSecretStore;
115 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
116 const encode = (value: string) => new TextEncoder().encode(value);
117
118 const unlinked = yield* serverEnvironment.getDescriptor;
119 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
120
121 // The opt-in alone is not enough: without relay link credentials no
122 // publish would leave this environment.
123 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
124 const withoutLink = yield* serverEnvironment.getDescriptor;
125 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
126
127 // Empty credentials are as unconfigured as missing ones: the
128 // publisher's truthiness gate skips them, so the capability must not
129 // advertise publishing.
130 yield* secrets.set(RELAY_URL_SECRET, encode(""));
131 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
132 const emptyUrl = yield* serverEnvironment.getDescriptor;
133 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
134
135 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
136 const linked = yield* serverEnvironment.getDescriptor;
137 expect(linked.capabilities.agentActivityPublishing).toBe(true);
138
139 // The toggle changes at runtime, so the same service instance must
140 // reflect a flip without a restart.
141 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
142 const disabled = yield* serverEnvironment.getDescriptor;
143 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
144 }).pipe(Effect.provide(testLayer));
145 }),
146 );
147
148 it.effect("structures persisted environment id filesystem failures", () =>
149 Effect.gen(function* () {
150 const fileSystem = yield* FileSystem.FileSystem;
151 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
152 prefix: "t3-server-environment-error-test-",
153 });
154 const serverConfig = yield* makeServerConfig(baseDir);
155 const environmentIdPath = serverConfig.environmentIdPath;
156 const methodByOperation = {
157 check: "exists",
158 read: "readFileString",
159 write: "writeFileString",
160 } as const;
161
162 for (const operation of ["check", "read", "write"] as const) {
163 const writeAttempts: string[] = [];
164 const cause = PlatformError.systemError({
165 _tag: "PermissionDenied",
166 module: "FileSystem",
167 method: methodByOperation[operation],
168 description: "permission denied",
169 pathOrDescriptor: environmentIdPath,
170 });
171 const failingFileSystemLayer = FileSystem.layerNoop({
172 exists: () =>
173 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
174 readFileString: () => Effect.fail(cause),
175 writeFileString: (path) => {
176 writeAttempts.push(path);
177 return Effect.fail(cause);
178 },
179 });
180
181 const error = yield* Effect.gen(function* () {
182 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
183 return yield* serverEnvironment.getDescriptor;
184 }).pipe(
185 Effect.provide(
186 ServerEnvironment.layer.pipe(
187 Layer.provide(emptySecretStoreLayer),
188 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
189 ),
190 ),
191 Effect.flip,
192 );
193
194 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
195 if (!isServerEnvironmentIdPersistenceError(error)) {
196 throw error;
197 }
198 expect(error.operation).toBe(operation);
199 expect(error.environmentIdPath).toBe(environmentIdPath);
200 expect(error.cause).toBe(cause);
201 expect(error.message).toBe(
202 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
203 );
204 expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
205 }
206 }),
207 );
208});