@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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