Open History to see the last commit
1import { describe, expect, it, vi } from "@effect/vitest";
2import { type OrchestrationProject, ProjectId, type TerminalEvent } from "@t3tools/contracts";
3import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8
9import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
10import * as ServerSettings from "../serverSettings.ts";
11import * as TerminalManager from "../terminal/Manager.ts";
12import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
13
14const isProjectSetupScriptOperationError = Schema.is(
15 ProjectSetupScriptRunner.ProjectSetupScriptOperationError,
16);
17
18const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
19 id: ProjectId.make("project-1"),
20 title: "Project",
21 workspaceRoot: "/repo/project",
22 defaultModelSelection: null,
23 scripts,
24 createdAt: "2026-01-01T00:00:00.000Z",
25 updatedAt: "2026-01-01T00:00:00.000Z",
26 deletedAt: null,
27});
28
29const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
30 Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
31 getUserInputActivity: () => Effect.die("unused"),
32 listActivitiesByKind: () => Effect.die("unused"),
33 getCommandReadModel: () => Effect.die("unused"),
34 getSnapshot: () => Effect.die("unused"),
35 getShellSnapshot: () => Effect.die("unused"),
36 getArchivedShellSnapshot: () => Effect.die("unused"),
37 getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
38 getCounts: () => Effect.die("unused"),
39 getEventReplayStats: () => Effect.die("unused"),
40 getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
41 Effect.succeed(
42 workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
43 ),
44 getProjectShells: () => Effect.die("unused"),
45 getProjectShellById: (projectId) =>
46 Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
47 getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
48 getImportedAgentSessionSources: () => Effect.die("unused"),
49 getThreadCheckpointContext: () => Effect.die("unused"),
50 getFullThreadDiffContext: () => Effect.die("unused"),
51 getThreadRuntimeContext: () => Effect.die("unused"),
52 getTurnStartMessage: () => Effect.die("unused"),
53 getThreadShellById: () => Effect.die("unused"),
54 getThreadDetailById: () => Effect.die("unused"),
55 getThreadDetailSnapshot: () => Effect.die("unused"),
56 searchThreads: () => Effect.succeed({ matches: [] }),
57 });
58
59type TerminalOverrides = Pick<TerminalManager.TerminalManager["Service"], "open" | "write"> &
60 Partial<Pick<TerminalManager.TerminalManager["Service"], "subscribe">>;
61
62const makeTerminalManagerLayer = (overrides: TerminalOverrides) =>
63 Layer.succeed(TerminalManager.TerminalManager, {
64 attachStream: () => Effect.die(new Error("unused")),
65 resize: () => Effect.void,
66 clear: () => Effect.void,
67 restart: () => Effect.die(new Error("unused")),
68 close: () => Effect.void,
69 subscribe: () => Effect.succeed(() => undefined),
70 subscribeMetadata: () => Effect.succeed(() => undefined),
71 ...overrides,
72 });
73
74const testLayer = (
75 project: OrchestrationProject,
76 terminal: TerminalOverrides,
77 settings = ServerSettings.layerTest(),
78) =>
79 ProjectSetupScriptRunner.layer.pipe(
80 Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
81 Layer.provideMerge(makeTerminalManagerLayer(terminal)),
82 Layer.provide(settings),
83 );
84
85describe("ProjectSetupScriptRunner", () => {
86 it.effect("runs the inherited machine setup action in the checkout's worktree", () => {
87 const open = vi.fn(() =>
88 Effect.succeed({
89 threadId: "thread-1",
90 terminalId: "setup-default-setup",
91 cwd: "/repo/worktrees/a",
92 worktreePath: "/repo/worktrees/a",
93 status: "running" as const,
94 pid: 123,
95 history: "",
96 exitCode: null,
97 exitSignal: null,
98 label: "setup-default-setup",
99 updatedAt: "2026-01-01T00:00:00.000Z",
100 }),
101 );
102 const write = vi.fn(() => Effect.void);
103 return Effect.gen(function* () {
104 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
105 const result = yield* runner.runForThread({
106 threadId: "thread-1",
107 projectId: "project-1",
108 worktreePath: "/repo/worktrees/a",
109 });
110 expect(result).toMatchObject({ status: "started", scriptId: "default-setup" });
111 expect(open).toHaveBeenCalledWith({
112 threadId: "thread-1",
113 terminalId: "setup-default-setup",
114 cwd: "/repo/worktrees/a",
115 worktreePath: "/repo/worktrees/a",
116 env: {
117 T3CODE_PROJECT_ROOT: "/repo/project",
118 T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
119 NO_COLOR: "1",
120 FORCE_COLOR: "0",
121 },
122 });
123 expect(write).toHaveBeenCalledWith({
124 threadId: "thread-1",
125 terminalId: "setup-default-setup",
126 data: "npm install\r",
127 });
128 }).pipe(
129 Effect.provide(
130 testLayer(
131 makeProject([]),
132 { open, write },
133 ServerSettings.layerTest({
134 defaultProjectScripts: [
135 {
136 id: "default-setup",
137 name: "Setup",
138 command: "npm install",
139 icon: "configure",
140 runOnWorktreeCreate: true,
141 },
142 ],
143 }),
144 ),
145 ),
146 );
147 });
148
149 it.effect("returns no-script when no setup script exists", () => {
150 const open = vi.fn(() => Effect.die("unexpected open"));
151 const write = vi.fn(() => Effect.die("unexpected write"));
152 const project = makeProject([]);
153
154 return Effect.gen(function* () {
155 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
156 const result = yield* runner.runForThread({
157 threadId: "thread-1",
158 projectId: "project-1",
159 worktreePath: "/repo/worktrees/a",
160 });
161
162 expect(result).toEqual({ status: "no-script" });
163 expect(open).not.toHaveBeenCalled();
164 expect(write).not.toHaveBeenCalled();
165 }).pipe(Effect.provide(testLayer(project, { open, write })));
166 });
167
168 it.effect(
169 "opens the deterministic setup terminal with worktree env and writes the command",
170 () => {
171 const open = vi.fn(() =>
172 Effect.succeed({
173 threadId: "thread-1",
174 terminalId: "setup-setup",
175 cwd: "/repo/worktrees/a",
176 worktreePath: "/repo/worktrees/a",
177 status: "running" as const,
178 pid: 123,
179 history: "",
180 exitCode: null,
181 exitSignal: null,
182 label: "setup-setup",
183 updatedAt: "2026-01-01T00:00:00.000Z",
184 }),
185 );
186 const write = vi.fn(() => Effect.void);
187 const project = makeProject([
188 {
189 id: "setup",
190 name: "Setup",
191 command: "bun install",
192 icon: "configure",
193 runOnWorktreeCreate: true,
194 },
195 ]);
196
197 return Effect.gen(function* () {
198 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
199 const result = yield* runner.runForThread({
200 threadId: "thread-1",
201 projectCwd: "/repo/project",
202 worktreePath: "/repo/worktrees/a",
203 });
204
205 expect(result).toEqual({
206 status: "started",
207 scriptId: "setup",
208 scriptName: "Setup",
209 scriptCommand: "bun install",
210 terminalId: "setup-setup",
211 cwd: "/repo/worktrees/a",
212 async: true,
213 });
214 expect(open).toHaveBeenCalledWith({
215 threadId: "thread-1",
216 terminalId: "setup-setup",
217 cwd: "/repo/worktrees/a",
218 worktreePath: "/repo/worktrees/a",
219 env: {
220 NO_COLOR: "1",
221 FORCE_COLOR: "0",
222 T3CODE_PROJECT_ROOT: "/repo/project",
223 T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
224 },
225 });
226 expect(write).toHaveBeenCalledWith({
227 threadId: "thread-1",
228 terminalId: "setup-setup",
229 data: "bun install\r",
230 });
231 }).pipe(Effect.provide(testLayer(project, { open, write })));
232 },
233 );
234
235 it.effect(
236 "wraps the command with a completion sentinel and resolves the exit code from terminal output",
237 () => {
238 const open = vi.fn(() =>
239 Effect.succeed({
240 threadId: "thread-1",
241 terminalId: "setup-setup",
242 cwd: "/repo/worktrees/a",
243 worktreePath: "/repo/worktrees/a",
244 status: "running" as const,
245 pid: 123,
246 history: "",
247 exitCode: null,
248 exitSignal: null,
249 label: "setup-setup",
250 updatedAt: "2026-01-01T00:00:00.000Z",
251 }),
252 );
253 const writes: string[] = [];
254 const write = vi.fn((input: { data: string }) =>
255 Effect.sync(() => void writes.push(input.data)),
256 );
257 let listener: ((event: TerminalEvent) => Effect.Effect<void>) | null = null;
258 const subscribe = vi.fn((next: (event: TerminalEvent) => Effect.Effect<void>) => {
259 listener = next;
260 return Effect.succeed(() => {
261 listener = null;
262 });
263 });
264 const project = makeProject([
265 {
266 id: "setup",
267 name: "Setup",
268 command: "bun install",
269 icon: "configure",
270 runOnWorktreeCreate: true,
271 },
272 ]);
273 const emit = (data: string) =>
274 Effect.suspend(() =>
275 listener
276 ? listener({ threadId: "thread-1", terminalId: "setup-setup", type: "output", data })
277 : Effect.void,
278 );
279
280 return Effect.gen(function* () {
281 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
282 const seen: string[] = [];
283 const result = yield* runner.runForThread({
284 threadId: "thread-1",
285 projectCwd: "/repo/project",
286 worktreePath: "/repo/worktrees/a",
287 observeCompletion: {
288 onOutputLine: (line) => Effect.sync(() => void seen.push(line)),
289 },
290 });
291 expect(result.status).toBe("started");
292 if (result.status !== "started") return;
293 expect(result.completion).toBeDefined();
294
295 // The subscription is attached before the command is written.
296 expect(subscribe).toHaveBeenCalledTimes(1);
297 expect(writes).toHaveLength(1);
298 // The block closes on its own line so a trailing comment in the
299 // command cannot swallow the sentinel, and the sentinel carries a
300 // per-run token so script output cannot spoof it.
301 const written = writes[0] ?? "";
302 const sentinel = /__T3_SETUP_DONE___[0-9a-f]{32}:/.exec(written)?.[0];
303 expect(sentinel).toBeDefined();
304 expect(written).toBe(`( bun install\r); printf '\\n${sentinel}%s\\n' "$?"\r`);
305
306 // Output arrives in chunks; partial lines are buffered until a newline,
307 // control sequences are stripped, and the echoed wrapper is hidden.
308 yield* emit(`( bun install\r\n> ); printf '\\n${sentinel}%s\\n' "$?"\r\n`);
309 yield* emit("\u001b[32mResolving");
310 yield* emit(" deps\u001b[0m\r\nDone in 2s\r\n");
311 // A spoofed sentinel from the script itself must not settle completion.
312 yield* emit("__T3_SETUP_DONE__:0\r\n");
313 yield* emit(`__T3_SETUP_DONE___${"0".repeat(32)}:0\r\n`);
314 yield* emit(`${sentinel}3\r\n`);
315
316 const completion = yield* result.completion!;
317 expect(completion.exitCode).toBe(3);
318 expect(seen).toEqual([
319 "Resolving deps",
320 "Done in 2s",
321 "__T3_SETUP_DONE__:0",
322 `__T3_SETUP_DONE___${"0".repeat(32)}:0`,
323 ]);
324 // The subscription is torn down once the sentinel arrives.
325 expect(listener).toBeNull();
326 }).pipe(
327 Effect.provide(testLayer(project, { open, write, subscribe })),
328 Effect.provideService(HostProcessPlatform, "linux"),
329 Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
330 );
331 },
332 );
333
334 it.effect("unsubscribes from terminal output when the command cannot be written", () => {
335 const open = vi.fn(() =>
336 Effect.succeed({
337 threadId: "thread-1",
338 terminalId: "setup-setup",
339 cwd: "/repo/worktrees/a",
340 worktreePath: "/repo/worktrees/a",
341 status: "running" as const,
342 pid: 123,
343 history: "",
344 exitCode: null,
345 exitSignal: null,
346 label: "setup-setup",
347 updatedAt: "2026-01-01T00:00:00.000Z",
348 }),
349 );
350 const write = vi.fn(() =>
351 Effect.fail(
352 new TerminalManager.TerminalCwdStatError({ cwd: "/repo/worktrees/a", cause: {} }),
353 ),
354 );
355 const unsubscribe = vi.fn();
356 const subscribe = vi.fn(() => Effect.succeed(unsubscribe));
357 const project = makeProject([
358 {
359 id: "setup",
360 name: "Setup",
361 command: "bun install",
362 icon: "configure",
363 runOnWorktreeCreate: true,
364 },
365 ]);
366
367 return Effect.gen(function* () {
368 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
369 const result = yield* runner
370 .runForThread({
371 threadId: "thread-1",
372 projectCwd: "/repo/project",
373 worktreePath: "/repo/worktrees/a",
374 observeCompletion: {},
375 })
376 .pipe(Effect.result);
377 expect(result._tag).toBe("Failure");
378 expect(unsubscribe).toHaveBeenCalledTimes(1);
379 }).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
380 });
381
382 it.effect.each([
383 {
384 shell: "/usr/bin/fish",
385 expected:
386 /^begin\rbun install\rend; printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' \$status\r$/,
387 },
388 {
389 shell: "/bin/bash",
390 expected: /^\( bun install\r\); printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' "\$\?"\r$/,
391 },
392 ])("wraps the command for the $shell syntax", ({ shell, expected }) => {
393 const open = vi.fn(() =>
394 Effect.succeed({
395 threadId: "thread-1",
396 terminalId: "setup-setup",
397 cwd: "/repo/worktrees/a",
398 worktreePath: "/repo/worktrees/a",
399 status: "running" as const,
400 pid: 123,
401 history: "",
402 exitCode: null,
403 exitSignal: null,
404 label: "setup-setup",
405 updatedAt: "2026-01-01T00:00:00.000Z",
406 }),
407 );
408 const writes: string[] = [];
409 const write = vi.fn((input: { data: string }) =>
410 Effect.sync(() => void writes.push(input.data)),
411 );
412 const project = makeProject([
413 {
414 id: "setup",
415 name: "Setup",
416 command: "bun install",
417 icon: "configure",
418 runOnWorktreeCreate: true,
419 },
420 ]);
421 return Effect.gen(function* () {
422 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
423 yield* runner.runForThread({
424 threadId: "thread-1",
425 projectCwd: "/repo/project",
426 worktreePath: "/repo/worktrees/a",
427 observeCompletion: {},
428 });
429 expect(writes).toHaveLength(1);
430 expect(writes[0]).toMatch(expected);
431 }).pipe(
432 Effect.provide(testLayer(project, { open, write })),
433 Effect.provideService(HostProcessPlatform, "linux"),
434 Effect.provideService(HostProcessEnvironment, { SHELL: shell }),
435 );
436 });
437
438 it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
439 const rootCause = new Error("stat failed");
440 const terminalError = new TerminalManager.TerminalCwdStatError({
441 cwd: "/repo/worktrees/a",
442 cause: rootCause,
443 });
444 const project = makeProject([
445 {
446 id: "setup",
447 name: "Setup",
448 command: "bun install",
449 icon: "configure",
450 runOnWorktreeCreate: true,
451 },
452 ]);
453
454 return Effect.gen(function* () {
455 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
456 const error = yield* runner
457 .runForThread({
458 threadId: "thread-1",
459 projectId: "project-1",
460 worktreePath: "/repo/worktrees/a",
461 })
462 .pipe(Effect.flip);
463
464 expect(isProjectSetupScriptOperationError(error)).toBe(true);
465 if (isProjectSetupScriptOperationError(error)) {
466 expect(error.operation).toBe("openTerminal");
467 expect(error.threadId).toBe("thread-1");
468 expect(error.projectId).toBe("project-1");
469 expect(error.worktreePath).toBe("/repo/worktrees/a");
470 expect(error.cause).toBe(terminalError);
471 expect(terminalError.cause).toBe(rootCause);
472 }
473 }).pipe(
474 Effect.provide(
475 testLayer(project, {
476 open: () => Effect.fail(terminalError),
477 write: () => Effect.die("unexpected write"),
478 }),
479 ),
480 );
481 });
482});