Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverRuntimeStartup.test.ts

448 lines18.9 KB

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