The best way to control Claude Code, Codex and more from any computer or phone
fix(server): worktree setup no longer hangs when a shell startup prompt eats the command (#24775)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 25, 2026 at 02:36 UTC
5d5b6e025ca4a4d8c9e15ec69d525c1f749fea40
2 files changed
+286
-25
apps/server/src/project/ProjectSetupScriptRunner.test.ts
new
+168
@@ -0,0 +1,168 @@
1
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
+import { describe, expect, it } from "@effect/vitest";
3
+import { ProjectId, type TerminalEvent, type TerminalSessionSnapshot } from "@t3tools/contracts";
4
+import * as HostProcess from "@t3tools/shared/HostProcess";
5
+import * as Deferred from "effect/Deferred";
6
+import * as Effect from "effect/Effect";
7
+import * as Fiber from "effect/Fiber";
8
+import * as Layer from "effect/Layer";
9
+import * as Queue from "effect/Queue";
10
+import { TestClock } from "effect/testing";
11
+
12
+import * as ServerSettings from "../serverSettings.ts";
13
+import * as TerminalManager from "../terminal/Manager.ts";
14
+import * as ProjectService from "./ProjectService.ts";
15
+import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
16
+
17
+const threadId = "thread-1";
18
+const terminalId = "setup-setup";
19
+const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" };
20
+
21
+const openSnapshot = (history: string): TerminalSessionSnapshot => ({
22
+ threadId,
23
+ terminalId,
24
+ cwd: "/repo/.t3/worktrees/feature",
25
+ worktreePath: null,
26
+ status: "running",
27
+ pid: 123,
28
+ history,
29
+ exitCode: null,
30
+ exitSignal: null,
31
+ label: "zsh",
32
+ updatedAt: "2026-01-01T00:00:00.000Z",
33
+});
34
+
35
+const makeHarness = Effect.fn(function* (options: {
36
+ readonly history?: string;
37
+ readonly opening?: Deferred.Deferred<void>;
38
+}) {
39
+ const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
40
+ const writes = yield* Queue.unbounded<string>();
41
+ const outputLines = yield* Queue.unbounded<string>();
42
+ const terminals = Layer.mock(TerminalManager.TerminalManager)({
43
+ open: () =>
44
+ (options.opening
45
+ ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
46
+ : Effect.void
47
+ ).pipe(Effect.as(openSnapshot(options.history ?? ""))),
48
+ subscribe: (listener) =>
49
+ Effect.sync(() => {
50
+ listeners.add(listener);
51
+ return () => listeners.delete(listener);
52
+ }),
53
+ write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
54
+ closeIdle: () => Effect.void,
55
+ });
56
+ const runner = yield* ProjectSetupScriptRunner.make.pipe(
57
+ Effect.provide(
58
+ Layer.mergeAll(
59
+ terminals,
60
+ Layer.mock(ProjectService.ProjectService)({}),
61
+ ServerSettings.layerTest(),
62
+ NodeCrypto.layer,
63
+ ),
64
+ ),
65
+ Effect.provideService(HostProcess.Platform, "darwin"),
66
+ Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }),
67
+ );
68
+ const start = runner.runForThread({
69
+ threadId,
70
+ worktreePath: "/repo/.t3/worktrees/feature",
71
+ observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
72
+ project: {
73
+ id: ProjectId.make("project-1"),
74
+ workspaceRoot: "/repo",
75
+ scripts: [
76
+ {
77
+ id: "setup",
78
+ name: "Setup",
79
+ command: "vp i",
80
+ icon: "configure",
81
+ runOnWorktreeCreate: true,
82
+ },
83
+ ],
84
+ },
85
+ });
86
+ const emit = (terminalEvent: TerminalEvent) =>
87
+ Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
88
+ return { start, listeners, writes, outputLines, emit };
89
+});
90
+
91
+const setup = Effect.fn(function* (options: { readonly history?: string } = {}) {
92
+ const harness = yield* makeHarness(options);
93
+ const result = yield* harness.start;
94
+ const completion = result.status === "started" ? result.completion : undefined;
95
+ if (!completion) return yield* Effect.die("setup did not start an observed run");
96
+ return { ...harness, result, completion };
97
+});
98
+
99
+describe("ProjectSetupScriptRunner", () => {
100
+ it.effect("shows a startup prompt and types only once the line editor starts", () =>
101
+ Effect.gen(function* () {
102
+ const { result, writes, outputLines, emit } = yield* setup();
103
+ expect(result).toMatchObject({ status: "started", terminalId });
104
+
105
+ yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
106
+ yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
107
+ yield* TestClock.adjust("1 minute");
108
+ expect(yield* Queue.size(writes)).toBe(0);
109
+ expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
110
+
111
+ yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
112
+ yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
113
+ expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
114
+ }),
115
+ );
116
+
117
+ it.effect("types into a quiet shell that has no line editor", () =>
118
+ Effect.gen(function* () {
119
+ const { writes } = yield* setup();
120
+ yield* TestClock.adjust("3 seconds");
121
+ expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
122
+ }),
123
+ );
124
+
125
+ it.effect("ignores line editor state restored from an earlier shell", () =>
126
+ Effect.gen(function* () {
127
+ const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
128
+ yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
129
+ yield* TestClock.adjust("1 minute");
130
+ expect(yield* Queue.size(writes)).toBe(0);
131
+ }),
132
+ );
133
+
134
+ it.effect("forgets a busy startup child when the shell restarts", () =>
135
+ Effect.gen(function* () {
136
+ const { writes, emit } = yield* setup();
137
+ yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
138
+ yield* TestClock.adjust("1 minute");
139
+ expect(yield* Queue.size(writes)).toBe(0);
140
+ yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
141
+ // The restart lands inside a quiet window, so the next full window decides.
142
+ yield* TestClock.adjust("6 seconds");
143
+ expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
144
+ }),
145
+ );
146
+
147
+ it.effect("drops its terminal listeners when cancelled while the terminal opens", () =>
148
+ Effect.gen(function* () {
149
+ const opening = yield* Deferred.make<void>();
150
+ const { start, listeners } = yield* makeHarness({ opening });
151
+ const fiber = yield* Effect.forkChild(start);
152
+ yield* Deferred.await(opening);
153
+ expect(listeners.size).toBe(2);
154
+ yield* Fiber.interrupt(fiber);
155
+ expect(listeners.size).toBe(0);
156
+ }),
157
+ );
158
+
159
+ it.effect("does not type into a shell that exits during startup", () =>
160
+ Effect.gen(function* () {
161
+ const { completion, writes, emit } = yield* setup();
162
+ yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
163
+ expect(yield* completion).toMatchObject({ exitCode: null });
164
+ yield* TestClock.adjust("1 minute");
165
+ expect(yield* Queue.size(writes)).toBe(0);
166
+ }),
167
+ );
168
+});
apps/server/src/project/ProjectSetupScriptRunner.ts
+118
-25
@@ -74,7 +74,7 @@ export class ProjectSetupScriptOperationError extends Schema.TaggedError<Project
74
projectId: Schema.optional(Schema.String),
75
projectCwd: Schema.optional(Schema.String),
76
worktreePath: Schema.String,
77
- operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal", "writeCommand"]),
77
+ operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal"]),
78
cause: Schema.Defect(),
79
},
80
) {
@@ -139,6 +139,18 @@ function stripTerminalControl(text: string): string {
139
);
140
}
141
142
+// Line editors (zsh, fish, bash 5.1+) enable bracketed paste when they start reading a command.
143
+const BRACKETED_PASTE_ON = "\x1b[?2004h";
144
+const BRACKETED_PASTE_OFF = "\x1b[?2004l";
145
+// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first.
146
+const SHELL_QUIET_FALLBACK = "3 seconds";
147
+
148
+function lineEditorReading(text: string, previous: boolean): boolean {
149
+ const on = text.lastIndexOf(BRACKETED_PASTE_ON);
150
+ const off = text.lastIndexOf(BRACKETED_PASTE_OFF);
151
+ return on === off ? previous : on > off;
152
+}
153
+
154
type CompletionShell = "posix" | "fish" | "powershell";
155
156
function resolveCompletionShell(
@@ -176,6 +188,7 @@ export const make = Effect.gen(function* () {
188
const terminalManager = yield* TerminalManager.TerminalManager;
189
const serverSettings = yield* ServerSettings.ServerSettingsService;
190
const crypto = yield* Crypto.Crypto;
191
+ const serviceScope = yield* Effect.scope;
192
const completionShell = resolveCompletionShell(
193
yield* HostProcess.Platform,
194
yield* HostProcess.Environment,
@@ -263,7 +276,67 @@ export const make = Effect.gen(function* () {
276
Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),
277
Effect.ensuring(Effect.sync(() => unsubscribe())),
278
);
266
- return { completion, unsubscribe };
279
+ // A startup prompt waits for input on a line that has no newline yet.
280
+ const flushPartialLine = Effect.suspend(() => {
281
+ const partial = lineBuffer;
282
+ lineBuffer = "";
283
+ return handleLine(partial);
284
+ });
285
+ const abandon = settle(null).pipe(
286
+ Effect.andThen(Deferred.succeed(promptReturned, undefined)),
287
+ );
288
+ return { completion, unsubscribe, flushPartialLine, abandon };
289
+ },
290
+ );
291
+
292
+ // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the
293
+ // shell, which loses the command. Subscribe before the terminal opens so no activity is missed.
294
+ const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")(
295
+ function* (input: {
296
+ readonly threadId: string;
297
+ readonly terminalId: string;
298
+ readonly onStartupPrompt: Effect.Effect<void>;
299
+ }) {
300
+ const outcome = yield* Deferred.make<"ready" | "exited">();
301
+ let reading = false;
302
+ let carry = "";
303
+ let busy = false;
304
+ let activity = 0;
305
+ const unsubscribe = yield* terminalManager.subscribe((event) => {
306
+ if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
307
+ return Effect.void;
308
+ }
309
+ activity += 1;
310
+ // A new shell process starts idle; the manager resets its subprocess state without an event.
311
+ if (event.type === "started" || event.type === "restarted") {
312
+ busy = false;
313
+ reading = false;
314
+ carry = "";
315
+ }
316
+ if (event.type === "activity") busy = event.hasRunningSubprocess;
317
+ if (event.type === "output") {
318
+ const text = carry + event.data;
319
+ carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
320
+ reading = lineEditorReading(text, reading);
321
+ }
322
+ if (event.type === "exited" || event.type === "closed") {
323
+ return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid);
324
+ }
325
+ return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void;
326
+ });
327
+ // A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
328
+ const quiet = Effect.gen(function* () {
329
+ while (true) {
330
+ const seen = activity;
331
+ yield* Effect.sleep(SHELL_QUIET_FALLBACK);
332
+ if (activity !== seen) continue;
333
+ if (!busy) return "ready" as const;
334
+ yield* input.onStartupPrompt;
335
+ }
336
+ });
337
+ // Restored history can hold a previous shell's line editor state, so only live output counts.
338
+ const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet));
339
+ return { wait, unsubscribe };
340
},
341
);
342
@@ -361,25 +434,7 @@ export const make = Effect.gen(function* () {
434
)
435
: script.command;
436
364
- yield* terminalManager
365
- .open({
366
- threadId: input.threadId,
367
- terminalId,
368
- cwd,
369
- worktreePath: input.worktreePath,
370
- env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
371
- })
372
- .pipe(
373
- Effect.mapError(
374
- (cause) =>
375
- new ProjectSetupScriptOperationError({
376
- ...errorContext,
377
- operation: "openTerminal",
378
- cause,
379
- }),
380
- ),
381
- );
382
- // Subscribe before writing so the sentinel cannot race past the listener.
437
+ // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
438
const observed =
439
observe && completionToken
440
? yield* observeTerminalCompletion({
@@ -391,25 +446,63 @@ export const make = Effect.gen(function* () {
446
onOutputLine: observe.onOutputLine,
447
})
448
: undefined;
449
+ // PowerShell has no line-editor signal; keep its immediate write.
450
+ const readiness =
451
+ completionShell === "powershell"
452
+ ? undefined
453
+ : yield* watchShellReadiness({
454
+ threadId: input.threadId,
455
+ terminalId,
456
+ onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
457
+ });
458
459
yield* terminalManager
396
- .write({
460
+ .open({
461
threadId: input.threadId,
462
terminalId,
399
- data: projectScriptTerminalInput(commandLine),
463
+ cwd,
464
+ worktreePath: input.worktreePath,
465
+ env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
466
})
467
.pipe(
468
Effect.mapError(
469
(cause) =>
470
new ProjectSetupScriptOperationError({
471
...errorContext,
406
- operation: "writeCommand",
472
+ operation: "openTerminal",
473
cause,
474
}),
475
),
410
- Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
476
+ Effect.onError(() =>
477
+ Effect.sync(() => {
478
+ observed?.unsubscribe();
479
+ readiness?.unsubscribe();
480
+ }),
481
+ ),
482
);
483
484
+ // Return once the terminal exists so callers can show it while a startup prompt waits.
485
+ yield* (readiness?.wait ?? Effect.succeed("ready" as const)).pipe(
486
+ Effect.flatMap((shell) =>
487
+ shell === "exited"
488
+ ? Effect.void
489
+ : terminalManager.write({
490
+ threadId: input.threadId,
491
+ terminalId,
492
+ data: projectScriptTerminalInput(commandLine),
493
+ }),
494
+ ),
495
+ Effect.catchCause((cause) =>
496
+ Effect.logWarning("project script command was not written", {
497
+ ...errorContext,
498
+ terminalId,
499
+ cause,
500
+ }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
501
+ ),
502
+ Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())),
503
+ Effect.forkIn(serviceScope),
504
+ );
505
+
506
const completion = observed?.completion.pipe(
507
Effect.tap(({ exitCode }) =>
508
exitCode === 0