Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverRuntimeStartup.test.ts

372 lines14.4 KB

1import { assert, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import {
4 DEFAULT_SERVER_SETTINGS,
5 ProjectId,
6 ProviderInstanceId,
7 ProviderDriverKind,
8 CommandId,
9 EnvironmentId,
10 type ServerLifecycleStreamEvent,
11} from "@t3tools/contracts";
12import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
13import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
14import { HttpServer } from "effect/http";
15import * as NetAddress from "effect/net/NetAddress";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Exit from "effect/Exit";
20import * as Fiber from "effect/Fiber";
21import * as Ref from "effect/Ref";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24​
25import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
26​
27import * as ServerConfig from "./config.ts";
28import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
29import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
30import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
31import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
32import * as Keybindings from "./keybindings.ts";
33import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
34import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
35import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
36import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
37import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
38import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
39import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
40import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
41import * as ExternalLauncher from "./process/externalLauncher.ts";
42import * as ProjectService from "./project/ProjectService.ts";
43import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
44import { ServerActivation } from "./serverActivation.ts";
45import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
46import * as ServerSettings from "./serverSettings.ts";
47import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
48import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
49​
50it.effect.each([
51 "disabled-codex",
52 "disabled-default",
53 "launch-failure",
54 "project-failure",
55] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) =>
56 Effect.scoped(
57 Effect.gen(function* () {
58 const projectId = ProjectId.make("bootstrap-project");
59 const instanceId = ProviderInstanceId.make(
60 scenario === "disabled-default" ? "custom" : "codex",
61 );
62 const events: ServerLifecycleStreamEvent[] = [];
63 const recovery = {
64 terminalizedRuns: 0,
65 stoppedSessions: 0,
66 closedRequests: 0,
67 retiredEffects: 0,
68 requeuedEffects: 0,
69 };
70 const imports = { importedThreadCount: 0, importedMessageCount: 0 };
71 const dependencies = Layer.mergeAll(
72 NodeCrypto.layer,
73 Path.layer,
74 Layer.mock(ServerConfig.ServerConfig)({
75 ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe(
76 Effect.provide(Path.layer),
77 )),
78 baseDir: "/bootstrap-project",
79 logLevel: "Error",
80 traceMinLevel: "Info",
81 traceTimingEnabled: false,
82 traceBatchWindowMs: 200,
83 traceMaxBytes: 1024,
84 traceMaxFiles: 1,
85 otlpTracesUrl: undefined,
86 otlpMetricsUrl: undefined,
87 otlpLogsUrl: undefined,
88 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
89 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
90 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
91 otelEnvironment: OtelEnvironment.none,
92 staticDir: undefined,
93 devAllowedOrigins: [],
94 desktopBootstrapToken: undefined,
95 logWebSocketEvents: false,
96 tailscaleServeEnabled: false,
97 tailscaleServePort: 443,
98 mode: "web",
99 cwd: "/bootstrap-project",
100 host: "localhost",
101 port: 3773,
102 devUrl: undefined,
103 noBrowser: true,
104 startupPresentation: "browser",
105 autoBootstrapProjectFromCwd: true,
106 }),
107 Layer.mock(Keybindings.Keybindings)({ start: Effect.void }),
108 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
109 pendingThreadCount: Effect.succeed(0),
110 reconcileShells: Effect.succeed(imports),
111 importPendingTranscripts: Effect.succeed(imports),
112 }),
113 Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({
114 recover: Effect.succeed(recovery),
115 prepareForShutdown: Effect.void,
116 reconcile: () => Effect.succeed(recovery),
117 }),
118 Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }),
119 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }),
120 Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }),
121 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.never }),
122 Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({
123 publish: (event) =>
124 Effect.sync(() => {
125 const published = { ...event, sequence: events.length + 1 };
126 events.push(published);
127 return published;
128 }),
129 }),
130 Layer.mock(ServerSettings.ServerSettingsService)({
131 start: Effect.void,
132 getSettings: Effect.succeed({
133 ...DEFAULT_SERVER_SETTINGS,
134 defaultModelSelection:
135 scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null,
136 providerInstances: {
137 [instanceId]: {
138 driver: ProviderDriverKind.make("codex"),
139 enabled: false,
140 config: {},
141 },
142 },
143 }),
144 }),
145 Layer.mock(ServerEnvironment.ServerEnvironment)({
146 getDescriptor: Effect.succeed({
147 environmentId: EnvironmentId.make("bootstrap-environment"),
148 label: "Test environment",
149 platform: { os: "linux", arch: "x64" },
150 serverVersion: "0.0.0-test",
151 capabilities: { repositoryIdentity: true },
152 }),
153 }),
154 Layer.mock(ProjectStore.ProjectStoreV2)({}),
155 Layer.mock(ProjectService.ProjectService)({
156 bootstrap: () =>
157 scenario === "project-failure"
158 ? Effect.die("project bootstrap failed")
159 : Effect.succeed({
160 created: true,
161 project: {
162 id: projectId,
163 title: "Project",
164 workspaceRoot: "/bootstrap-project",
165 repositoryIdentity: null,
166 faviconPath: null,
167 scripts: [],
168 createdAt: "2026-01-01T00:00:00Z",
169 updatedAt: "2026-01-01T00:00:00Z",
170 deletedAt: null,
171 defaultModelSelection:
172 scenario === "disabled-default"
173 ? { instanceId, model: "custom-model" }
174 : null,
175 },
176 }),
177 }),
178 Layer.mock(ThreadManagement.ThreadManagementService)({
179 getShellSnapshot: () =>
180 Effect.succeed({
181 threads: [],
182 archivedThreads: [],
183 schemaVersion: 1,
184 snapshotSequence: 0,
185 }),
186 }),
187 Layer.mock(ThreadLaunch.ThreadLaunchService)({
188 launch: (input) => {
189 assert.equal(input.modelSelection.instanceId, instanceId);
190 return scenario === "launch-failure"
191 ? Effect.fail(
192 new ThreadLaunch.ThreadLaunchError({
193 operation: "create-thread",
194 commandId: CommandId.make("bootstrap-command"),
195 projectId,
196 cause: "test launch failure",
197 }),
198 )
199 : Effect.fail(
200 new ThreadManagement.ThreadManagementProviderInstanceDisabledError({
201 projectId,
202 instanceId,
203 }),
204 );
205 },
206 }),
207 Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
208 managed: false,
209 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
210 prepareTrial: Effect.succeed(undefined),
211 }),
212 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
213 Layer.mock(AnalyticsService.AnalyticsService)({}),
214 // No provider logins or Connect link, so startup records no owners.
215 FileSystem.layerNoop({}),
216 Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
217 Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
218 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
219 Layer.mock(HttpServer.HttpServer)({
220 address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
221 }),
222 );
223 yield* Effect.gen(function* () {
224 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
225 yield* startup.markHttpListening;
226 const ready = yield* Effect.exit(startup.awaitCommandReady);
227 assert.equal(Exit.isSuccess(ready), scenario !== "project-failure");
228 const welcome = events.find((event) => event.type === "welcome");
229 if (scenario === "project-failure") {
230 assert.isUndefined(welcome);
231 } else {
232 assert.isDefined(welcome);
233 if (welcome?.type === "welcome") {
234 assert.equal(welcome.payload.bootstrapProjectId, projectId);
235 assert.isUndefined(welcome.payload.bootstrapThreadId);
236 }
237 }
238 }).pipe(
239 Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))),
240 Effect.provideService(ServerActivation, Effect.never),
241 );
242 }),
243 ),
244);
245​
246it.effect("interrupts the effect worker when awareness relay startup fails", () =>
247 Effect.scoped(
248 Effect.gen(function* () {
249 const workerInterrupted = yield* Ref.make(false);
250 const workerFiberRef = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
251​
252 const exit = yield* ServerRuntimeStartup.startEffectWorkerWithRelay({
253 runWorker: Effect.never.pipe(Effect.ensuring(Ref.set(workerInterrupted, true))),
254 startRelay: Effect.yieldNow.pipe(
255 Effect.andThen(Effect.die("awareness relay startup failed")),
256 ),
257 workerFiberRef,
258 }).pipe(Effect.exit);
259​
260 assert.isTrue(Exit.isFailure(exit));
261 assert.isTrue(yield* Ref.get(workerInterrupted));
262 assert.isNull(yield* Ref.get(workerFiberRef));
263 }),
264 ),
265);
266​
267it.effect("queues commands until startup signals readiness", () =>
268 Effect.scoped(
269 Effect.gen(function* () {
270 const gate = yield* ServerRuntimeStartup.makeCommandGate;
271 const count = yield* Ref.make(0);
272 const queued = yield* gate
273 .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1))
274 .pipe(Effect.forkScoped);
275​
276 yield* Effect.yieldNow;
277 assert.equal(yield* Ref.get(count), 0);
278 yield* gate.signalCommandReady;
279 assert.equal(yield* Fiber.join(queued), 1);
280 }),
281 ),
282);
283​
284it.effect("enqueueCommand fails queued work when readiness fails", () =>
285 Effect.scoped(
286 Effect.gen(function* () {
287 const commandGate = yield* ServerRuntimeStartup.makeCommandGate;
288 const failure = yield* Deferred.make<void, never>();
289​
290 const queuedCommandFiber = yield* commandGate
291 .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run")))
292 .pipe(Effect.forkScoped);
293​
294 yield* commandGate.failCommandReady(
295 new ServerRuntimeStartup.ServerRuntimeStartupError({
296 mode: "web",
297 host: "127.0.0.1",
298 port: 3773,
299 cause: new Error("test startup failure"),
300 }),
301 );
302​
303 const error = yield* Effect.flip(Fiber.join(queuedCommandFiber));
304 assert.equal(error.message, "Server runtime startup failed before command readiness.");
305 }),
306 ),
307);
308​
309it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () =>
310 Effect.gen(function* () {
311 const pulled: string[] = [];
312 const git = {
313 statusDetails: (cwd: string) =>
314 Effect.succeed({
315 isRepo: true,
316 isDefaultBranch: cwd !== "/feature",
317 hasUpstream: true,
318 hasWorkingTreeChanges: cwd === "/dirty",
319 aheadCount: cwd === "/ahead" ? 1 : 0,
320 behindCount: cwd === "/current" ? 0 : 1,
321 } as never),
322 pullCurrentBranch: (cwd: string) =>
323 Effect.sync(() => {
324 pulled.push(cwd);
325 return {
326 status: "pulled" as const,
327 refName: "main",
328 upstreamRef: "origin/main",
329 };
330 }),
331 } as unknown as GitVcsDriver.GitVcsDriver["Service"];
332 const project = (workspaceRoot: string) =>
333 ({ id: ProjectId.make(workspaceRoot), workspaceRoot }) as never;
334 const overrides = (entries: Record<string, boolean>) => ({
335 ...DEFAULT_SERVER_SETTINGS,
336 projectSettingsOverrides: Object.fromEntries(
337 Object.entries(entries).map(([root, defaultAutoPull]) => [
338 ProjectId.make(root),
339 { defaultAutoPull },
340 ]),
341 ),
342 });
343​
344 yield* ServerRuntimeStartup.autoPullProjects(
345 [
346 project("/clean"),
347 project("/current"),
348 project("/dirty"),
349 project("/ahead"),
350 project("/feature"),
351 project("/disabled"),
352 ],
353 overrides({
354 "/clean": true,
355 "/current": true,
356 "/dirty": true,
357 "/ahead": true,
358 "/feature": true,
359 "/disabled": false,
360 }),
361 ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
362​
363 assert.deepStrictEqual(pulled, ["/clean"]);
364​
365 pulled.length = 0;
366 yield* ServerRuntimeStartup.autoPullProjects(
367 [project("/inherited"), project("/opted-out"), project("/dirty")],
368 { ...overrides({ "/opted-out": false }), defaultAutoPull: true },
369 ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
370 assert.deepStrictEqual(pulled, ["/inherited"]);
371 }),
372);