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 getProjectShellById: () => Effect.die("unused"),
191 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
192 getImportedAgentSessionSources: () => Effect.die("unused"),
193 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
194 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
195 getThreadRuntimeContext: () => Effect.die("unused"),
196 getTurnStartMessage: () => Effect.die("unused"),
197 getThreadShellById: () => Effect.die("unused"),
198 getThreadDetailById: () => Effect.die("unused"),
199 getThreadDetailSnapshot: () => Effect.die("unused"),
200 searchThreads: () => Effect.succeed({ matches: [] }),
201 }),
202 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
203 readEvents: () => Stream.empty,
204 readThreadEvents: () => Stream.empty,
205 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
206 dispatch: (command) =>
207 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
208 Effect.as({ sequence: 1 }),
209 ),
210 streamDomainEvents: Stream.empty,
211 subscribeDomainEvents: Effect.succeed(Stream.empty),
212 latestSequence: Effect.succeed(0),
213 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
214 Effect.provide(NodeServices.layer),
215 );
216
217 assert.deepStrictEqual(targets, {
218 bootstrapProjectId,
219 bootstrapThreadId,
220 bootstrapProjectCreated: false,
221 bootstrapThreadCreated: false,
222 });
223 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
224 });
225});
226
227it.effect.each([
228 {
229 existing: false,
230 machineModel: null,
231 projectModel: null,
232 machineMode: "full-access",
233 projectMode: null,
234 },
235 {
236 existing: false,
237 machineModel: "claude-sonnet-4-6",
238 projectModel: null,
239 machineMode: "approval-required",
240 projectMode: null,
241 },
242 {
243 existing: true,
244 machineModel: "claude-sonnet-4-6",
245 projectModel: null,
246 machineMode: "auto",
247 projectMode: null,
248 },
249 {
250 existing: true,
251 machineModel: "claude-sonnet-4-6",
252 projectModel: "gpt-5.4",
253 machineMode: "full-access",
254 projectMode: "auto-accept-edits",
255 },
256] as const)("auto-bootstrap model and permissions precedence: %j", (options) =>
257 Effect.gen(function* () {
258 const { existing, machineModel, projectModel, machineMode, projectMode } = options;
259 const machineSelection = machineModel
260 ? { instanceId: ProviderInstanceId.make("claude-code"), model: machineModel }
261 : null;
262 const projectSelection = projectModel
263 ? { instanceId: ProviderInstanceId.make("codex"), model: projectModel }
264 : null;
265 const dispatchCalls = yield* Ref.make<
266 ReadonlyArray<{
267 readonly type: string;
268 readonly defaultModelSelection?: unknown;
269 readonly modelSelection?: unknown;
270 readonly runtimeMode?: unknown;
271 }>
272 >([]);
273 const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
274 Effect.provide(
275 ServerSettings.layerTest({
276 defaultModelSelection: machineSelection,
277 defaultRuntimeMode: machineMode,
278 projectSettingsOverrides:
279 existing && projectSelection
280 ? {
281 [ProjectId.make("existing-project")]: {
282 defaultModelSelection: projectSelection,
283 ...(projectMode ? { defaultRuntimeMode: projectMode } : {}),
284 },
285 }
286 : {},
287 }),
288 ),
289 Effect.provideService(ServerConfig.ServerConfig, {
290 cwd: "/tmp/startup-project",
291 autoBootstrapProjectFromCwd: true,
292 } as never),
293 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
294 getUserInputActivity: () => Effect.die("unused"),
295 getCommandReadModel: () => Effect.die("unused"),
296 getSnapshot: () => Effect.die("unused"),
297 getShellSnapshot: () => Effect.die("unused"),
298 getArchivedShellSnapshot: () => Effect.die("unused"),
299 getSnapshotSequence: () => Effect.die("unused"),
300 getCounts: () => Effect.die("unused"),
301 getEventReplayStats: () => Effect.die("unused"),
302 getActiveProjectByWorkspaceRoot: () =>
303 Effect.succeed(
304 existing
305 ? Option.some({
306 id: ProjectId.make("existing-project"),
307 title: "Startup Project",
308 workspaceRoot: "/tmp/startup-project",
309 defaultModelSelection: null,
310 scripts: [],
311 createdAt: "2026-01-01T00:00:00.000Z",
312 updatedAt: "2026-01-01T00:00:00.000Z",
313 deletedAt: null,
314 })
315 : Option.none(),
316 ),
317 getProjectShellById: () => Effect.die("unused"),
318 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
319 getImportedAgentSessionSources: () => Effect.die("unused"),
320 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
321 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
322 getThreadRuntimeContext: () => Effect.die("unused"),
323 getTurnStartMessage: () => Effect.die("unused"),
324 getThreadShellById: () => Effect.die("unused"),
325 getThreadDetailById: () => Effect.die("unused"),
326 getThreadDetailSnapshot: () => Effect.die("unused"),
327 searchThreads: () => Effect.succeed({ matches: [] }),
328 }),
329 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
330 readEvents: () => Stream.empty,
331 readThreadEvents: () => Stream.empty,
332 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
333 dispatch: (command) =>
334 Ref.update(dispatchCalls, (calls) => [...calls, command]).pipe(
335 Effect.as({ sequence: 1 }),
336 ),
337 streamDomainEvents: Stream.empty,
338 subscribeDomainEvents: Effect.succeed(Stream.empty),
339 latestSequence: Effect.succeed(0),
340 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
341 Effect.provide(NodeServices.layer),
342 );
343
344 assert.equal(typeof targets.bootstrapProjectId, "string");
345 assert.equal(typeof targets.bootstrapThreadId, "string");
346 assert.equal(targets.bootstrapProjectCreated, !existing);
347 assert.equal(targets.bootstrapThreadCreated, true);
348 const commands = yield* Ref.get(dispatchCalls);
349 assert.deepStrictEqual(
350 commands.map((command) => command.type),
351 existing ? ["thread.create"] : ["project.create", "thread.create"],
352 );
353 if (!existing) assert.equal("defaultModelSelection" in commands[0]!, false);
354 assert.equal(commands.at(-1)?.runtimeMode, projectMode ?? machineMode);
355 assert.deepStrictEqual(
356 commands.at(-1)?.modelSelection,
357 projectSelection ??
358 machineSelection ?? {
359 instanceId: ProviderInstanceId.make("codex"),
360 model: DEFAULT_MODEL,
361 },
362 );
363 }),
364);
365
366it.effect(
367 "resolveAutoBootstrapWelcomeTargets preserves a project created before thread failure",
368 () =>
369 Effect.gen(function* () {
370 const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
371 const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
372 Effect.provide(ServerSettings.layerTest()),
373 Effect.provideService(ServerConfig.ServerConfig, {
374 cwd: "/tmp/startup-project",
375 autoBootstrapProjectFromCwd: true,
376 } as never),
377 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
378 getUserInputActivity: () => Effect.die("unused"),
379 getCommandReadModel: () => Effect.die("unused"),
380 getSnapshot: () => Effect.die("unused"),
381 getShellSnapshot: () => Effect.die("unused"),
382 getArchivedShellSnapshot: () => Effect.die("unused"),
383 getSnapshotSequence: () => Effect.die("unused"),
384 getCounts: () => Effect.die("unused"),
385 getEventReplayStats: () => Effect.die("unused"),
386 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
387 getProjectShellById: () => Effect.die("unused"),
388 getFirstActiveThreadIdByProjectId: () => Effect.die("thread lookup failed"),
389 getImportedAgentSessionSources: () => Effect.die("unused"),
390 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
391 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
392 getThreadRuntimeContext: () => Effect.die("unused"),
393 getTurnStartMessage: () => Effect.die("unused"),
394 getThreadShellById: () => Effect.die("unused"),
395 getThreadDetailById: () => Effect.die("unused"),
396 getThreadDetailSnapshot: () => Effect.die("unused"),
397 searchThreads: () => Effect.succeed({ matches: [] }),
398 }),
399 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
400 readEvents: () => Stream.empty,
401 readThreadEvents: () => Stream.empty,
402 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
403 dispatch: (command) =>
404 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
405 Effect.as({ sequence: 1 }),
406 ),
407 streamDomainEvents: Stream.empty,
408 subscribeDomainEvents: Effect.succeed(Stream.empty),
409 latestSequence: Effect.succeed(0),
410 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
411 Effect.provide(NodeServices.layer),
412 );
413
414 assert.equal(typeof targets.bootstrapProjectId, "string");
415 assert.equal(targets.bootstrapProjectCreated, true);
416 assert.equal(targets.bootstrapThreadId, undefined);
417 assert.equal(targets.bootstrapThreadCreated, undefined);
418 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create"]);
419 }),
420);
421
422it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation failures", () =>
423 Effect.gen(function* () {
424 const crypto = yield* Crypto.Crypto;
425 const uuidError = PlatformError.systemError({
426 _tag: "Unknown",
427 module: "Crypto",
428 method: "randomUUIDv4",
429 description: "UUID generation unavailable",
430 });
431 const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
432
433 const error = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
434 Effect.provide(ServerSettings.layerTest()),
435 Effect.provideService(ServerConfig.ServerConfig, {
436 cwd: "/tmp/startup-project",
437 autoBootstrapProjectFromCwd: true,
438 } as never),
439 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
440 getUserInputActivity: () => Effect.die("unused"),
441 getCommandReadModel: () => Effect.die("unused"),
442 getSnapshot: () => Effect.die("unused"),
443 getShellSnapshot: () => Effect.die("unused"),
444 getArchivedShellSnapshot: () => Effect.die("unused"),
445 getSnapshotSequence: () => Effect.die("unused"),
446 getCounts: () => Effect.die("unused"),
447 getEventReplayStats: () => Effect.die("unused"),
448 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
449 getProjectShellById: () => Effect.die("unused"),
450 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
451 getImportedAgentSessionSources: () => Effect.die("unused"),
452 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
453 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
454 getThreadRuntimeContext: () => Effect.die("unused"),
455 getTurnStartMessage: () => Effect.die("unused"),
456 getThreadShellById: () => Effect.die("unused"),
457 getThreadDetailById: () => Effect.die("unused"),
458 getThreadDetailSnapshot: () => Effect.die("unused"),
459 searchThreads: () => Effect.succeed({ matches: [] }),
460 }),
461 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
462 readEvents: () => Stream.empty,
463 readThreadEvents: () => Stream.empty,
464 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
465 dispatch: (command) =>
466 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
467 Effect.as({ sequence: 1 }),
468 ),
469 streamDomainEvents: Stream.empty,
470 subscribeDomainEvents: Effect.succeed(Stream.empty),
471 latestSequence: Effect.succeed(0),
472 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
473 Effect.provideService(Crypto.Crypto, {
474 ...crypto,
475 randomUUIDv4: Effect.fail(uuidError),
476 }),
477 Effect.flip,
478 );
479
480 assert.strictEqual(error, uuidError);
481 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
482 }).pipe(Effect.provide(NodeServices.layer)),
483);
484
485it.effect("completeAutoBootstrapWelcome settles failures without bootstrap targets", () =>
486 Effect.gen(function* () {
487 const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(
488 Effect.fail("bootstrap failed"),
489 );
490
491 assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
492 }),
493);
494
495it.effect("completeAutoBootstrapWelcome settles unexpected defects", () =>
496 Effect.gen(function* () {
497 const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(
498 Effect.die("bootstrap defect"),
499 );
500
501 assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
502 }),
503);
504
505it.effect("completeAutoBootstrapWelcome settles an empty bootstrap result", () =>
506 Effect.gen(function* () {
507 const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(Effect.succeed({}));
508
509 assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
510 }),
511);