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

serverRuntimeStartup.test.ts

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