Skip to content

Commit 5ac3fba

Browse files
fix(terminal): hold project action input on mobile too
Mobile runs project actions through terminal attach and wrote the command when the first snapshot arrived, so it never reached the queue that terminal.open's initialInput fed. Delivery is now one primitive both clients use: terminal.write takes afterShellStartup, and the server holds such writes, in order, while a shell it just started has not begun reading input. Every shell started by open or attach is watched, so the web and mobile launch paths behave the same. This replaces initialInput and initialInputHandled; a server that predates the flag ignores it and writes at once, as before. Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent 95d415c commit 5ac3fba

7 files changed

Lines changed: 108 additions & 105 deletions

File tree

‎apps/server/src/terminal/Manager.test.ts‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2360,41 +2360,61 @@ it.layer(
23602360
),
23612361
);
23622362

2363-
it.effect("types initial input in order once a fresh shell reads input", () =>
2363+
it.effect("holds startup writes, in order, until a fresh shell reads input", () =>
23642364
Effect.gen(function* () {
23652365
const { manager, ptyAdapter } = yield* createManager();
2366-
const first = yield* manager.open(openInput({ initialInput: "FIRST\r" }));
2367-
const second = yield* manager.open(openInput({ initialInput: "SECOND\r" }));
2366+
const afterStartup = (data: string) =>
2367+
manager.write({
2368+
threadId: "thread-1",
2369+
terminalId: DEFAULT_TERMINAL_ID,
2370+
data,
2371+
afterShellStartup: true,
2372+
});
2373+
yield* manager.open(openInput());
23682374
const shell = ptyAdapter.processes[0]!;
23692375
const secondWritten = yield* Deferred.make<void>();
23702376
shell.onWrite = (data) => {
23712377
if (data === "SECOND\r") Deferred.doneUnsafe(secondWritten, Effect.void);
23722378
};
23732379

2374-
expect([first.initialInputHandled, second.initialInputHandled]).toEqual([true, true]);
2380+
yield* afterStartup("FIRST\r");
2381+
// A second action reopens the running terminal before typing.
2382+
yield* manager.open(openInput());
2383+
yield* afterStartup("SECOND\r");
23752384
expect(shell.writes).toEqual([]);
2385+
// Answering an rc-file prompt must not wait behind the held input.
2386+
yield* manager.write({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, data: "y\r" });
2387+
expect(shell.writes).toEqual(["y\r"]);
23762388

23772389
shell.emitData("\x1b[?2004h$ ");
23782390
yield* Deferred.await(secondWritten);
2379-
expect(shell.writes).toEqual(["FIRST\r", "SECOND\r"]);
2391+
expect(shell.writes).toEqual(["y\r", "FIRST\r", "SECOND\r"]);
23802392

2381-
const third = yield* manager.open(openInput({ initialInput: "THIRD\r" }));
2382-
expect(third.initialInputHandled).toBe(true);
2383-
expect(shell.writes).toEqual(["FIRST\r", "SECOND\r", "THIRD\r"]);
2393+
yield* afterStartup("THIRD\r");
2394+
expect(shell.writes).toEqual(["y\r", "FIRST\r", "SECOND\r", "THIRD\r"]);
23842395
expect(ptyAdapter.spawnInputs).toHaveLength(1);
23852396
}),
23862397
);
23872398

2388-
it.effect("drops initial input waiting for a shell that open replaced", () =>
2399+
it.effect("drops startup writes held for a shell that open replaced", () =>
23892400
Effect.gen(function* () {
23902401
const { manager, ptyAdapter, baseDir } = yield* createManager(5, { processKillGraceMs: 0 });
23912402
const path = yield* Path.Path;
23922403
const fs = yield* FileSystem.FileSystem;
23932404
const replacementCwd = path.join(baseDir, "replacement");
23942405
yield* fs.makeDirectory(replacementCwd, { recursive: true });
2406+
const afterStartup = (data: string) =>
2407+
manager.write({
2408+
threadId: "thread-1",
2409+
terminalId: DEFAULT_TERMINAL_ID,
2410+
data,
2411+
afterShellStartup: true,
2412+
});
23952413

2396-
yield* manager.open(openInput({ initialInput: "OLD\r" }));
2397-
yield* manager.open(openInput({ cwd: replacementCwd, initialInput: "NEW\r" }));
2414+
yield* manager.open(openInput());
2415+
yield* afterStartup("OLD\r");
2416+
yield* manager.open(openInput({ cwd: replacementCwd }));
2417+
yield* afterStartup("NEW\r");
23982418
const replacement = ptyAdapter.processes[1]!;
23992419
const written = yield* Deferred.make<void>();
24002420
replacement.onWrite = () => Deferred.doneUnsafe(written, Effect.void);
@@ -2405,16 +2425,21 @@ it.layer(
24052425
}),
24062426
);
24072427

2408-
it.effect("types initial input into PowerShell without waiting for a line editor", () =>
2428+
it.effect("types a startup write into PowerShell without waiting for a line editor", () =>
24092429
Effect.gen(function* () {
24102430
const { manager, ptyAdapter } = yield* createManager(5, {
24112431
env: { PATH: "C:\\Windows\\System32", SystemRoot: "C:\\Windows" },
24122432
}).pipe(Effect.provide(layerWithHostPlatform("win32")));
24132433

2414-
const opened = yield* manager.open(openInput({ initialInput: "npm run dev\r" }));
2434+
yield* manager.open(openInput());
2435+
yield* manager.write({
2436+
threadId: "thread-1",
2437+
terminalId: DEFAULT_TERMINAL_ID,
2438+
data: "npm run dev\r",
2439+
afterShellStartup: true,
2440+
});
24152441

24162442
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("pwsh.exe");
2417-
expect(opened.initialInputHandled).toBe(true);
24182443
expect(ptyAdapter.processes[0]?.writes).toEqual(["npm run dev\r"]);
24192444
}),
24202445
);

‎apps/server/src/terminal/Manager.ts‎

Lines changed: 37 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,8 @@ interface TerminalSessionState {
320320
childCommandLabel: string | null;
321321
runtimeEnv: Record<string, string> | null;
322322
stopOnSettle: boolean;
323-
/** Input waiting for the current shell to read; null once that shell takes writes directly. */
324-
pendingInitialInputs: Array<string> | null;
323+
/** Writes waiting for the current shell to read input; null once it takes them directly. */
324+
heldWrites: Array<string> | null;
325325
}
326326

327327
interface TerminalGrid {
@@ -2446,7 +2446,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
24462446
session.hasRunningSubprocess = false;
24472447
session.childCommandLabel = null;
24482448
session.status = "exited";
2449-
session.pendingInitialInputs = null;
2449+
session.heldWrites = null;
24502450
session.pendingHistoryControlSequence = "";
24512451
session.pendingProcessEvents = [];
24522452
session.pendingProcessEventIndex = 0;
@@ -2544,7 +2544,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
25442544
yield* modifyManagerState((state) => {
25452545
session.status = "starting";
25462546
session.shell = null;
2547-
session.pendingInitialInputs = null;
2547+
session.heldWrites = null;
25482548
session.cwd = input.cwd;
25492549
session.worktreePath = input.worktreePath ?? null;
25502550
session.cols = input.cols;
@@ -2954,16 +2954,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
29542954
);
29552955

29562956
// Input typed while a shell starts can be read by an rc-file prompt (fnm, nvm) instead of the
2957-
// shell, so it waits for the line editor. The queue keeps later opens behind it, in order.
2957+
// shell. Writes that ask to wait are held, in order, until the line editor reads input.
29582958
const startOpenedSession = Effect.fn("terminal.startOpenedSession")(function* (
29592959
session: TerminalSessionState,
29602960
startInput: TerminalStartInput,
2961-
initialInput: string | undefined,
29622961
) {
2963-
if (initialInput === undefined) {
2964-
yield* startSession(session, startInput, "started");
2965-
return snapshot(session);
2966-
}
29672962
const target = { threadId: session.threadId, terminalId: session.terminalId };
29682963
// Subscribed before the spawn so no startup output is missed.
29692964
const readiness = yield* watchShellReadiness({
@@ -2975,33 +2970,33 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
29752970
Effect.onError(() => Effect.sync(readiness.unsubscribe)),
29762971
);
29772972
const spawned = session.process;
2978-
if (session.status !== "running" || spawned === null || session.shell === null) {
2973+
if (
2974+
session.status !== "running" ||
2975+
spawned === null ||
2976+
session.shell === null ||
2977+
!shellSignalsLineEditor(session.shell)
2978+
) {
29792979
readiness.unsubscribe();
29802980
return snapshot(session);
29812981
}
2982-
if (!shellSignalsLineEditor(session.shell)) {
2983-
readiness.unsubscribe();
2984-
yield* write({ ...target, data: initialInput });
2985-
return { ...snapshot(session), initialInputHandled: true };
2986-
}
2987-
const queued = [initialInput];
2988-
session.pendingInitialInputs = queued;
2982+
const held: Array<string> = [];
2983+
session.heldWrites = held;
29892984
yield* readiness.wait.pipe(
29902985
Effect.flatMap((outcome) => {
2991-
// A restart or exit already dropped the queue: the input belonged to the shell it was opened for.
2992-
if (session.pendingInitialInputs !== queued) return Effect.void;
2993-
session.pendingInitialInputs = null;
2986+
// A restart or exit already dropped the queue: the input belonged to the shell it was typed for.
2987+
if (session.heldWrites !== held) return Effect.void;
2988+
session.heldWrites = null;
29942989
return outcome === "exited" || session.process !== spawned
29952990
? Effect.void
2996-
: Effect.forEach(queued, (data) => write({ ...target, data }), { discard: true });
2991+
: Effect.forEach(held, (data) => write({ ...target, data }), { discard: true });
29972992
}),
29982993
Effect.catchCause((cause) =>
2999-
Effect.logWarning("terminal initial input was not written", { ...target, cause }),
2994+
Effect.logWarning("terminal held input was not written", { ...target, cause }),
30002995
),
30012996
Effect.ensuring(Effect.sync(readiness.unsubscribe)),
30022997
Effect.forkIn(workerScope),
30032998
);
3004-
return { ...snapshot(session), initialInputHandled: true };
2999+
return snapshot(session);
30053000
});
30063001

30073002
const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* (
@@ -3054,7 +3049,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
30543049
childCommandLabel: null,
30553050
runtimeEnv: normalizedRuntimeEnv(input.env),
30563051
stopOnSettle: input.stopOnSettle ?? false,
3057-
pendingInitialInputs: null,
3052+
heldWrites: null,
30583053
};
30593054

30603055
const createdSession = session;
@@ -3066,16 +3061,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
30663061
});
30673062

30683063
yield* evictInactiveSessionsIfNeeded();
3069-
return yield* startOpenedSession(
3070-
session,
3071-
{
3072-
cwd: input.cwd,
3073-
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
3074-
cols,
3075-
rows,
3076-
},
3077-
input.initialInput,
3078-
);
3064+
return yield* startOpenedSession(session, {
3065+
cwd: input.cwd,
3066+
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
3067+
cols,
3068+
rows,
3069+
});
30793070
}
30803071

30813072
const liveSession = existing.value;
@@ -3115,34 +3106,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
31153106
}
31163107

31173108
if (!liveSession.process) {
3118-
return yield* startOpenedSession(
3119-
liveSession,
3120-
{
3121-
cwd: input.cwd,
3122-
worktreePath: liveSession.worktreePath,
3123-
cols: targetCols,
3124-
rows: targetRows,
3125-
},
3126-
input.initialInput,
3127-
);
3109+
return yield* startOpenedSession(liveSession, {
3110+
cwd: input.cwd,
3111+
worktreePath: liveSession.worktreePath,
3112+
cols: targetCols,
3113+
rows: targetRows,
3114+
});
31283115
}
31293116

31303117
if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
31313118
yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows);
31323119
}
31333120

3134-
if (input.initialInput === undefined) return snapshot(liveSession);
3135-
// Behind input still waiting for this shell, so a second action cannot overtake the first.
3136-
if (liveSession.pendingInitialInputs !== null) {
3137-
liveSession.pendingInitialInputs.push(input.initialInput);
3138-
} else {
3139-
yield* write({
3140-
threadId: liveSession.threadId,
3141-
terminalId: liveSession.terminalId,
3142-
data: input.initialInput,
3143-
});
3144-
}
3145-
return { ...snapshot(liveSession), initialInputHandled: true };
3121+
return snapshot(liveSession);
31463122
});
31473123

31483124
const openLocked = (input: TerminalOpenInput) =>
@@ -3538,6 +3514,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
35383514
terminalId,
35393515
});
35403516
}
3517+
if (input.afterShellStartup === true && session.heldWrites !== null) {
3518+
session.heldWrites.push(input.data);
3519+
return;
3520+
}
35413521
session.inputCount += 1;
35423522
yield* Effect.try({
35433523
try: () => process.write(input.data),

‎apps/web/src/components/chat/useChatTerminalActions.ts‎

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -244,10 +244,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
244244
return;
245245
}
246246

247-
const scriptInput =
248-
options?.shellHistory === "preserve"
249-
? `${script.command}\r`
250-
: projectScriptTerminalInput(script.command);
251247
const launched = terminalActions.launchTerminal({
252248
// The drawer opens with the target already placed: opening it empty would claim
253249
// DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own.
@@ -261,8 +257,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
261257
location: { cwd: targetCwd, worktreePath: targetWorktreePath },
262258
stopOnSettle: script.stopOnSettle ?? false,
263259
...(options?.env ? { extraEnv: options.env } : {}),
264-
// The open schema caps input; a longer command takes the write path below, as before.
265-
...(scriptInput.length <= 65_536 ? { initialInput: scriptInput } : {}),
266260
});
267261
if (!launched) return;
268262
const targetTerminalId = launched.terminalId;
@@ -279,20 +273,23 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
279273
return;
280274
}
281275

282-
// A server that predates initialInput leaves it to the client.
283-
if (openResult.value.initialInputHandled !== true) {
284-
const writeResult = await terminalActions.writeToTerminal(targetTerminalId, scriptInput);
285-
if (!writeResult) return;
286-
if (writeResult._tag === "Failure") {
287-
if (!isAtomCommandInterrupted(writeResult)) {
288-
const error = squashAtomCommandFailure(writeResult);
289-
setThreadError(
290-
activeThreadId,
291-
error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
292-
);
293-
}
294-
return;
276+
const writeResult = await terminalActions.writeToTerminal(
277+
targetTerminalId,
278+
options?.shellHistory === "preserve"
279+
? `${script.command}\r`
280+
: projectScriptTerminalInput(script.command),
281+
{ afterShellStartup: true },
282+
);
283+
if (!writeResult) return;
284+
if (writeResult._tag === "Failure") {
285+
if (!isAtomCommandInterrupted(writeResult)) {
286+
const error = squashAtomCommandFailure(writeResult);
287+
setThreadError(
288+
activeThreadId,
289+
error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
290+
);
295291
}
292+
return;
296293
}
297294
if (
298295
script.autoOpenPreview &&

‎apps/web/src/components/terminal/useThreadTerminalActions.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,6 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
8989
readonly extraEnv?: Record<string, string>;
9090
readonly stopOnSettle?: boolean;
9191
readonly size?: { readonly cols: number; readonly rows: number };
92-
/** The server types this once the shell reads input; see `initialInputHandled` on the result. */
93-
readonly initialInput?: string;
9492
}) => {
9593
if (!threadRef || !canWrite() || !project) return null;
9694
const location = input.location ?? defaultLaunchLocation();
@@ -111,7 +109,6 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
111109
}),
112110
...input.size,
113111
...(input.stopOnSettle !== undefined ? { stopOnSettle: input.stopOnSettle } : {}),
114-
...(input.initialInput !== undefined ? { initialInput: input.initialInput } : {}),
115112
},
116113
});
117114
return { terminalId, result };
@@ -137,11 +134,16 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
137134
})();
138135
};
139136

140-
const writeToTerminal = (terminalId: string, data: string) => {
137+
/** afterShellStartup has the server hold the input until a starting shell reads it. */
138+
const writeToTerminal = (
139+
terminalId: string,
140+
data: string,
141+
options?: { readonly afterShellStartup: boolean },
142+
) => {
141143
if (!threadRef || !canWrite()) return null;
142144
return writeTerminal({
143145
environmentId: threadRef.environmentId,
144-
input: { threadId: threadRef.threadId, terminalId, data },
146+
input: { threadId: threadRef.threadId, terminalId, data, ...options },
145147
});
146148
};
147149

‎packages/client-runtime/src/state/terminal.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,13 +154,15 @@ it("replays the measured grid on every new attachment generation", () => {
154154
]);
155155
});
156156

157-
it("writes the launch's initial input once the first snapshot lands", () => {
157+
it("sends the launch's initial input once, for the server to type after shell startup", () => {
158158
const { attached, emit, mount, calls, of } = setup({ initialInput: "pnpm dev\r" });
159159
mount(attached);
160160
expect(of("write")).toEqual([]);
161161
emit({ status: "running", version: 1 });
162162
emit({ status: "running", version: 2 });
163-
expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "pnpm dev\r" }]);
163+
expect(of("write")).toEqual([
164+
{ threadId, terminalId: "term-1", data: "pnpm dev\r", afterShellStartup: true },
165+
]);
164166
// The shell gets the measured grid before the launched command runs.
165167
expect(calls.map((call) => call.command)).toEqual(["resize", "write"]);
166168
});

0 commit comments

Comments
 (0)