Skip to content

Commit 869b6e5

Browse files
t3dotggclaude
andcommitted
fix(server): worktree setup waits for the shell, so startup prompts can't eat it
A prompt in the user's shell rc (for example fnm offering to install a missing Node version) read the typed setup command as its answer. The shell then got half a command, the completion marker never printed, and setup spun forever. Wait for the shell's line editor (bracketed paste on) before typing, or for a quiet shell with no child process when there is no line editor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b3d382e commit 869b6e5

2 files changed

Lines changed: 182 additions & 18 deletions

File tree

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2+
import { describe, expect, it } from "@effect/vitest";
3+
import { ProjectId, type TerminalEvent } from "@t3tools/contracts";
4+
import * as HostProcess from "@t3tools/shared/HostProcess";
5+
import * as Effect from "effect/Effect";
6+
import * as Fiber from "effect/Fiber";
7+
import * as Layer from "effect/Layer";
8+
import * as Queue from "effect/Queue";
9+
import { TestClock } from "effect/testing";
10+
11+
import * as ServerSettings from "../serverSettings.ts";
12+
import * as TerminalManager from "../terminal/Manager.ts";
13+
import * as ProjectService from "./ProjectService.ts";
14+
import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
15+
16+
const threadId = "thread-1";
17+
const terminalId = "setup-setup";
18+
19+
type TerminalCall =
20+
| { readonly type: "subscribe"; readonly listener: (event: TerminalEvent) => Effect.Effect<void> }
21+
| { readonly type: "write"; readonly data: string };
22+
23+
const setup = Effect.gen(function* () {
24+
const calls = yield* Queue.unbounded<TerminalCall>();
25+
const terminals = Layer.mock(TerminalManager.TerminalManager)({
26+
open: (input) =>
27+
Effect.succeed({
28+
threadId: input.threadId,
29+
terminalId: input.terminalId ?? terminalId,
30+
cwd: input.cwd,
31+
worktreePath: null,
32+
status: "running",
33+
pid: 123,
34+
history: "",
35+
exitCode: null,
36+
exitSignal: null,
37+
label: "zsh",
38+
updatedAt: "2026-01-01T00:00:00.000Z",
39+
}),
40+
subscribe: (listener) =>
41+
Queue.offer(calls, { type: "subscribe", listener }).pipe(Effect.as(() => {})),
42+
write: (input) => Queue.offer(calls, { type: "write", data: input.data }).pipe(Effect.asVoid),
43+
});
44+
const runner = yield* ProjectSetupScriptRunner.make.pipe(
45+
Effect.provide(
46+
Layer.mergeAll(
47+
terminals,
48+
Layer.mock(ProjectService.ProjectService)({}),
49+
ServerSettings.layerTest(),
50+
NodeCrypto.layer,
51+
),
52+
),
53+
Effect.provideService(HostProcess.Platform, "darwin"),
54+
Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }),
55+
);
56+
const run = yield* runner
57+
.runForThread({
58+
threadId,
59+
worktreePath: "/repo/.t3/worktrees/feature",
60+
project: {
61+
id: ProjectId.make("project-1"),
62+
workspaceRoot: "/repo",
63+
scripts: [
64+
{
65+
id: "setup",
66+
name: "Setup",
67+
command: "vp i",
68+
icon: "configure",
69+
runOnWorktreeCreate: true,
70+
},
71+
],
72+
},
73+
})
74+
.pipe(Effect.forkChild);
75+
const first = yield* Queue.take(calls);
76+
expect(first.type).toBe("subscribe");
77+
const emit = first.type === "subscribe" ? first.listener : () => Effect.void;
78+
const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" };
79+
return { run, calls, emit, event };
80+
});
81+
82+
describe("ProjectSetupScriptRunner", () => {
83+
it.effect("waits for the line editor so a startup prompt cannot read the command", () =>
84+
Effect.gen(function* () {
85+
const { run, calls, emit, event } = yield* setup;
86+
yield* emit({ ...event, type: "output", data: "Do you want to install it? [y/N]: " });
87+
yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
88+
yield* TestClock.adjust("1 minute");
89+
expect(yield* Queue.size(calls)).toBe(0);
90+
91+
yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
92+
yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
93+
yield* Fiber.join(run);
94+
expect(yield* Queue.take(calls)).toEqual({ type: "write", data: " vp i\r" });
95+
}),
96+
);
97+
98+
it.effect("writes to a quiet shell that has no line editor", () =>
99+
Effect.gen(function* () {
100+
const { run, calls } = yield* setup;
101+
yield* TestClock.adjust("2 seconds");
102+
yield* Fiber.join(run);
103+
expect(yield* Queue.take(calls)).toEqual({ type: "write", data: " vp i\r" });
104+
}),
105+
);
106+
});

‎apps/server/src/project/ProjectSetupScriptRunner.ts‎

Lines changed: 76 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,17 @@ function stripTerminalControl(text: string): string {
139139
);
140140
}
141141

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+
const SHELL_QUIET_FALLBACK = "2 seconds";
146+
147+
function lineEditorReading(text: string, previous: boolean): boolean {
148+
const on = text.lastIndexOf(BRACKETED_PASTE_ON);
149+
const off = text.lastIndexOf(BRACKETED_PASTE_OFF);
150+
return on === off ? previous : on > off;
151+
}
152+
142153
type CompletionShell = "posix" | "fish" | "powershell";
143154

144155
function resolveCompletionShell(
@@ -267,6 +278,47 @@ export const make = Effect.gen(function* () {
267278
},
268279
);
269280

281+
// Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the
282+
// shell, which loses the command. Wait for the line editor, or for a quiet shell without one.
283+
const awaitShellReady = Effect.fn("ProjectSetupScriptRunner.awaitShellReady")(function* (input: {
284+
readonly threadId: string;
285+
readonly terminalId: string;
286+
readonly history: string;
287+
}) {
288+
if (lineEditorReading(input.history, false)) return;
289+
const ready = yield* Deferred.make<void>();
290+
let reading = false;
291+
let carry = "";
292+
let busy = false;
293+
let activity = 0;
294+
const unsubscribe = yield* terminalManager.subscribe((event) => {
295+
if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
296+
return Effect.void;
297+
}
298+
activity += 1;
299+
if (event.type === "activity") busy = event.hasRunningSubprocess;
300+
if (event.type === "output") {
301+
const text = carry + event.data;
302+
carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
303+
reading = lineEditorReading(text, reading);
304+
}
305+
const done = reading || event.type === "exited" || event.type === "closed";
306+
return done ? Deferred.succeed(ready, undefined).pipe(Effect.asVoid) : Effect.void;
307+
});
308+
// A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
309+
const quiet = Effect.gen(function* () {
310+
while (true) {
311+
const seen = activity;
312+
yield* Effect.sleep(SHELL_QUIET_FALLBACK);
313+
if (activity === seen && !busy) return;
314+
}
315+
});
316+
yield* Deferred.await(ready).pipe(
317+
Effect.raceFirst(quiet),
318+
Effect.ensuring(Effect.sync(() => unsubscribe())),
319+
);
320+
});
321+
270322
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
271323
"ProjectSetupScriptRunner.runForThread",
272324
)(function* (input) {
@@ -361,7 +413,7 @@ export const make = Effect.gen(function* () {
361413
)
362414
: script.command;
363415

364-
yield* terminalManager
416+
const terminal = yield* terminalManager
365417
.open({
366418
threadId: input.threadId,
367419
terminalId,
@@ -392,23 +444,29 @@ export const make = Effect.gen(function* () {
392444
})
393445
: undefined;
394446

395-
yield* terminalManager
396-
.write({
397-
threadId: input.threadId,
398-
terminalId,
399-
data: projectScriptTerminalInput(commandLine),
400-
})
401-
.pipe(
402-
Effect.mapError(
403-
(cause) =>
404-
new ProjectSetupScriptOperationError({
405-
...errorContext,
406-
operation: "writeCommand",
407-
cause,
408-
}),
409-
),
410-
Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
411-
);
447+
// PowerShell has no line-editor signal; keep its immediate write.
448+
yield* (
449+
completionShell === "powershell"
450+
? Effect.void
451+
: awaitShellReady({ threadId: input.threadId, terminalId, history: terminal.history })
452+
).pipe(
453+
Effect.andThen(
454+
terminalManager.write({
455+
threadId: input.threadId,
456+
terminalId,
457+
data: projectScriptTerminalInput(commandLine),
458+
}),
459+
),
460+
Effect.mapError(
461+
(cause) =>
462+
new ProjectSetupScriptOperationError({
463+
...errorContext,
464+
operation: "writeCommand",
465+
cause,
466+
}),
467+
),
468+
Effect.onError(() => Effect.sync(() => observed?.unsubscribe())),
469+
);
412470

413471
const completion = observed?.completion.pipe(
414472
Effect.tap(({ exitCode }) =>

0 commit comments

Comments
 (0)