Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { DEFAULT_MODEL, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
3import { assert, it } from "@effect/vitest";
4import * as Crypto from "effect/Crypto";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Option from "effect/Option";
9import * as PlatformError from "effect/PlatformError";
10import * as Ref from "effect/Ref";
11import * as Stream from "effect/Stream";
12
13import * as ServerConfig from "./config.ts";
14import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
15import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
16import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
17import * as ServerSettings from "./serverSettings.ts";
18import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
19
20it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () =>
21 Effect.gen(function* () {
22 const pulled: string[] = [];
23 const git = {
24 statusDetails: (cwd: string) =>
25 Effect.succeed({
26 isRepo: true,
27 isDefaultBranch: cwd !== "/feature",
28 hasUpstream: true,
29 hasWorkingTreeChanges: cwd === "/dirty",
30 aheadCount: cwd === "/ahead" ? 1 : 0,
31 behindCount: cwd === "/current" ? 0 : 1,
32 } as never),
33 pullCurrentBranch: (cwd: string) =>
34 Effect.sync(() => {
35 pulled.push(cwd);
36 return {
37 status: "pulled" as const,
38 refName: "main",
39 upstreamRef: "origin/main",
40 };
41 }),
42 } as unknown as GitVcsDriver.GitVcsDriver["Service"];
43 const project = (workspaceRoot: string, autoPull = true) =>
44 ({ id: ProjectId.make(workspaceRoot), workspaceRoot, autoPull }) as never;
45
46 yield* ServerRuntimeStartup.autoPullProjects([
47 project("/clean"),
48 project("/current"),
49 project("/dirty"),
50 project("/ahead"),
51 project("/feature"),
52 project("/disabled", false),
53 ]).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
54
55 assert.deepStrictEqual(pulled, ["/clean"]);
56
57 pulled.length = 0;
58 yield* ServerRuntimeStartup.autoPullProjects(
59 [project("/inherited", false), project("/opted-out"), project("/dirty", false)],
60 {
61 defaultAutoPull: true,
62 projectAutoPullOverrides: { [ProjectId.make("/opted-out")]: false },
63 },
64 ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
65 assert.deepStrictEqual(pulled, ["/inherited"]);
66 }),
67);
68
69it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
70 Effect.scoped(
71 Effect.gen(function* () {
72 const executionCount = yield* Ref.make(0);
73 const commandGate = yield* ServerRuntimeStartup.makeCommandGate;
74
75 const queuedCommandFiber = yield* commandGate
76 .enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1))
77 .pipe(Effect.forkScoped);
78
79 yield* Effect.yieldNow;
80 assert.equal(yield* Ref.get(executionCount), 0);
81
82 yield* commandGate.signalCommandReady;
83
84 const result = yield* Fiber.join(queuedCommandFiber);
85 assert.equal(result, 1);
86 assert.equal(yield* Ref.get(executionCount), 1);
87 }),
88 ),
89);
90
91it.effect("enqueueCommand fails queued work when readiness fails", () =>
92 Effect.scoped(
93 Effect.gen(function* () {
94 const commandGate = yield* ServerRuntimeStartup.makeCommandGate;
95 const failure = yield* Deferred.make<void, never>();
96
97 const queuedCommandFiber = yield* commandGate
98 .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run")))
99 .pipe(Effect.forkScoped);
100
101 yield* commandGate.failCommandReady(
102 new ServerRuntimeStartup.ServerRuntimeStartupError({
103 mode: "web",
104 host: "127.0.0.1",
105 port: 3773,
106 cause: new Error("test startup failure"),
107 }),
108 );
109
110 const error = yield* Effect.flip(Fiber.join(queuedCommandFiber));
111 assert.equal(error.message, "Server runtime startup failed before command readiness.");
112 }),
113 ),
114);
115
116it.effect("resolveWelcomeBase derives cwd and project name from server config", () =>
117 Effect.gen(function* () {
118 const welcome = yield* ServerRuntimeStartup.resolveWelcomeBase.pipe(
119 Effect.provideService(ServerConfig.ServerConfig, {
120 cwd: "/tmp/startup-project",
121 } as never),
122 );
123
124 assert.deepStrictEqual(welcome, {
125 cwd: "/tmp/startup-project",
126 projectName: "startup-project",
127 });
128 }),
129);
130
131it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and thread ids", () => {
132 const bootstrapProjectId = ProjectId.make("project-startup-bootstrap");
133 const bootstrapThreadId = ThreadId.make("thread-startup-bootstrap");
134
135 return Effect.gen(function* () {
136 const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
137 const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
138 Effect.provide(ServerSettings.layerTest()),
139 Effect.provideService(ServerConfig.ServerConfig, {
140 cwd: "/tmp/startup-project",
141 autoBootstrapProjectFromCwd: true,
142 } as never),
143 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
144 getUserInputActivity: () => Effect.die("unused"),
145 getCommandReadModel: () => Effect.die("unused"),
146 getSnapshot: () => Effect.die("unused"),
147 getShellSnapshot: () => Effect.die("unused"),
148 getArchivedShellSnapshot: () => Effect.die("unused"),
149 getSnapshotSequence: () => Effect.die("unused"),
150 getCounts: () => Effect.die("unused"),
151 getEventReplayStats: () => Effect.die("unused"),
152 getActiveProjectByWorkspaceRoot: () =>
153 Effect.succeed(
154 Option.some({
155 id: bootstrapProjectId,
156 title: "Startup Project",
157 workspaceRoot: "/tmp/startup-project",
158 defaultModelSelection: {
159 instanceId: ProviderInstanceId.make("codex"),
160 model: DEFAULT_MODEL,
161 },
162 scripts: [],
163 createdAt: "2026-01-01T00:00:00.000Z",
164 updatedAt: "2026-01-01T00:00:00.000Z",
165 deletedAt: null,
166 }),
167 ),
168 getProjectShellById: () => Effect.die("unused"),
169 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
170 getImportedAgentSessionSources: () => Effect.die("unused"),
171 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
172 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
173 getThreadRuntimeContext: () => Effect.die("unused"),
174 getTurnStartMessage: () => Effect.die("unused"),
175 getThreadShellById: () => Effect.die("unused"),
176 getThreadDetailById: () => Effect.die("unused"),
177 getThreadDetailSnapshot: () => Effect.die("unused"),
178 searchThreads: () => Effect.succeed({ matches: [] }),
179 listThreadWorktreePaths: () => Effect.succeed([]),
180 }),
181 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
182 readEvents: () => Stream.empty,
183 readThreadEvents: () => Stream.empty,
184 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
185 dispatch: (command) =>
186 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
187 Effect.as({ sequence: 1 }),
188 ),
189 streamDomainEvents: Stream.empty,
190 subscribeDomainEvents: Effect.succeed(Stream.empty),
191 latestSequence: Effect.succeed(0),
192 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
193 Effect.provide(NodeServices.layer),
194 );
195
196 assert.deepStrictEqual(targets, {
197 bootstrapProjectId,
198 bootstrapThreadId,
199 bootstrapProjectCreated: false,
200 bootstrapThreadCreated: false,
201 });
202 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
203 });
204});
205
206it.effect.each([
207 { existing: false, machineModel: null, projectModel: null },
208 { existing: false, machineModel: "claude-sonnet-4-6", projectModel: null },
209 { existing: true, machineModel: "claude-sonnet-4-6", projectModel: null },
210 { existing: true, machineModel: "claude-sonnet-4-6", projectModel: "gpt-5.4" },
211])("auto-bootstrap model precedence: %j", ({ existing, machineModel, projectModel }) =>
212 Effect.gen(function* () {
213 const machineSelection = machineModel
214 ? { instanceId: ProviderInstanceId.make("claude-code"), model: machineModel }
215 : null;
216 const projectSelection = projectModel
217 ? { instanceId: ProviderInstanceId.make("codex"), model: projectModel }
218 : null;
219 const dispatchCalls = yield* Ref.make<
220 ReadonlyArray<{
221 readonly type: string;
222 readonly defaultModelSelection?: unknown;
223 readonly modelSelection?: unknown;
224 }>
225 >([]);
226 const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
227 Effect.provide(ServerSettings.layerTest({ defaultModelSelection: machineSelection })),
228 Effect.provideService(ServerConfig.ServerConfig, {
229 cwd: "/tmp/startup-project",
230 autoBootstrapProjectFromCwd: true,
231 } as never),
232 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
233 getUserInputActivity: () => Effect.die("unused"),
234 getCommandReadModel: () => Effect.die("unused"),
235 getSnapshot: () => Effect.die("unused"),
236 getShellSnapshot: () => Effect.die("unused"),
237 getArchivedShellSnapshot: () => Effect.die("unused"),
238 getSnapshotSequence: () => Effect.die("unused"),
239 getCounts: () => Effect.die("unused"),
240 getEventReplayStats: () => Effect.die("unused"),
241 getActiveProjectByWorkspaceRoot: () =>
242 Effect.succeed(
243 existing
244 ? Option.some({
245 id: ProjectId.make("existing-project"),
246 title: "Startup Project",
247 workspaceRoot: "/tmp/startup-project",
248 defaultModelSelection: projectSelection,
249 scripts: [],
250 createdAt: "2026-01-01T00:00:00.000Z",
251 updatedAt: "2026-01-01T00:00:00.000Z",
252 deletedAt: null,
253 })
254 : Option.none(),
255 ),
256 getProjectShellById: () => Effect.die("unused"),
257 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
258 getImportedAgentSessionSources: () => Effect.die("unused"),
259 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
260 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
261 getThreadRuntimeContext: () => Effect.die("unused"),
262 getTurnStartMessage: () => Effect.die("unused"),
263 getThreadShellById: () => Effect.die("unused"),
264 getThreadDetailById: () => Effect.die("unused"),
265 getThreadDetailSnapshot: () => Effect.die("unused"),
266 searchThreads: () => Effect.succeed({ matches: [] }),
267 listThreadWorktreePaths: () => Effect.succeed([]),
268 }),
269 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
270 readEvents: () => Stream.empty,
271 readThreadEvents: () => Stream.empty,
272 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
273 dispatch: (command) =>
274 Ref.update(dispatchCalls, (calls) => [...calls, command]).pipe(
275 Effect.as({ sequence: 1 }),
276 ),
277 streamDomainEvents: Stream.empty,
278 subscribeDomainEvents: Effect.succeed(Stream.empty),
279 latestSequence: Effect.succeed(0),
280 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
281 Effect.provide(NodeServices.layer),
282 );
283
284 assert.equal(typeof targets.bootstrapProjectId, "string");
285 assert.equal(typeof targets.bootstrapThreadId, "string");
286 assert.equal(targets.bootstrapProjectCreated, !existing);
287 assert.equal(targets.bootstrapThreadCreated, true);
288 const commands = yield* Ref.get(dispatchCalls);
289 assert.deepStrictEqual(
290 commands.map((command) => command.type),
291 existing ? ["thread.create"] : ["project.create", "thread.create"],
292 );
293 if (!existing) assert.equal("defaultModelSelection" in commands[0]!, false);
294 assert.deepStrictEqual(
295 commands.at(-1)?.modelSelection,
296 projectSelection ??
297 machineSelection ?? {
298 instanceId: ProviderInstanceId.make("codex"),
299 model: DEFAULT_MODEL,
300 },
301 );
302 }),
303);
304
305it.effect(
306 "resolveAutoBootstrapWelcomeTargets preserves a project created before thread failure",
307 () =>
308 Effect.gen(function* () {
309 const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
310 const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
311 Effect.provide(ServerSettings.layerTest()),
312 Effect.provideService(ServerConfig.ServerConfig, {
313 cwd: "/tmp/startup-project",
314 autoBootstrapProjectFromCwd: true,
315 } as never),
316 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
317 getUserInputActivity: () => Effect.die("unused"),
318 getCommandReadModel: () => Effect.die("unused"),
319 getSnapshot: () => Effect.die("unused"),
320 getShellSnapshot: () => Effect.die("unused"),
321 getArchivedShellSnapshot: () => Effect.die("unused"),
322 getSnapshotSequence: () => Effect.die("unused"),
323 getCounts: () => Effect.die("unused"),
324 getEventReplayStats: () => Effect.die("unused"),
325 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
326 getProjectShellById: () => Effect.die("unused"),
327 getFirstActiveThreadIdByProjectId: () => Effect.die("thread lookup failed"),
328 getImportedAgentSessionSources: () => Effect.die("unused"),
329 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
330 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
331 getThreadRuntimeContext: () => Effect.die("unused"),
332 getTurnStartMessage: () => Effect.die("unused"),
333 getThreadShellById: () => Effect.die("unused"),
334 getThreadDetailById: () => Effect.die("unused"),
335 getThreadDetailSnapshot: () => Effect.die("unused"),
336 searchThreads: () => Effect.succeed({ matches: [] }),
337 listThreadWorktreePaths: () => Effect.succeed([]),
338 }),
339 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
340 readEvents: () => Stream.empty,
341 readThreadEvents: () => Stream.empty,
342 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
343 dispatch: (command) =>
344 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
345 Effect.as({ sequence: 1 }),
346 ),
347 streamDomainEvents: Stream.empty,
348 subscribeDomainEvents: Effect.succeed(Stream.empty),
349 latestSequence: Effect.succeed(0),
350 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
351 Effect.provide(NodeServices.layer),
352 );
353
354 assert.equal(typeof targets.bootstrapProjectId, "string");
355 assert.equal(targets.bootstrapProjectCreated, true);
356 assert.equal(targets.bootstrapThreadId, undefined);
357 assert.equal(targets.bootstrapThreadCreated, undefined);
358 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create"]);
359 }),
360);
361
362it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation failures", () =>
363 Effect.gen(function* () {
364 const crypto = yield* Crypto.Crypto;
365 const uuidError = PlatformError.systemError({
366 _tag: "Unknown",
367 module: "Crypto",
368 method: "randomUUIDv4",
369 description: "UUID generation unavailable",
370 });
371 const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
372
373 const error = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
374 Effect.provide(ServerSettings.layerTest()),
375 Effect.provideService(ServerConfig.ServerConfig, {
376 cwd: "/tmp/startup-project",
377 autoBootstrapProjectFromCwd: true,
378 } as never),
379 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
380 getUserInputActivity: () => Effect.die("unused"),
381 getCommandReadModel: () => Effect.die("unused"),
382 getSnapshot: () => Effect.die("unused"),
383 getShellSnapshot: () => Effect.die("unused"),
384 getArchivedShellSnapshot: () => Effect.die("unused"),
385 getSnapshotSequence: () => Effect.die("unused"),
386 getCounts: () => Effect.die("unused"),
387 getEventReplayStats: () => Effect.die("unused"),
388 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
389 getProjectShellById: () => Effect.die("unused"),
390 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
391 getImportedAgentSessionSources: () => Effect.die("unused"),
392 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
393 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
394 getThreadRuntimeContext: () => Effect.die("unused"),
395 getTurnStartMessage: () => Effect.die("unused"),
396 getThreadShellById: () => Effect.die("unused"),
397 getThreadDetailById: () => Effect.die("unused"),
398 getThreadDetailSnapshot: () => Effect.die("unused"),
399 searchThreads: () => Effect.succeed({ matches: [] }),
400 listThreadWorktreePaths: () => Effect.succeed([]),
401 }),
402 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
403 readEvents: () => Stream.empty,
404 readThreadEvents: () => Stream.empty,
405 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
406 dispatch: (command) =>
407 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
408 Effect.as({ sequence: 1 }),
409 ),
410 streamDomainEvents: Stream.empty,
411 subscribeDomainEvents: Effect.succeed(Stream.empty),
412 latestSequence: Effect.succeed(0),
413 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
414 Effect.provideService(Crypto.Crypto, {
415 ...crypto,
416 randomUUIDv4: Effect.fail(uuidError),
417 }),
418 Effect.flip,
419 );
420
421 assert.strictEqual(error, uuidError);
422 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
423 }).pipe(Effect.provide(NodeServices.layer)),
424);
425
426it.effect("completeAutoBootstrapWelcome settles failures without bootstrap targets", () =>
427 Effect.gen(function* () {
428 const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(
429 Effect.fail("bootstrap failed"),
430 );
431
432 assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
433 }),
434);
435
436it.effect("completeAutoBootstrapWelcome settles unexpected defects", () =>
437 Effect.gen(function* () {
438 const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(
439 Effect.die("bootstrap defect"),
440 );
441
442 assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
443 }),
444);
445
446it.effect("completeAutoBootstrapWelcome settles an empty bootstrap result", () =>
447 Effect.gen(function* () {
448 const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(Effect.succeed({}));
449
450 assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
451 }),
452);