Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
4import { expect, it } from "@effect/vitest";
5import * as SecureRandom from "effect/crypto/SecureRandom";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10
11import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
14
15import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16import {
17 PUBLISH_AGENT_ACTIVITY_SECRET,
18 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
19 RELAY_URL_SECRET,
20} from "../cloud/config.ts";
21import * as ServerConfig from "../config.ts";
22import * as ServerEnvironment from "./ServerEnvironment.ts";
23
24const layerServerEnvironment = (baseDir: string) =>
25 ServerEnvironment.layer.pipe(
26 Layer.provide(ServerSecretStore.layer),
27 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
28 );
29
30const layerEmptySecretStore = Layer.succeed(
31 ServerSecretStore.ServerSecretStore,
32 ServerSecretStore.ServerSecretStore.of({
33 get: () => Effect.succeedNone,
34 set: () => Effect.void,
35 create: () => Effect.void,
36 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
37 remove: () => Effect.void,
38 }),
39);
40
41const makeServerConfig = Effect.fn(function* (baseDir: string) {
42 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
43
44 return {
45 ...derivedPaths,
46 logLevel: "Error",
47 traceMinLevel: "Info",
48 traceTimingEnabled: true,
49 traceBatchWindowMs: 200,
50 traceMaxBytes: 10 * 1024 * 1024,
51 traceMaxFiles: 10,
52 otlpTracesUrl: undefined,
53 otlpMetricsUrl: undefined,
54 otlpLogsUrl: undefined,
55 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
56 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
57 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
58 otelEnvironment: OtelEnvironment.none,
59 cwd: process.cwd(),
60 baseDir,
61 mode: "web",
62 autoBootstrapProjectFromCwd: false,
63 logWebSocketEvents: false,
64 tailscaleServeEnabled: false,
65 tailscaleServePort: 443,
66 port: 0,
67 host: undefined,
68 desktopBootstrapToken: undefined,
69 staticDir: undefined,
70 devUrl: undefined,
71 devAllowedOrigins: [],
72 noBrowser: false,
73 startupPresentation: "browser",
74 } satisfies ServerConfig.ServerConfig["Service"];
75});
76
77it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmentLive", (it) => {
78 it.effect("publishes proven install ownership only for manually updated servers", () =>
79 Effect.gen(function* () {
80 const fs = yield* FileSystem.FileSystem;
81 const baseDir = yield* fs.makeTempDirectoryScoped();
82 const prefix = `${baseDir}/node`;
83 const entry = `${prefix}/lib/node_modules/t3/dist/bin.mjs`;
84 yield* fs.makeDirectory(`${prefix}/lib/node_modules/t3/dist`, { recursive: true });
85 yield* fs.makeDirectory(`${prefix}/bin`, { recursive: true });
86 yield* fs.writeFileString(entry, "");
87 yield* fs.writeFileString(
88 `${prefix}/lib/node_modules/t3/package.json`,
89 '{"name":"t3","version":"0.0.45","bin":{"t3":"./dist/bin.mjs"}}',
90 );
91 yield* fs.symlink(entry, `${prefix}/bin/t3`);
92 const config = yield* makeServerConfig(baseDir);
93 yield* fs.makeDirectory(config.stateDir, { recursive: true });
94 for (const mode of ["web", "desktop"] as const) {
95 const descriptor = yield* Effect.gen(function* () {
96 const environment = yield* ServerEnvironment.ServerEnvironment;
97 return yield* environment.getDescriptor;
98 }).pipe(
99 Effect.provide(
100 ServerEnvironment.layer.pipe(
101 Layer.provide(layerEmptySecretStore),
102 Layer.provide(ServerConfig.layer({ ...config, mode })),
103 ),
104 ),
105 Effect.provideService(HostProcess.Arguments, ["node", entry]),
106 Effect.provideService(HostProcess.IsExecutable, false),
107 Effect.provideService(HostProcess.Platform, "linux"),
108 Effect.provideService(HostProcess.Environment, {}),
109 );
110 expect(descriptor.capabilities.serverInstallation).toEqual(
111 mode === "web" ? { kind: "npm-global", prefix } : undefined,
112 );
113 expect(descriptor.capabilities.serverSelfUpdate).toBe(
114 mode === "web" ? undefined : "desktop-managed",
115 );
116 expect(descriptor.capabilities).toMatchObject({
117 settledWorktreeCleanup: true,
118 storageCleanupRun: true,
119 projectWorktreeCleanup: true,
120 worktreesDirectory: true,
121 threadAutoSettlementScope: true,
122 });
123 }
124 }),
125 );
126 it.effect.each([
127 { platform: "darwin", architecture: "arm64", supported: true },
128 { platform: "linux", architecture: "x64", supported: true },
129 { platform: "linux", architecture: "x64", libc: "musl", supported: false },
130 { platform: "win32", architecture: "arm64", supported: false },
131 { platform: "linux", architecture: "arm", supported: false },
132 ] as const)("advertises voice transcription on $platform-$architecture: $supported", (host) =>
133 Effect.gen(function* () {
134 const fileSystem = yield* FileSystem.FileSystem;
135 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
136 prefix: "t3-server-environment-speech-test-",
137 });
138 const descriptor = yield* Effect.gen(function* () {
139 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
140 return yield* serverEnvironment.getDescriptor;
141 }).pipe(
142 Effect.provide(layerServerEnvironment(baseDir)),
143 Effect.provideService(HostProcess.Platform, host.platform),
144 Effect.provideService(HostProcess.Architecture, host.architecture),
145 Effect.provideService(HostProcess.LinuxLibc, "libc" in host ? host.libc : "gnu"),
146 );
147 expect(descriptor.capabilities.voiceTranscription).toBe(host.supported);
148 }),
149 );
150 it.effect.each([
151 { name: "missing", content: undefined },
152 { name: "empty", content: "" },
153 { name: "whitespace-only", content: " \t\n" },
154 ])("concurrent initializers recover a $name environment id file", ({ content }) =>
155 Effect.gen(function* () {
156 const fileSystem = yield* FileSystem.FileSystem;
157 const random = yield* SecureRandom.SecureRandom;
158 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
159 prefix: "t3-server-environment-concurrent-test-",
160 });
161 const serverConfig = yield* makeServerConfig(baseDir);
162 yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
163 if (content !== undefined) {
164 yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
165 }
166 const bothGenerated = yield* Deferred.make<void>();
167 const bothReadEmpty = yield* Deferred.make<void>();
168 const firstInitialized = yield* Deferred.make<void>();
169 let remaining = 2;
170 let emptyReads = 0;
171 const readIdentity = Effect.gen(function* () {
172 const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
173 return yield* identity.getEnvironmentId;
174 }).pipe(
175 Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
176 Effect.provide(Layer.fresh(ServerEnvironment.layerIdentity)),
177 Effect.provideService(ServerConfig.ServerConfig, serverConfig),
178 Effect.provideService(FileSystem.FileSystem, {
179 ...fileSystem,
180 readFileString: (path) =>
181 fileSystem.readFileString(path).pipe(
182 Effect.tap(
183 Effect.fn(function* (value) {
184 if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
185 return;
186 }
187 if (++emptyReads === 2) {
188 yield* Deferred.succeed(bothReadEmpty, undefined);
189 yield* Deferred.await(firstInitialized);
190 } else {
191 yield* Deferred.await(bothReadEmpty);
192 }
193 }),
194 ),
195 ),
196 }),
197 Effect.provideService(SecureRandom.SecureRandom, {
198 ...random,
199 uuidV4: (() =>
200 Effect.gen(function* () {
201 const id = yield* random.uuidV4();
202 if (--remaining === 0) {
203 yield* Deferred.succeed(bothGenerated, undefined);
204 }
205 yield* Deferred.await(bothGenerated);
206 return id;
207 })) as SecureRandom.SecureRandom["Service"]["uuidV4"],
208 }),
209 );
210
211 const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
212 concurrency: "unbounded",
213 });
214 const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
215
216 expect(first).toBe(second);
217 expect(persisted.trim()).toBe(first);
218 }),
219 );
220
221 it.effect("persists the environment id across service restarts", () =>
222 Effect.gen(function* () {
223 const fileSystem = yield* FileSystem.FileSystem;
224 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
225 prefix: "t3-server-environment-test-",
226 });
227
228 const first = yield* Effect.gen(function* () {
229 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
230 return yield* serverEnvironment.getDescriptor;
231 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
232 const second = yield* Effect.gen(function* () {
233 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
234 return yield* serverEnvironment.getDescriptor;
235 }).pipe(Effect.provide(layerServerEnvironment(baseDir)));
236
237 expect(first.environmentId).toBe(second.environmentId);
238 expect(first.orchestrationProtocolVersion).toBe(ORCHESTRATION_PROTOCOL_VERSION);
239 expect(second.capabilities.repositoryIdentity).toBe(true);
240 expect(second.capabilities.connectionProbe).toBe(true);
241 expect(second.capabilities.attachmentUploads).toBe(true);
242 expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
243 expect(second.capabilities.pullRequests).toBe(true);
244 expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
245 expect(second.capabilities.usagePriceOverrides).toBe(true);
246 expect(second.capabilities.threadActiveReorder).toBe(true);
247 expect(second.capabilities.threadTitleRegeneration).toBe(true);
248 expect(second.capabilities.threadPullRequests).toBe(true);
249 expect(second.capabilities.threadPullRequestLinking).toBe(true);
250 expect(second.capabilities.serverResolvedCommandContext).toBe(true);
251 expect(second.capabilities.projectProviderInstanceOverrides).toBe(true);
252 expect(second.capabilities.agentActivityPublishing).toBe(false);
253 }),
254 );
255
256 it.effect("reports agent activity publishing from the current secret state", () =>
257 Effect.gen(function* () {
258 const fileSystem = yield* FileSystem.FileSystem;
259 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
260 prefix: "t3-server-environment-publish-test-",
261 });
262 const layerTest = Layer.mergeAll(
263 ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
264 ServerSecretStore.layer,
265 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
266
267 yield* Effect.gen(function* () {
268 const secrets = yield* ServerSecretStore.ServerSecretStore;
269 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
270 const encode = (value: string) => new TextEncoder().encode(value);
271
272 const unlinked = yield* serverEnvironment.getDescriptor;
273 expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
274
275 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
276 const withoutLink = yield* serverEnvironment.getDescriptor;
277 expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
278
279 yield* secrets.set(RELAY_URL_SECRET, encode(""));
280 yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
281 const emptyUrl = yield* serverEnvironment.getDescriptor;
282 expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
283
284 yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
285 const linked = yield* serverEnvironment.getDescriptor;
286 expect(linked.capabilities.agentActivityPublishing).toBe(true);
287
288 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
289 const disabled = yield* serverEnvironment.getDescriptor;
290 expect(disabled.capabilities.agentActivityPublishing).toBe(false);
291 }).pipe(Effect.provide(layerTest));
292 }),
293 );
294});