Skip to content

Commit c2cfce4

Browse files
t3dotggclaude
andcommitted
fix(server): show the setup terminal while a startup prompt waits
Review follow-ups: - Return once the terminal opens and type in the background, so the setup card offers Open terminal and the agent start is not delayed. - Show a waiting prompt line that has no newline in the setup output. - Subscribe before opening so early subprocess activity is not lost. - Do not type into a shell that exited during startup. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 869b6e5 commit c2cfce4

2 files changed

Lines changed: 157 additions & 115 deletions

File tree

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

Lines changed: 54 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { describe, expect, it } from "@effect/vitest";
33
import { ProjectId, type TerminalEvent } from "@t3tools/contracts";
44
import * as HostProcess from "@t3tools/shared/HostProcess";
55
import * as Effect from "effect/Effect";
6-
import * as Fiber from "effect/Fiber";
76
import * as Layer from "effect/Layer";
87
import * as Queue from "effect/Queue";
98
import { TestClock } from "effect/testing";
@@ -15,13 +14,12 @@ import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
1514

1615
const threadId = "thread-1";
1716
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 };
17+
const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" };
2218

2319
const setup = Effect.gen(function* () {
24-
const calls = yield* Queue.unbounded<TerminalCall>();
20+
const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
21+
const writes = yield* Queue.unbounded<string>();
22+
const outputLines = yield* Queue.unbounded<string>();
2523
const terminals = Layer.mock(TerminalManager.TerminalManager)({
2624
open: (input) =>
2725
Effect.succeed({
@@ -38,8 +36,12 @@ const setup = Effect.gen(function* () {
3836
updatedAt: "2026-01-01T00:00:00.000Z",
3937
}),
4038
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),
39+
Effect.sync(() => {
40+
listeners.add(listener);
41+
return () => listeners.delete(listener);
42+
}),
43+
write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
44+
closeIdle: () => Effect.void,
4345
});
4446
const runner = yield* ProjectSetupScriptRunner.make.pipe(
4547
Effect.provide(
@@ -53,54 +55,64 @@ const setup = Effect.gen(function* () {
5355
Effect.provideService(HostProcess.Platform, "darwin"),
5456
Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }),
5557
);
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 };
58+
const result = yield* runner.runForThread({
59+
threadId,
60+
worktreePath: "/repo/.t3/worktrees/feature",
61+
observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
62+
project: {
63+
id: ProjectId.make("project-1"),
64+
workspaceRoot: "/repo",
65+
scripts: [
66+
{
67+
id: "setup",
68+
name: "Setup",
69+
command: "vp i",
70+
icon: "configure",
71+
runOnWorktreeCreate: true,
72+
},
73+
],
74+
},
75+
});
76+
const completion = result.status === "started" ? result.completion : undefined;
77+
if (!completion) return yield* Effect.die("setup did not start an observed run");
78+
const emit = (terminalEvent: TerminalEvent) =>
79+
Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
80+
return { result, completion, writes, outputLines, emit };
8081
});
8182

8283
describe("ProjectSetupScriptRunner", () => {
83-
it.effect("waits for the line editor so a startup prompt cannot read the command", () =>
84+
it.effect("shows a startup prompt and types only once the line editor starts", () =>
8485
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]: " });
86+
const { result, writes, outputLines, emit } = yield* setup;
87+
expect(result).toMatchObject({ status: "started", terminalId });
88+
89+
yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
8790
yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
8891
yield* TestClock.adjust("1 minute");
89-
expect(yield* Queue.size(calls)).toBe(0);
92+
expect(yield* Queue.size(writes)).toBe(0);
93+
expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
9094

9195
yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
9296
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" });
97+
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
9598
}),
9699
);
97100

98-
it.effect("writes to a quiet shell that has no line editor", () =>
101+
it.effect("types into a quiet shell that has no line editor", () =>
99102
Effect.gen(function* () {
100-
const { run, calls } = yield* setup;
103+
const { writes } = yield* setup;
101104
yield* TestClock.adjust("2 seconds");
102-
yield* Fiber.join(run);
103-
expect(yield* Queue.take(calls)).toEqual({ type: "write", data: " vp i\r" });
105+
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
106+
}),
107+
);
108+
109+
it.effect("does not type into a shell that exits during startup", () =>
110+
Effect.gen(function* () {
111+
const { completion, writes, emit } = yield* setup;
112+
yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
113+
expect(yield* completion).toMatchObject({ exitCode: null });
114+
yield* TestClock.adjust("1 minute");
115+
expect(yield* Queue.size(writes)).toBe(0);
104116
}),
105117
);
106118
});

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

Lines changed: 103 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export class ProjectSetupScriptOperationError extends Schema.TaggedError<Project
7474
projectId: Schema.optional(Schema.String),
7575
projectCwd: Schema.optional(Schema.String),
7676
worktreePath: Schema.String,
77-
operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal", "writeCommand"]),
77+
operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal"]),
7878
cause: Schema.Defect(),
7979
},
8080
) {
@@ -187,6 +187,7 @@ export const make = Effect.gen(function* () {
187187
const terminalManager = yield* TerminalManager.TerminalManager;
188188
const serverSettings = yield* ServerSettings.ServerSettingsService;
189189
const crypto = yield* Crypto.Crypto;
190+
const serviceScope = yield* Effect.scope;
190191
const completionShell = resolveCompletionShell(
191192
yield* HostProcess.Platform,
192193
yield* HostProcess.Environment,
@@ -274,50 +275,66 @@ export const make = Effect.gen(function* () {
274275
Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),
275276
Effect.ensuring(Effect.sync(() => unsubscribe())),
276277
);
277-
return { completion, unsubscribe };
278+
// A startup prompt waits for input on a line that has no newline yet.
279+
const flushPartialLine = Effect.suspend(() => {
280+
const partial = lineBuffer;
281+
lineBuffer = "";
282+
return handleLine(partial);
283+
});
284+
const abandon = settle(null).pipe(
285+
Effect.andThen(Deferred.succeed(promptReturned, undefined)),
286+
);
287+
return { completion, unsubscribe, flushPartialLine, abandon };
278288
},
279289
);
280290

281291
// 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-
});
292+
// shell, which loses the command. Subscribe before the terminal opens so no activity is missed.
293+
const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")(
294+
function* (input: {
295+
readonly threadId: string;
296+
readonly terminalId: string;
297+
readonly onStartupPrompt: Effect.Effect<void>;
298+
}) {
299+
const outcome = yield* Deferred.make<"ready" | "exited">();
300+
let reading = false;
301+
let carry = "";
302+
let busy = false;
303+
let activity = 0;
304+
const unsubscribe = yield* terminalManager.subscribe((event) => {
305+
if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
306+
return Effect.void;
307+
}
308+
activity += 1;
309+
if (event.type === "activity") busy = event.hasRunningSubprocess;
310+
if (event.type === "output") {
311+
const text = carry + event.data;
312+
carry = text.slice(-(BRACKETED_PASTE_ON.length - 1));
313+
reading = lineEditorReading(text, reading);
314+
}
315+
if (event.type === "exited" || event.type === "closed") {
316+
return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid);
317+
}
318+
return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void;
319+
});
320+
// A startup prompt runs as a child process, so a busy shell keeps waiting for the user.
321+
const quiet = Effect.gen(function* () {
322+
while (true) {
323+
const seen = activity;
324+
yield* Effect.sleep(SHELL_QUIET_FALLBACK);
325+
if (activity !== seen) continue;
326+
if (!busy) return "ready" as const;
327+
yield* input.onStartupPrompt;
328+
}
329+
});
330+
const wait = (history: string) =>
331+
(lineEditorReading(history, false)
332+
? Effect.succeed("ready" as const)
333+
: Deferred.await(outcome).pipe(Effect.raceFirst(quiet))
334+
).pipe(Effect.ensuring(Effect.sync(() => unsubscribe())));
335+
return { wait, unsubscribe };
336+
},
337+
);
321338

322339
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
323340
"ProjectSetupScriptRunner.runForThread",
@@ -413,6 +430,28 @@ export const make = Effect.gen(function* () {
413430
)
414431
: script.command;
415432

433+
// Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
434+
const observed =
435+
observe && completionToken
436+
? yield* observeTerminalCompletion({
437+
threadId: input.threadId,
438+
terminalId,
439+
sentinel: completionSentinel(completionToken),
440+
sentinelPattern: completionSentinelPattern(completionToken),
441+
echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
442+
onOutputLine: observe.onOutputLine,
443+
})
444+
: undefined;
445+
// PowerShell has no line-editor signal; keep its immediate write.
446+
const readiness =
447+
completionShell === "powershell"
448+
? undefined
449+
: yield* watchShellReadiness({
450+
threadId: input.threadId,
451+
terminalId,
452+
onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
453+
});
454+
416455
const terminal = yield* terminalManager
417456
.open({
418457
threadId: input.threadId,
@@ -430,42 +469,33 @@ export const make = Effect.gen(function* () {
430469
cause,
431470
}),
432471
),
472+
Effect.tapError(() =>
473+
Effect.sync(() => {
474+
observed?.unsubscribe();
475+
readiness?.unsubscribe();
476+
}),
477+
),
433478
);
434-
// Subscribe before writing so the sentinel cannot race past the listener.
435-
const observed =
436-
observe && completionToken
437-
? yield* observeTerminalCompletion({
438-
threadId: input.threadId,
439-
terminalId,
440-
sentinel: completionSentinel(completionToken),
441-
sentinelPattern: completionSentinelPattern(completionToken),
442-
echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
443-
onOutputLine: observe.onOutputLine,
444-
})
445-
: undefined;
446479

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-
}),
480+
// Return once the terminal exists so callers can show it while a startup prompt waits.
481+
yield* (readiness?.wait(terminal.history) ?? Effect.succeed("ready" as const)).pipe(
482+
Effect.flatMap((shell) =>
483+
shell === "exited"
484+
? Effect.void
485+
: terminalManager.write({
486+
threadId: input.threadId,
487+
terminalId,
488+
data: projectScriptTerminalInput(commandLine),
489+
}),
459490
),
460-
Effect.mapError(
461-
(cause) =>
462-
new ProjectSetupScriptOperationError({
463-
...errorContext,
464-
operation: "writeCommand",
465-
cause,
466-
}),
491+
Effect.catchCause((cause) =>
492+
Effect.logWarning("project script command was not written", {
493+
...errorContext,
494+
terminalId,
495+
cause,
496+
}).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
467497
),
468-
Effect.onError(() => Effect.sync(() => observed?.unsubscribe())),
498+
Effect.forkIn(serviceScope),
469499
);
470500

471501
const completion = observed?.completion.pipe(

0 commit comments

Comments
 (0)