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

serverRuntimeStartup.test.ts

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