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