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