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

serverRuntimeStartup.test.ts

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