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