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\n");
311 // Progress redraws separated by bare carriage returns are their own lines.
312 yield* emit("Progress: 1/3\rProgress: 2/3\rProgress: 3/3\r\nDone in 2s\r\n");
313 // A spoofed sentinel from the script itself must not settle completion.
314 yield* emit("__T3_SETUP_DONE__:0\r\n");
315 yield* emit(`__T3_SETUP_DONE___${"0".repeat(32)}:0\r\n`);
316 yield* emit(`${sentinel}3\r\n`);
317
318 const completion = yield* result.completion!;
319 expect(completion.exitCode).toBe(3);
320 expect(seen).toEqual([
321 "Resolving deps",
322 "Progress: 1/3",
323 "Progress: 2/3",
324 "Progress: 3/3",
325 "Done in 2s",
326 "__T3_SETUP_DONE__:0",
327 `__T3_SETUP_DONE___${"0".repeat(32)}:0`,
328 ]);
329 // The subscription is torn down once the sentinel arrives.
330 expect(listener).toBeNull();
331 }).pipe(
332 Effect.provide(testLayer(project, { open, write, subscribe })),
333 Effect.provideService(HostProcessPlatform, "linux"),
334 Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
335 );
336 },
337 );
338
339 it.effect("unsubscribes from terminal output when the command cannot be written", () => {
340 const open = vi.fn(() =>
341 Effect.succeed({
342 threadId: "thread-1",
343 terminalId: "setup-setup",
344 cwd: "/repo/worktrees/a",
345 worktreePath: "/repo/worktrees/a",
346 status: "running" as const,
347 pid: 123,
348 history: "",
349 exitCode: null,
350 exitSignal: null,
351 label: "setup-setup",
352 updatedAt: "2026-01-01T00:00:00.000Z",
353 }),
354 );
355 const write = vi.fn(() =>
356 Effect.fail(
357 new TerminalManager.TerminalCwdStatError({ cwd: "/repo/worktrees/a", cause: {} }),
358 ),
359 );
360 const unsubscribe = vi.fn();
361 const subscribe = vi.fn(() => Effect.succeed(unsubscribe));
362 const project = makeProject([
363 {
364 id: "setup",
365 name: "Setup",
366 command: "bun install",
367 icon: "configure",
368 runOnWorktreeCreate: true,
369 },
370 ]);
371
372 return Effect.gen(function* () {
373 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
374 const result = yield* runner
375 .runForThread({
376 threadId: "thread-1",
377 projectCwd: "/repo/project",
378 worktreePath: "/repo/worktrees/a",
379 observeCompletion: {},
380 })
381 .pipe(Effect.result);
382 expect(result._tag).toBe("Failure");
383 expect(unsubscribe).toHaveBeenCalledTimes(1);
384 }).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
385 });
386
387 it.effect.each([
388 {
389 shell: "/usr/bin/fish",
390 expected:
391 /^begin\rbun install\rend; printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' \$status\r$/,
392 },
393 {
394 shell: "/bin/bash",
395 expected: /^\( bun install\r\); printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' "\$\?"\r$/,
396 },
397 ])("wraps the command for the $shell syntax", ({ shell, expected }) => {
398 const open = vi.fn(() =>
399 Effect.succeed({
400 threadId: "thread-1",
401 terminalId: "setup-setup",
402 cwd: "/repo/worktrees/a",
403 worktreePath: "/repo/worktrees/a",
404 status: "running" as const,
405 pid: 123,
406 history: "",
407 exitCode: null,
408 exitSignal: null,
409 label: "setup-setup",
410 updatedAt: "2026-01-01T00:00:00.000Z",
411 }),
412 );
413 const writes: string[] = [];
414 const write = vi.fn((input: { data: string }) =>
415 Effect.sync(() => void writes.push(input.data)),
416 );
417 const project = makeProject([
418 {
419 id: "setup",
420 name: "Setup",
421 command: "bun install",
422 icon: "configure",
423 runOnWorktreeCreate: true,
424 },
425 ]);
426 return Effect.gen(function* () {
427 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
428 yield* runner.runForThread({
429 threadId: "thread-1",
430 projectCwd: "/repo/project",
431 worktreePath: "/repo/worktrees/a",
432 observeCompletion: {},
433 });
434 expect(writes).toHaveLength(1);
435 expect(writes[0]).toMatch(expected);
436 }).pipe(
437 Effect.provide(testLayer(project, { open, write })),
438 Effect.provideService(HostProcessPlatform, "linux"),
439 Effect.provideService(HostProcessEnvironment, { SHELL: shell }),
440 );
441 });
442
443 it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
444 const rootCause = new Error("stat failed");
445 const terminalError = new TerminalManager.TerminalCwdStatError({
446 cwd: "/repo/worktrees/a",
447 cause: rootCause,
448 });
449 const project = makeProject([
450 {
451 id: "setup",
452 name: "Setup",
453 command: "bun install",
454 icon: "configure",
455 runOnWorktreeCreate: true,
456 },
457 ]);
458
459 return Effect.gen(function* () {
460 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
461 const error = yield* runner
462 .runForThread({
463 threadId: "thread-1",
464 projectId: "project-1",
465 worktreePath: "/repo/worktrees/a",
466 })
467 .pipe(Effect.flip);
468
469 expect(isProjectSetupScriptOperationError(error)).toBe(true);
470 if (isProjectSetupScriptOperationError(error)) {
471 expect(error.operation).toBe("openTerminal");
472 expect(error.threadId).toBe("thread-1");
473 expect(error.projectId).toBe("project-1");
474 expect(error.worktreePath).toBe("/repo/worktrees/a");
475 expect(error.cause).toBe(terminalError);
476 expect(terminalError.cause).toBe(rootCause);
477 }
478 }).pipe(
479 Effect.provide(
480 testLayer(project, {
481 open: () => Effect.fail(terminalError),
482 write: () => Effect.die("unexpected write"),
483 }),
484 ),
485 );
486 });
487});