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.pullRequests).toBe(true);
95 expect(second.capabilities.threadTitleRegeneration).toBe(true);
96 expect(second.capabilities.agentActivityPublishing).toBe(false);
97 }),
98 );
99
100 it.effect("reports agent activity publishing from the current secret state", () =>
101 Effect.gen(function* () {
102 const fileSystem = yield* FileSystem.FileSystem;
103 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
104 prefix: "t3-server-environment-publish-test-",
105 });
106 const testLayer = Layer.mergeAll(
107 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
108 ServerSecretStore.layer,
109 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
110
111 yield* Effect.gen(function* () {
112 const secrets = yield* ServerSecretStore.ServerSecretStore;
113 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
114 const encode = (value: string) => new TextEncoder().encode(value);
115
116 const unlinked = yield* serverEnvironment.getDescriptor;
117 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
118
119 // The opt-in alone is not enough: without relay link credentials no
120 // publish would leave this environment.
121 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
122 const withoutLink = yield* serverEnvironment.getDescriptor;
123 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
124
125 // Empty credentials are as unconfigured as missing ones: the
126 // publisher's truthiness gate skips them, so the capability must not
127 // advertise publishing.
128 yield* secrets.set(RELAY_URL_SECRET, encode(""));
129 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
130 const emptyUrl = yield* serverEnvironment.getDescriptor;
131 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
132
133 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
134 const linked = yield* serverEnvironment.getDescriptor;
135 expect(linked.capabilities.agentActivityPublishing).toBe(true);
136
137 // The toggle changes at runtime, so the same service instance must
138 // reflect a flip without a restart.
139 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
140 const disabled = yield* serverEnvironment.getDescriptor;
141 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
142 }).pipe(Effect.provide(testLayer));
143 }),
144 );
145
146 it.effect("structures persisted environment id filesystem failures", () =>
147 Effect.gen(function* () {
148 const fileSystem = yield* FileSystem.FileSystem;
149 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
150 prefix: "t3-server-environment-error-test-",
151 });
152 const serverConfig = yield* makeServerConfig(baseDir);
153 const environmentIdPath = serverConfig.environmentIdPath;
154 const methodByOperation = {
155 check: "exists",
156 read: "readFileString",
157 write: "writeFileString",
158 } as const;
159
160 for (const operation of ["check", "read", "write"] as const) {
161 const writeAttempts: string[] = [];
162 const cause = PlatformError.systemError({
163 _tag: "PermissionDenied",
164 module: "FileSystem",
165 method: methodByOperation[operation],
166 description: "permission denied",
167 pathOrDescriptor: environmentIdPath,
168 });
169 const failingFileSystemLayer = FileSystem.layerNoop({
170 exists: () =>
171 operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
172 readFileString: () => Effect.fail(cause),
173 writeFileString: (path) => {
174 writeAttempts.push(path);
175 return Effect.fail(cause);
176 },
177 });
178
179 const error = yield* Effect.gen(function* () {
180 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
181 return yield* serverEnvironment.getDescriptor;
182 }).pipe(
183 Effect.provide(
184 ServerEnvironment.layer.pipe(
185 Layer.provide(emptySecretStoreLayer),
186 Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
187 ),
188 ),
189 Effect.flip,
190 );
191
192 expect(isServerEnvironmentIdPersistenceError(error)).toBe(true);
193 if (!isServerEnvironmentIdPersistenceError(error)) {
194 throw error;
195 }
196 expect(error.operation).toBe(operation);
197 expect(error.environmentIdPath).toBe(environmentIdPath);
198 expect(error.cause).toBe(cause);
199 expect(error.message).toBe(
200 `Server environment ID ${operation} failed at '${environmentIdPath}'.`,
201 );
202 expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
203 }
204 }),
205 );
206});