Skip to content

Commit c657e54

Browse files
fix(terminal): run project actions after shell startup
Project actions typed the command into a fresh terminal before the interactive shell was reading, so shell startup could eat the command and leave it stuck above the prompt (#6337). Pass the command to the shell as an initial command for zsh, bash, and sh, then re-enter the interactive shell when it finishes. Clients fall back to the old write path for older servers, unsupported shells, and already-running terminals. Fixes #6337. Co-Authored-By: Claude Code <[email protected]>
1 parent 4f0b74e commit c657e54

6 files changed

Lines changed: 187 additions & 21 deletions

File tree

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

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,91 @@ it.layer(
431431
}),
432432
);
433433

434+
it.effect("runs an initial command during fresh shell startup", () =>
435+
Effect.gen(function* () {
436+
const { manager, ptyAdapter } = yield* createManager(5, {
437+
shellResolver: () => "/bin/zsh",
438+
});
439+
440+
const snapshot = yield* manager.open(openInput({ initialCommand: "npm run dev" }));
441+
442+
expect(ptyAdapter.spawnInputs[0]?.args).toEqual([
443+
"-o",
444+
"nopromptsp",
445+
"-i",
446+
"-c",
447+
"trap ':' INT\nnpm run dev\nexec '/bin/zsh' '-o' 'nopromptsp'",
448+
]);
449+
expect(ptyAdapter.processes[0]?.writes).toEqual([]);
450+
expect(snapshot.initialCommandHandled).toBe(true);
451+
}),
452+
);
453+
454+
it.effect("leaves an initial command unhandled for an existing shell", () =>
455+
Effect.gen(function* () {
456+
const { manager, ptyAdapter } = yield* createManager();
457+
yield* manager.open(openInput());
458+
459+
const snapshot = yield* manager.open(openInput({ initialCommand: "npm run dev" }));
460+
461+
expect(ptyAdapter.spawnInputs).toHaveLength(1);
462+
expect(ptyAdapter.processes[0]?.writes).toEqual([]);
463+
expect(snapshot.initialCommandHandled).toBeUndefined();
464+
}),
465+
);
466+
467+
it.effect("handles an initial command when open restarts a running session", () =>
468+
Effect.gen(function* () {
469+
const { manager, ptyAdapter, baseDir } = yield* createManager(5, {
470+
shellResolver: () => "/bin/zsh",
471+
});
472+
const path = yield* Path.Path;
473+
const fs = yield* FileSystem.FileSystem;
474+
const originalCwd = path.join(baseDir, "original");
475+
const differentCwd = path.join(baseDir, "different");
476+
yield* fs.makeDirectory(originalCwd, { recursive: true });
477+
yield* fs.makeDirectory(differentCwd, { recursive: true });
478+
479+
yield* manager.open(openInput({ cwd: originalCwd }));
480+
const reopened = yield* manager.open(
481+
openInput({ cwd: differentCwd, initialCommand: "npm run dev" }),
482+
);
483+
484+
expect(ptyAdapter.spawnInputs).toHaveLength(2);
485+
expect(ptyAdapter.spawnInputs[1]?.args).toEqual([
486+
"-o",
487+
"nopromptsp",
488+
"-i",
489+
"-c",
490+
"trap ':' INT\nnpm run dev\nexec '/bin/zsh' '-o' 'nopromptsp'",
491+
]);
492+
expect(reopened.initialCommandHandled).toBe(true);
493+
expect(reopened.cwd).toBe(differentCwd);
494+
}),
495+
);
496+
497+
it.effect("leaves a Windows shell unchanged for an initial command", () =>
498+
Effect.gen(function* () {
499+
const { manager, ptyAdapter } = yield* createManager(5, {
500+
env: {
501+
PATH: "C:\\Windows\\System32",
502+
SystemRoot: "C:\\Windows",
503+
},
504+
}).pipe(Effect.provide(layerWithHostPlatform("win32")));
505+
506+
const snapshot = yield* manager.open(openInput({ initialCommand: "npm run dev" }));
507+
508+
expect(ptyAdapter.spawnInputs[0]).toEqual(
509+
expect.objectContaining({
510+
shell: "pwsh.exe",
511+
args: ["-NoLogo"],
512+
}),
513+
);
514+
expect(ptyAdapter.processes[0]?.writes).toEqual([]);
515+
expect(snapshot.initialCommandHandled).toBeUndefined();
516+
}),
517+
);
518+
434519
it.effect("keeps attach streams live when a terminal id is closed and reopened", () =>
435520
Effect.gen(function* () {
436521
const { manager, ptyAdapter } = yield* createManager();

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

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,7 @@ interface TerminalStartInput {
278278
readonly worktreePath?: string | null;
279279
readonly cols: number;
280280
readonly rows: number;
281+
readonly initialCommand?: string;
281282
}
282283

283284
interface TerminalSessionState {
@@ -405,6 +406,16 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
405406
};
406407
}
407408

409+
function openSnapshot(
410+
session: TerminalSessionState,
411+
initialCommandHandled: boolean,
412+
): TerminalSessionSnapshot {
413+
const current = snapshot(session);
414+
return initialCommandHandled && session.status === "running"
415+
? { ...current, initialCommandHandled: true }
416+
: current;
417+
}
418+
408419
function summary(session: TerminalSessionState): TerminalSummary {
409420
return {
410421
threadId: session.threadId,
@@ -596,6 +607,33 @@ function formatShellCandidate(candidate: ShellCandidate): string {
596607
return `${candidate.shell} ${candidate.args.join(" ")}`;
597608
}
598609

610+
function quotePosixShellArgument(value: string): string {
611+
return `'${value.replaceAll("'", `'\\''`)}'`;
612+
}
613+
614+
function posixShellCandidateWithInitialCommand(
615+
candidate: ShellCandidate,
616+
initialCommand: string,
617+
): ShellCandidate {
618+
const baseArgs = candidate.args ?? [];
619+
const reenterShell = [candidate.shell, ...baseArgs].map(quotePosixShellArgument).join(" ");
620+
return {
621+
shell: candidate.shell,
622+
args: [...baseArgs, "-i", "-c", `trap ':' INT\n${initialCommand}\nexec ${reenterShell}`],
623+
};
624+
}
625+
626+
function supportsPosixInitialCommand(
627+
candidates: ReadonlyArray<ShellCandidate>,
628+
platform: NodeJS.Platform,
629+
): boolean {
630+
if (platform === "win32") return false;
631+
return candidates.every((candidate) => {
632+
const shellName = basenameForPlatform(candidate.shell, platform).toLowerCase();
633+
return shellName === "zsh" || shellName === "bash" || shellName === "sh";
634+
});
635+
}
636+
599637
function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
600638
const seen = new Set<string>();
601639
const ordered: ShellCandidate[] = [];
@@ -2438,12 +2476,28 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
24382476

24392477
let ptyProcess: PtyAdapter.PtyProcess | null = null;
24402478
let startedShell: string | null = null;
2479+
let initialCommandHandled = false;
24412480

24422481
const startResult = yield* Effect.result(
24432482
increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(
24442483
Effect.andThen(
24452484
Effect.gen(function* () {
2446-
const shellCandidates = resolveShellCandidates(shellResolver, platform, baseEnv);
2485+
const resolvedShellCandidates = resolveShellCandidates(
2486+
shellResolver,
2487+
platform,
2488+
baseEnv,
2489+
);
2490+
const initialCommand = input.initialCommand;
2491+
let shellCandidates = resolvedShellCandidates;
2492+
if (
2493+
initialCommand !== undefined &&
2494+
supportsPosixInitialCommand(resolvedShellCandidates, platform)
2495+
) {
2496+
initialCommandHandled = true;
2497+
shellCandidates = resolvedShellCandidates.map((candidate) =>
2498+
posixShellCandidateWithInitialCommand(candidate, initialCommand),
2499+
);
2500+
}
24472501
const terminalEnv = createTerminalSpawnEnv(
24482502
baseEnv,
24492503
session.runtimeEnv,
@@ -2531,7 +2585,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
25312585
);
25322586

25332587
if (startResult._tag === "Success") {
2534-
return;
2588+
return initialCommandHandled;
25352589
}
25362590

25372591
{
@@ -2574,6 +2628,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
25742628
cause: error,
25752629
...(startedShell ? { shell: startedShell } : {}),
25762630
});
2631+
return false;
25772632
}
25782633
});
25792634

@@ -2890,17 +2945,18 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
28902945
});
28912946

28922947
yield* evictInactiveSessionsIfNeeded();
2893-
yield* startSession(
2948+
const initialCommandHandled = yield* startSession(
28942949
session,
28952950
{
28962951
cwd: input.cwd,
28972952
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
28982953
cols,
28992954
rows,
2955+
...(input.initialCommand ? { initialCommand: input.initialCommand } : {}),
29002956
},
29012957
"started",
29022958
);
2903-
return snapshot(session);
2959+
return openSnapshot(session, initialCommandHandled);
29042960
}
29052961

29062962
const liveSession = existing.value;
@@ -2940,17 +2996,18 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
29402996
}
29412997

29422998
if (!liveSession.process) {
2943-
yield* startSession(
2999+
const initialCommandHandled = yield* startSession(
29443000
liveSession,
29453001
{
29463002
cwd: input.cwd,
29473003
worktreePath: liveSession.worktreePath,
29483004
cols: targetCols,
29493005
rows: targetRows,
3006+
...(input.initialCommand ? { initialCommand: input.initialCommand } : {}),
29503007
},
29513008
"started",
29523009
);
2953-
return snapshot(liveSession);
3010+
return openSnapshot(liveSession, initialCommandHandled);
29543011
}
29553012

29563013
if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {

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

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
257257
location: { cwd: targetCwd, worktreePath: targetWorktreePath },
258258
stopOnSettle: script.stopOnSettle ?? false,
259259
...(options?.env ? { extraEnv: options.env } : {}),
260+
initialCommand: script.command,
260261
});
261262
if (!launched) return;
262263
const targetTerminalId = launched.terminalId;
@@ -273,22 +274,27 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
273274
return;
274275
}
275276

276-
const writeResult = await terminalActions.writeToTerminal(
277-
targetTerminalId,
278-
options?.shellHistory === "preserve"
279-
? `${script.command}\r`
280-
: projectScriptTerminalInput(script.command),
281-
);
282-
if (!writeResult) return;
283-
if (writeResult._tag === "Failure") {
284-
if (!isAtomCommandInterrupted(writeResult)) {
285-
const error = squashAtomCommandFailure(writeResult);
286-
setThreadError(
287-
activeThreadId,
288-
error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
289-
);
277+
// Older remote servers ignore the optional initialCommand field. Keep project
278+
// actions working across version skew, even though only newer servers avoid the
279+
// fresh-shell startup race.
280+
if (openResult.value.initialCommandHandled !== true) {
281+
const writeResult = await terminalActions.writeToTerminal(
282+
targetTerminalId,
283+
options?.shellHistory === "preserve"
284+
? `${script.command}\r`
285+
: projectScriptTerminalInput(script.command),
286+
);
287+
if (!writeResult) return;
288+
if (writeResult._tag === "Failure") {
289+
if (!isAtomCommandInterrupted(writeResult)) {
290+
const error = squashAtomCommandFailure(writeResult);
291+
setThreadError(
292+
activeThreadId,
293+
error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
294+
);
295+
}
296+
return;
290297
}
291-
return;
292298
}
293299
if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) {
294300
const previewResult = await openUrlInPreview({

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ 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+
readonly initialCommand?: string;
9293
}) => {
9394
if (!threadRef || !canWrite() || !project) return null;
9495
const location = input.location ?? defaultLaunchLocation();
@@ -109,6 +110,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
109110
}),
110111
...input.size,
111112
...(input.stopOnSettle !== undefined ? { stopOnSettle: input.stopOnSettle } : {}),
113+
...(input.initialCommand !== undefined ? { initialCommand: input.initialCommand } : {}),
112114
},
113115
});
114116
return { terminalId, result };

‎packages/contracts/src/terminal.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,14 @@ describe("TerminalOpenInput", () => {
4848
});
4949
expect(parsed.env).toEqual({ GOOD_KEY: "2" });
5050
});
51+
52+
it("accepts an initial command", () => {
53+
const parsed = decodeSync(TerminalOpenInput, {
54+
threadId: "thread-1",
55+
terminalId: DEFAULT_TERMINAL_ID,
56+
cwd: "/tmp/project",
57+
initialCommand: "npm run dev",
58+
});
59+
expect(parsed.initialCommand).toBe("npm run dev");
60+
});
5161
});

‎packages/contracts/src/terminal.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ export const TerminalOpenInput = Schema.Struct({
4242
env: Schema.optional(TerminalEnvSchema),
4343
providerInstanceId: Schema.optional(ProviderInstanceId),
4444
stopOnSettle: Schema.optional(Schema.Boolean),
45+
/** Ask the server to run a command during shell startup when supported. */
46+
initialCommand: Schema.optional(
47+
Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),
48+
),
4549
});
4650
export type TerminalOpenInput = typeof TerminalOpenInput.Type;
4751

@@ -105,6 +109,8 @@ export const TerminalSessionSnapshot = Schema.Struct({
105109
// The PTY grid every renderer of this terminal should draw; absent from older servers.
106110
cols: Schema.optional(TerminalColsSchema),
107111
rows: Schema.optional(TerminalRowsSchema),
112+
/** Present when terminal.open handled the requested initial command. */
113+
initialCommandHandled: Schema.optional(Schema.Boolean),
108114
});
109115
export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;
110116

0 commit comments

Comments
 (0)