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