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

serverRuntimeStartup.test.ts

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