Open History to see the last commit
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 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
159 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
160 getThreadRuntimeContext: () => Effect.die("unused"),
161 getThreadShellById: () => Effect.die("unused"),
162 getThreadDetailById: () => Effect.die("unused"),
163 getThreadDetailSnapshot: () => Effect.die("unused"),
164 searchThreads: () => Effect.succeed({ matches: [] }),
165 }),
166 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
167 readEvents: () => Stream.empty,
168 readThreadEvents: () => Stream.empty,
169 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
170 dispatch: (command) =>
171 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
172 Effect.as({ sequence: 1 }),
173 ),
174 streamDomainEvents: Stream.empty,
175 subscribeDomainEvents: Effect.succeed(Stream.empty),
176 latestSequence: Effect.succeed(0),
177 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
178 Effect.provide(NodeServices.layer),
179 );
180
181 assert.deepStrictEqual(targets, {
182 bootstrapProjectId,
183 bootstrapThreadId,
184 });
185 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
186 });
187});
188
189it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when missing", () =>
190 Effect.gen(function* () {
191 const dispatchCalls = yield* Ref.make<
192 ReadonlyArray<{
193 readonly type: string;
194 readonly defaultModelSelection?: unknown;
195 readonly modelSelection?: unknown;
196 }>
197 >([]);
198 const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
199 Effect.provideService(ServerConfig.ServerConfig, {
200 cwd: "/tmp/startup-project",
201 autoBootstrapProjectFromCwd: true,
202 } as never),
203 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
204 getUserInputActivity: () => Effect.die("unused"),
205 getCommandReadModel: () => Effect.die("unused"),
206 getSnapshot: () => Effect.die("unused"),
207 getShellSnapshot: () => Effect.die("unused"),
208 getArchivedShellSnapshot: () => Effect.die("unused"),
209 getSnapshotSequence: () => Effect.die("unused"),
210 getCounts: () => Effect.die("unused"),
211 getEventReplayStats: () => Effect.die("unused"),
212 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
213 getProjectShellById: () => Effect.die("unused"),
214 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
215 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
216 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
217 getThreadRuntimeContext: () => Effect.die("unused"),
218 getThreadShellById: () => Effect.die("unused"),
219 getThreadDetailById: () => Effect.die("unused"),
220 getThreadDetailSnapshot: () => Effect.die("unused"),
221 searchThreads: () => Effect.succeed({ matches: [] }),
222 }),
223 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
224 readEvents: () => Stream.empty,
225 readThreadEvents: () => Stream.empty,
226 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
227 dispatch: (command) =>
228 Ref.update(dispatchCalls, (calls) => [...calls, command]).pipe(
229 Effect.as({ sequence: 1 }),
230 ),
231 streamDomainEvents: Stream.empty,
232 subscribeDomainEvents: Effect.succeed(Stream.empty),
233 latestSequence: Effect.succeed(0),
234 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
235 Effect.provide(NodeServices.layer),
236 );
237
238 assert.equal(typeof targets.bootstrapProjectId, "string");
239 assert.equal(typeof targets.bootstrapThreadId, "string");
240 const commands = yield* Ref.get(dispatchCalls);
241 assert.deepStrictEqual(
242 commands.map((command) => command.type),
243 ["project.create", "thread.create"],
244 );
245 assert.equal("defaultModelSelection" in commands[0]!, false);
246 assert.deepStrictEqual(commands[1]?.modelSelection, {
247 instanceId: ProviderInstanceId.make("codex"),
248 model: DEFAULT_MODEL,
249 });
250 }),
251);
252
253it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation failures", () =>
254 Effect.gen(function* () {
255 const crypto = yield* Crypto.Crypto;
256 const uuidError = PlatformError.systemError({
257 _tag: "Unknown",
258 module: "Crypto",
259 method: "randomUUIDv4",
260 description: "UUID generation unavailable",
261 });
262 const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
263
264 const error = 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.succeed(Option.none()),
281 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
282 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
283 getThreadRuntimeContext: () => Effect.die("unused"),
284 getThreadShellById: () => Effect.die("unused"),
285 getThreadDetailById: () => Effect.die("unused"),
286 getThreadDetailSnapshot: () => Effect.die("unused"),
287 searchThreads: () => Effect.succeed({ matches: [] }),
288 }),
289 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
290 readEvents: () => Stream.empty,
291 readThreadEvents: () => Stream.empty,
292 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
293 dispatch: (command) =>
294 Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
295 Effect.as({ sequence: 1 }),
296 ),
297 streamDomainEvents: Stream.empty,
298 subscribeDomainEvents: Effect.succeed(Stream.empty),
299 latestSequence: Effect.succeed(0),
300 } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
301 Effect.provideService(Crypto.Crypto, {
302 ...crypto,
303 randomUUIDv4: Effect.fail(uuidError),
304 }),
305 Effect.flip,
306 );
307
308 assert.strictEqual(error, uuidError);
309 assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
310 }).pipe(Effect.provide(NodeServices.layer)),
311);