From 95d415c4c88a4e3ecc02e280d19dd25c9787a686 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 19:45:42 +0000 Subject: [PATCH 1/3] fix(terminal): run project actions after shell startup A project action run in a terminal that had never been opened was typed into the PTY as soon as terminal.open returned, before the interactive shell read input. An rc-file prompt (fnm, nvm) could consume it, so the command sat above the prompt and never ran. terminal.open now takes initialInput and the server types it once the shell's line editor reads input, using the readiness watcher the setup script runner already had. Every open that carries input is delivered by the server through one per-terminal queue, so an action run while an earlier one still waits lands behind it instead of overtaking it. The client keeps its own write only for servers that predate the field. Fixes pingdotgg/t3code#6337 Co-authored-by: farseenmanekhan1232 <67449931+farseenmanekhan1232@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- .../src/project/ProjectSetupScriptRunner.ts | 57 +----------- apps/server/src/terminal/Manager.test.ts | 61 +++++++++++++ apps/server/src/terminal/Manager.ts | 86 +++++++++++++++++-- apps/server/src/terminal/shellReadiness.ts | 69 +++++++++++++++ .../components/chat/useChatTerminalActions.ts | 34 ++++---- .../terminal/useThreadTerminalActions.ts | 3 + packages/contracts/src/terminal.ts | 6 ++ 7 files changed, 241 insertions(+), 75 deletions(-) create mode 100644 apps/server/src/terminal/shellReadiness.ts diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index a049bc89b01a1..19452ac310d0c 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -19,6 +19,7 @@ import * as Schema from "effect/Schema"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as TerminalManager from "../terminal/Manager.ts"; +import { watchShellReadiness as watchTerminalShellReadiness } from "../terminal/shellReadiness.ts"; import * as ProjectService from "./ProjectService.ts"; export interface ProjectSetupScriptRunnerResultNoScript { @@ -154,18 +155,6 @@ function stripTerminalControl(text: string): string { .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ""); } -// Line editors (zsh, fish, nu, bash 5.1+) enable bracketed paste when they start reading a command. -const BRACKETED_PASTE_ON = "\x1b[?2004h"; -const BRACKETED_PASTE_OFF = "\x1b[?2004l"; -// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first. -const SHELL_QUIET_FALLBACK = "3 seconds"; - -function lineEditorReading(text: string, previous: boolean): boolean { - const on = text.lastIndexOf(BRACKETED_PASTE_ON); - const off = text.lastIndexOf(BRACKETED_PASTE_OFF); - return on === off ? previous : on > off; -} - type CompletionShell = "posix" | "fish" | "nushell" | "powershell"; function resolveCompletionShell(shell: string): CompletionShell | null { @@ -312,54 +301,16 @@ export const make = Effect.gen(function* () { }, ); - // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the - // shell, which loses the command. Subscribe before the terminal opens so no activity is missed. const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")( function* (input: { readonly threadId: string; readonly terminalId: string; readonly onStartupPrompt: Effect.Effect; }) { - const outcome = yield* Deferred.make<"ready" | "exited">(); - let reading = false; - let carry = ""; - let busy = false; - let activity = 0; - const unsubscribe = yield* terminalManager.subscribe((event) => { - if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) { - return Effect.void; - } - activity += 1; - // A new shell process starts idle; the manager resets its subprocess state without an event. - if (event.type === "started" || event.type === "restarted") { - busy = false; - reading = false; - carry = ""; - } - if (event.type === "activity") busy = event.hasRunningSubprocess; - if (event.type === "output") { - const text = carry + event.data; - carry = text.slice(-(BRACKETED_PASTE_ON.length - 1)); - reading = lineEditorReading(text, reading); - } - if (event.type === "exited" || event.type === "closed") { - return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid); - } - return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void; - }); - // A startup prompt runs as a child process, so a busy shell keeps waiting for the user. - const quiet = Effect.gen(function* () { - while (true) { - const seen = activity; - yield* Effect.sleep(SHELL_QUIET_FALLBACK); - if (activity !== seen) continue; - if (!busy) return "ready" as const; - yield* input.onStartupPrompt; - } + return yield* watchTerminalShellReadiness({ + ...input, + subscribe: terminalManager.subscribe, }); - // Restored history can hold a previous shell's line editor state, so only live output counts. - const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet)); - return { wait, unsubscribe }; }, ); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index eb27174d5ed6d..b33f1f62905c7 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -73,6 +73,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess { killed = false; exitOnSubscribe: PtyAdapter.PtyExitEvent | undefined; onKill: ((signal?: string) => void) | undefined; + onWrite: ((data: string) => void) | undefined; constructor(pid: number) { this.pid = pid; @@ -83,6 +84,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess { throw this.writeFailure; } this.writes.push(data); + this.onWrite?.(data); } resize(cols: number, rows: number): void { @@ -2358,6 +2360,65 @@ it.layer( ), ); + it.effect("types initial input in order once a fresh shell reads input", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const first = yield* manager.open(openInput({ initialInput: "FIRST\r" })); + const second = yield* manager.open(openInput({ initialInput: "SECOND\r" })); + const shell = ptyAdapter.processes[0]!; + const secondWritten = yield* Deferred.make(); + shell.onWrite = (data) => { + if (data === "SECOND\r") Deferred.doneUnsafe(secondWritten, Effect.void); + }; + + expect([first.initialInputHandled, second.initialInputHandled]).toEqual([true, true]); + expect(shell.writes).toEqual([]); + + shell.emitData("\x1b[?2004h$ "); + yield* Deferred.await(secondWritten); + expect(shell.writes).toEqual(["FIRST\r", "SECOND\r"]); + + const third = yield* manager.open(openInput({ initialInput: "THIRD\r" })); + expect(third.initialInputHandled).toBe(true); + expect(shell.writes).toEqual(["FIRST\r", "SECOND\r", "THIRD\r"]); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); + + it.effect("drops initial input waiting for a shell that open replaced", () => + Effect.gen(function* () { + const { manager, ptyAdapter, baseDir } = yield* createManager(5, { processKillGraceMs: 0 }); + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const replacementCwd = path.join(baseDir, "replacement"); + yield* fs.makeDirectory(replacementCwd, { recursive: true }); + + yield* manager.open(openInput({ initialInput: "OLD\r" })); + yield* manager.open(openInput({ cwd: replacementCwd, initialInput: "NEW\r" })); + const replacement = ptyAdapter.processes[1]!; + const written = yield* Deferred.make(); + replacement.onWrite = () => Deferred.doneUnsafe(written, Effect.void); + replacement.emitData("\x1b[?2004h$ "); + yield* Deferred.await(written); + + expect(ptyAdapter.processes.map((process) => process.writes)).toEqual([[], ["NEW\r"]]); + }), + ); + + it.effect("types initial input into PowerShell without waiting for a line editor", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + env: { PATH: "C:\\Windows\\System32", SystemRoot: "C:\\Windows" }, + }).pipe(Effect.provide(layerWithHostPlatform("win32"))); + + const opened = yield* manager.open(openInput({ initialInput: "npm run dev\r" })); + + expect(ptyAdapter.spawnInputs[0]?.shell).toBe("pwsh.exe"); + expect(opened.initialInputHandled).toBe(true); + expect(ptyAdapter.processes[0]?.writes).toEqual(["npm run dev\r"]); + }), + ); + it.effect("restarts a running terminal when the resolved provider environment changes", () => Effect.gen(function* () { const providerInstanceId = ProviderInstanceId.make("codex_work"); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index dd06f5f516959..3fb77be757a88 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -76,6 +76,7 @@ import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts"; import { terminalOutputStream } from "./OutputProtocol.ts"; +import { watchShellReadiness } from "./shellReadiness.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; export { @@ -111,6 +112,12 @@ const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; +// PowerShell and cmd have no line-editor signal, so their input is written right away. +function shellSignalsLineEditor(shell: string): boolean { + const name = (shell.split(/[/\\]/).at(-1) ?? shell).toLowerCase().replace(/\.exe$/, ""); + return name !== "cmd" && name !== "pwsh" && name !== "powershell"; +} + const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; // The tmux/screen/Zellij keys name the multiplexer pane that launched the server, @@ -313,6 +320,8 @@ interface TerminalSessionState { childCommandLabel: string | null; runtimeEnv: Record | null; stopOnSettle: boolean; + /** Input waiting for the current shell to read; null once that shell takes writes directly. */ + pendingInitialInputs: Array | null; } interface TerminalGrid { @@ -2437,6 +2446,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func session.hasRunningSubprocess = false; session.childCommandLabel = null; session.status = "exited"; + session.pendingInitialInputs = null; session.pendingHistoryControlSequence = ""; session.pendingProcessEvents = []; session.pendingProcessEventIndex = 0; @@ -2534,6 +2544,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* modifyManagerState((state) => { session.status = "starting"; session.shell = null; + session.pendingInitialInputs = null; session.cwd = input.cwd; session.worktreePath = input.worktreePath ?? null; session.cols = input.cols; @@ -2942,6 +2953,57 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }).pipe(Effect.ignoreCause({ log: true })), ); + // Input typed while a shell starts can be read by an rc-file prompt (fnm, nvm) instead of the + // shell, so it waits for the line editor. The queue keeps later opens behind it, in order. + const startOpenedSession = Effect.fn("terminal.startOpenedSession")(function* ( + session: TerminalSessionState, + startInput: TerminalStartInput, + initialInput: string | undefined, + ) { + if (initialInput === undefined) { + yield* startSession(session, startInput, "started"); + return snapshot(session); + } + const target = { threadId: session.threadId, terminalId: session.terminalId }; + // Subscribed before the spawn so no startup output is missed. + const readiness = yield* watchShellReadiness({ + ...target, + subscribe, + onStartupPrompt: Effect.void, + }); + yield* startSession(session, startInput, "started").pipe( + Effect.onError(() => Effect.sync(readiness.unsubscribe)), + ); + const spawned = session.process; + if (session.status !== "running" || spawned === null || session.shell === null) { + readiness.unsubscribe(); + return snapshot(session); + } + if (!shellSignalsLineEditor(session.shell)) { + readiness.unsubscribe(); + yield* write({ ...target, data: initialInput }); + return { ...snapshot(session), initialInputHandled: true }; + } + const queued = [initialInput]; + session.pendingInitialInputs = queued; + yield* readiness.wait.pipe( + Effect.flatMap((outcome) => { + // A restart or exit already dropped the queue: the input belonged to the shell it was opened for. + if (session.pendingInitialInputs !== queued) return Effect.void; + session.pendingInitialInputs = null; + return outcome === "exited" || session.process !== spawned + ? Effect.void + : Effect.forEach(queued, (data) => write({ ...target, data }), { discard: true }); + }), + Effect.catchCause((cause) => + Effect.logWarning("terminal initial input was not written", { ...target, cause }), + ), + Effect.ensuring(Effect.sync(readiness.unsubscribe)), + Effect.forkIn(workerScope), + ); + return { ...snapshot(session), initialInputHandled: true }; + }); + const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* ( requestedInput: TerminalOpenInput, ) { @@ -2992,6 +3054,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func childCommandLabel: null, runtimeEnv: normalizedRuntimeEnv(input.env), stopOnSettle: input.stopOnSettle ?? false, + pendingInitialInputs: null, }; const createdSession = session; @@ -3003,7 +3066,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); yield* evictInactiveSessionsIfNeeded(); - yield* startSession( + return yield* startOpenedSession( session, { cwd: input.cwd, @@ -3011,9 +3074,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func cols, rows, }, - "started", + input.initialInput, ); - return snapshot(session); } const liveSession = existing.value; @@ -3053,7 +3115,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } if (!liveSession.process) { - yield* startSession( + return yield* startOpenedSession( liveSession, { cwd: input.cwd, @@ -3061,16 +3123,26 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func cols: targetCols, rows: targetRows, }, - "started", + input.initialInput, ); - return snapshot(liveSession); } if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows); } - return snapshot(liveSession); + if (input.initialInput === undefined) return snapshot(liveSession); + // Behind input still waiting for this shell, so a second action cannot overtake the first. + if (liveSession.pendingInitialInputs !== null) { + liveSession.pendingInitialInputs.push(input.initialInput); + } else { + yield* write({ + threadId: liveSession.threadId, + terminalId: liveSession.terminalId, + data: input.initialInput, + }); + } + return { ...snapshot(liveSession), initialInputHandled: true }; }); const openLocked = (input: TerminalOpenInput) => diff --git a/apps/server/src/terminal/shellReadiness.ts b/apps/server/src/terminal/shellReadiness.ts new file mode 100644 index 0000000000000..88380c46bd9b6 --- /dev/null +++ b/apps/server/src/terminal/shellReadiness.ts @@ -0,0 +1,69 @@ +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; + +import type { TerminalEvent } from "@t3tools/contracts"; + +// Line editors (zsh, fish, nu, bash 5.1+) enable bracketed paste when they start reading a command. +const BRACKETED_PASTE_ON = "\x1b[?2004h"; +const BRACKETED_PASTE_OFF = "\x1b[?2004l"; +// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first. +const SHELL_QUIET_FALLBACK = "3 seconds"; + +function lineEditorReading(text: string, previous: boolean): boolean { + const on = text.lastIndexOf(BRACKETED_PASTE_ON); + const off = text.lastIndexOf(BRACKETED_PASTE_OFF); + return on === off ? previous : on > off; +} + +// Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the +// shell, which loses the command. Subscribe before the terminal opens so no activity is missed. +// Untraced: each caller owns the span around the wait. +export const watchShellReadiness = Effect.fnUntraced(function* (input: { + readonly subscribe: ( + listener: (event: TerminalEvent) => Effect.Effect, + ) => Effect.Effect<() => void>; + readonly threadId: string; + readonly terminalId: string; + readonly onStartupPrompt: Effect.Effect; +}) { + const outcome = yield* Deferred.make<"ready" | "exited">(); + let reading = false; + let carry = ""; + let busy = false; + let activity = 0; + const unsubscribe = yield* input.subscribe((event) => { + if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) { + return Effect.void; + } + activity += 1; + // A new shell process starts idle; the manager resets its subprocess state without an event. + if (event.type === "started" || event.type === "restarted") { + busy = false; + reading = false; + carry = ""; + } + if (event.type === "activity") busy = event.hasRunningSubprocess; + if (event.type === "output") { + const text = carry + event.data; + carry = text.slice(-(BRACKETED_PASTE_ON.length - 1)); + reading = lineEditorReading(text, reading); + } + if (event.type === "exited" || event.type === "closed") { + return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid); + } + return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void; + }); + // A startup prompt runs as a child process, so a busy shell keeps waiting for the user. + const quiet = Effect.gen(function* () { + while (true) { + const seen = activity; + yield* Effect.sleep(SHELL_QUIET_FALLBACK); + if (activity !== seen) continue; + if (!busy) return "ready" as const; + yield* input.onStartupPrompt; + } + }); + // Restored history can hold a previous shell's line editor state, so only live output counts. + const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet)); + return { wait, unsubscribe }; +}); diff --git a/apps/web/src/components/chat/useChatTerminalActions.ts b/apps/web/src/components/chat/useChatTerminalActions.ts index a64c748e81432..6252dba9bbc1d 100644 --- a/apps/web/src/components/chat/useChatTerminalActions.ts +++ b/apps/web/src/components/chat/useChatTerminalActions.ts @@ -244,6 +244,10 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { return; } + const scriptInput = + options?.shellHistory === "preserve" + ? `${script.command}\r` + : projectScriptTerminalInput(script.command); const launched = terminalActions.launchTerminal({ // The drawer opens with the target already placed: opening it empty would claim // DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own. @@ -257,6 +261,8 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { location: { cwd: targetCwd, worktreePath: targetWorktreePath }, stopOnSettle: script.stopOnSettle ?? false, ...(options?.env ? { extraEnv: options.env } : {}), + // The open schema caps input; a longer command takes the write path below, as before. + ...(scriptInput.length <= 65_536 ? { initialInput: scriptInput } : {}), }); if (!launched) return; const targetTerminalId = launched.terminalId; @@ -273,22 +279,20 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { return; } - const writeResult = await terminalActions.writeToTerminal( - targetTerminalId, - options?.shellHistory === "preserve" - ? `${script.command}\r` - : projectScriptTerminalInput(script.command), - ); - if (!writeResult) return; - if (writeResult._tag === "Failure") { - if (!isAtomCommandInterrupted(writeResult)) { - const error = squashAtomCommandFailure(writeResult); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : `Failed to run script "${script.name}".`, - ); + // A server that predates initialInput leaves it to the client. + if (openResult.value.initialInputHandled !== true) { + const writeResult = await terminalActions.writeToTerminal(targetTerminalId, scriptInput); + if (!writeResult) return; + if (writeResult._tag === "Failure") { + if (!isAtomCommandInterrupted(writeResult)) { + const error = squashAtomCommandFailure(writeResult); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : `Failed to run script "${script.name}".`, + ); + } + return; } - return; } if ( script.autoOpenPreview && diff --git a/apps/web/src/components/terminal/useThreadTerminalActions.ts b/apps/web/src/components/terminal/useThreadTerminalActions.ts index 9112f41519754..d2e483c4b6115 100644 --- a/apps/web/src/components/terminal/useThreadTerminalActions.ts +++ b/apps/web/src/components/terminal/useThreadTerminalActions.ts @@ -89,6 +89,8 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) { readonly extraEnv?: Record; readonly stopOnSettle?: boolean; readonly size?: { readonly cols: number; readonly rows: number }; + /** The server types this once the shell reads input; see `initialInputHandled` on the result. */ + readonly initialInput?: string; }) => { if (!threadRef || !canWrite() || !project) return null; const location = input.location ?? defaultLaunchLocation(); @@ -109,6 +111,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) { }), ...input.size, ...(input.stopOnSettle !== undefined ? { stopOnSettle: input.stopOnSettle } : {}), + ...(input.initialInput !== undefined ? { initialInput: input.initialInput } : {}), }, }); return { terminalId, result }; diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 7dcd75cb9d94e..99c279a17bc56 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -69,6 +69,10 @@ export const TerminalOpenInput = Schema.Struct({ env: Schema.optional(TerminalEnvSchema), providerInstanceId: Schema.optional(ProviderInstanceId), stopOnSettle: Schema.optional(Schema.Boolean), + // Typed once the shell reads input, after any earlier input still waiting; older servers ignore it. + initialInput: Schema.optional( + Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)), + ), }); export type TerminalOpenInput = typeof TerminalOpenInput.Type; @@ -134,6 +138,8 @@ export const TerminalSessionSnapshot = Schema.Struct({ // The PTY grid every renderer of this terminal should draw; absent from older servers. cols: Schema.optional(TerminalColsSchema), rows: Schema.optional(TerminalRowsSchema), + // Set by terminal.open when the server delivers initialInput; absent means the client types it. + initialInputHandled: Schema.optional(Schema.Boolean), }); export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type; From 5ac3fba979e050aa0016a507429fe1892d76e21b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 20:00:15 +0000 Subject: [PATCH 2/3] 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 --- apps/server/src/terminal/Manager.test.ts | 53 ++++++++--- apps/server/src/terminal/Manager.ts | 94 ++++++++----------- .../components/chat/useChatTerminalActions.ts | 35 ++++--- .../terminal/useThreadTerminalActions.ts | 12 ++- .../client-runtime/src/state/terminal.test.ts | 6 +- packages/client-runtime/src/state/terminal.ts | 5 +- packages/contracts/src/terminal.ts | 8 +- 7 files changed, 108 insertions(+), 105 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index b33f1f62905c7..d5f0a085cc30d 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -2360,41 +2360,61 @@ it.layer( ), ); - it.effect("types initial input in order once a fresh shell reads input", () => + it.effect("holds startup writes, in order, until a fresh shell reads input", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); - const first = yield* manager.open(openInput({ initialInput: "FIRST\r" })); - const second = yield* manager.open(openInput({ initialInput: "SECOND\r" })); + const afterStartup = (data: string) => + manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data, + afterShellStartup: true, + }); + yield* manager.open(openInput()); const shell = ptyAdapter.processes[0]!; const secondWritten = yield* Deferred.make(); shell.onWrite = (data) => { if (data === "SECOND\r") Deferred.doneUnsafe(secondWritten, Effect.void); }; - expect([first.initialInputHandled, second.initialInputHandled]).toEqual([true, true]); + yield* afterStartup("FIRST\r"); + // A second action reopens the running terminal before typing. + yield* manager.open(openInput()); + yield* afterStartup("SECOND\r"); expect(shell.writes).toEqual([]); + // Answering an rc-file prompt must not wait behind the held input. + yield* manager.write({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, data: "y\r" }); + expect(shell.writes).toEqual(["y\r"]); shell.emitData("\x1b[?2004h$ "); yield* Deferred.await(secondWritten); - expect(shell.writes).toEqual(["FIRST\r", "SECOND\r"]); + expect(shell.writes).toEqual(["y\r", "FIRST\r", "SECOND\r"]); - const third = yield* manager.open(openInput({ initialInput: "THIRD\r" })); - expect(third.initialInputHandled).toBe(true); - expect(shell.writes).toEqual(["FIRST\r", "SECOND\r", "THIRD\r"]); + yield* afterStartup("THIRD\r"); + expect(shell.writes).toEqual(["y\r", "FIRST\r", "SECOND\r", "THIRD\r"]); expect(ptyAdapter.spawnInputs).toHaveLength(1); }), ); - it.effect("drops initial input waiting for a shell that open replaced", () => + it.effect("drops startup writes held for a shell that open replaced", () => Effect.gen(function* () { const { manager, ptyAdapter, baseDir } = yield* createManager(5, { processKillGraceMs: 0 }); const path = yield* Path.Path; const fs = yield* FileSystem.FileSystem; const replacementCwd = path.join(baseDir, "replacement"); yield* fs.makeDirectory(replacementCwd, { recursive: true }); + const afterStartup = (data: string) => + manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data, + afterShellStartup: true, + }); - yield* manager.open(openInput({ initialInput: "OLD\r" })); - yield* manager.open(openInput({ cwd: replacementCwd, initialInput: "NEW\r" })); + yield* manager.open(openInput()); + yield* afterStartup("OLD\r"); + yield* manager.open(openInput({ cwd: replacementCwd })); + yield* afterStartup("NEW\r"); const replacement = ptyAdapter.processes[1]!; const written = yield* Deferred.make(); replacement.onWrite = () => Deferred.doneUnsafe(written, Effect.void); @@ -2405,16 +2425,21 @@ it.layer( }), ); - it.effect("types initial input into PowerShell without waiting for a line editor", () => + it.effect("types a startup write into PowerShell without waiting for a line editor", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(5, { env: { PATH: "C:\\Windows\\System32", SystemRoot: "C:\\Windows" }, }).pipe(Effect.provide(layerWithHostPlatform("win32"))); - const opened = yield* manager.open(openInput({ initialInput: "npm run dev\r" })); + yield* manager.open(openInput()); + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "npm run dev\r", + afterShellStartup: true, + }); expect(ptyAdapter.spawnInputs[0]?.shell).toBe("pwsh.exe"); - expect(opened.initialInputHandled).toBe(true); expect(ptyAdapter.processes[0]?.writes).toEqual(["npm run dev\r"]); }), ); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 3fb77be757a88..344fd0d7638f6 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -320,8 +320,8 @@ interface TerminalSessionState { childCommandLabel: string | null; runtimeEnv: Record | null; stopOnSettle: boolean; - /** Input waiting for the current shell to read; null once that shell takes writes directly. */ - pendingInitialInputs: Array | null; + /** Writes waiting for the current shell to read input; null once it takes them directly. */ + heldWrites: Array | null; } interface TerminalGrid { @@ -2446,7 +2446,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func session.hasRunningSubprocess = false; session.childCommandLabel = null; session.status = "exited"; - session.pendingInitialInputs = null; + session.heldWrites = null; session.pendingHistoryControlSequence = ""; session.pendingProcessEvents = []; session.pendingProcessEventIndex = 0; @@ -2544,7 +2544,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* modifyManagerState((state) => { session.status = "starting"; session.shell = null; - session.pendingInitialInputs = null; + session.heldWrites = null; session.cwd = input.cwd; session.worktreePath = input.worktreePath ?? null; session.cols = input.cols; @@ -2954,16 +2954,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); // Input typed while a shell starts can be read by an rc-file prompt (fnm, nvm) instead of the - // shell, so it waits for the line editor. The queue keeps later opens behind it, in order. + // shell. Writes that ask to wait are held, in order, until the line editor reads input. const startOpenedSession = Effect.fn("terminal.startOpenedSession")(function* ( session: TerminalSessionState, startInput: TerminalStartInput, - initialInput: string | undefined, ) { - if (initialInput === undefined) { - yield* startSession(session, startInput, "started"); - return snapshot(session); - } const target = { threadId: session.threadId, terminalId: session.terminalId }; // Subscribed before the spawn so no startup output is missed. const readiness = yield* watchShellReadiness({ @@ -2975,33 +2970,33 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.onError(() => Effect.sync(readiness.unsubscribe)), ); const spawned = session.process; - if (session.status !== "running" || spawned === null || session.shell === null) { + if ( + session.status !== "running" || + spawned === null || + session.shell === null || + !shellSignalsLineEditor(session.shell) + ) { readiness.unsubscribe(); return snapshot(session); } - if (!shellSignalsLineEditor(session.shell)) { - readiness.unsubscribe(); - yield* write({ ...target, data: initialInput }); - return { ...snapshot(session), initialInputHandled: true }; - } - const queued = [initialInput]; - session.pendingInitialInputs = queued; + const held: Array = []; + session.heldWrites = held; yield* readiness.wait.pipe( Effect.flatMap((outcome) => { - // A restart or exit already dropped the queue: the input belonged to the shell it was opened for. - if (session.pendingInitialInputs !== queued) return Effect.void; - session.pendingInitialInputs = null; + // A restart or exit already dropped the queue: the input belonged to the shell it was typed for. + if (session.heldWrites !== held) return Effect.void; + session.heldWrites = null; return outcome === "exited" || session.process !== spawned ? Effect.void - : Effect.forEach(queued, (data) => write({ ...target, data }), { discard: true }); + : Effect.forEach(held, (data) => write({ ...target, data }), { discard: true }); }), Effect.catchCause((cause) => - Effect.logWarning("terminal initial input was not written", { ...target, cause }), + Effect.logWarning("terminal held input was not written", { ...target, cause }), ), Effect.ensuring(Effect.sync(readiness.unsubscribe)), Effect.forkIn(workerScope), ); - return { ...snapshot(session), initialInputHandled: true }; + return snapshot(session); }); const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* ( @@ -3054,7 +3049,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func childCommandLabel: null, runtimeEnv: normalizedRuntimeEnv(input.env), stopOnSettle: input.stopOnSettle ?? false, - pendingInitialInputs: null, + heldWrites: null, }; const createdSession = session; @@ -3066,16 +3061,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); yield* evictInactiveSessionsIfNeeded(); - return yield* startOpenedSession( - session, - { - cwd: input.cwd, - ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), - cols, - rows, - }, - input.initialInput, - ); + return yield* startOpenedSession(session, { + cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), + cols, + rows, + }); } const liveSession = existing.value; @@ -3115,34 +3106,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } if (!liveSession.process) { - return yield* startOpenedSession( - liveSession, - { - cwd: input.cwd, - worktreePath: liveSession.worktreePath, - cols: targetCols, - rows: targetRows, - }, - input.initialInput, - ); + return yield* startOpenedSession(liveSession, { + cwd: input.cwd, + worktreePath: liveSession.worktreePath, + cols: targetCols, + rows: targetRows, + }); } if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows); } - if (input.initialInput === undefined) return snapshot(liveSession); - // Behind input still waiting for this shell, so a second action cannot overtake the first. - if (liveSession.pendingInitialInputs !== null) { - liveSession.pendingInitialInputs.push(input.initialInput); - } else { - yield* write({ - threadId: liveSession.threadId, - terminalId: liveSession.terminalId, - data: input.initialInput, - }); - } - return { ...snapshot(liveSession), initialInputHandled: true }; + return snapshot(liveSession); }); const openLocked = (input: TerminalOpenInput) => @@ -3538,6 +3514,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId, }); } + if (input.afterShellStartup === true && session.heldWrites !== null) { + session.heldWrites.push(input.data); + return; + } session.inputCount += 1; yield* Effect.try({ try: () => process.write(input.data), diff --git a/apps/web/src/components/chat/useChatTerminalActions.ts b/apps/web/src/components/chat/useChatTerminalActions.ts index 6252dba9bbc1d..07afc84fb7466 100644 --- a/apps/web/src/components/chat/useChatTerminalActions.ts +++ b/apps/web/src/components/chat/useChatTerminalActions.ts @@ -244,10 +244,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { return; } - const scriptInput = - options?.shellHistory === "preserve" - ? `${script.command}\r` - : projectScriptTerminalInput(script.command); const launched = terminalActions.launchTerminal({ // The drawer opens with the target already placed: opening it empty would claim // DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own. @@ -261,8 +257,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { location: { cwd: targetCwd, worktreePath: targetWorktreePath }, stopOnSettle: script.stopOnSettle ?? false, ...(options?.env ? { extraEnv: options.env } : {}), - // The open schema caps input; a longer command takes the write path below, as before. - ...(scriptInput.length <= 65_536 ? { initialInput: scriptInput } : {}), }); if (!launched) return; const targetTerminalId = launched.terminalId; @@ -279,20 +273,23 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { return; } - // A server that predates initialInput leaves it to the client. - if (openResult.value.initialInputHandled !== true) { - const writeResult = await terminalActions.writeToTerminal(targetTerminalId, scriptInput); - if (!writeResult) return; - if (writeResult._tag === "Failure") { - if (!isAtomCommandInterrupted(writeResult)) { - const error = squashAtomCommandFailure(writeResult); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : `Failed to run script "${script.name}".`, - ); - } - return; + const writeResult = await terminalActions.writeToTerminal( + targetTerminalId, + options?.shellHistory === "preserve" + ? `${script.command}\r` + : projectScriptTerminalInput(script.command), + { afterShellStartup: true }, + ); + if (!writeResult) return; + if (writeResult._tag === "Failure") { + if (!isAtomCommandInterrupted(writeResult)) { + const error = squashAtomCommandFailure(writeResult); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : `Failed to run script "${script.name}".`, + ); } + return; } if ( script.autoOpenPreview && diff --git a/apps/web/src/components/terminal/useThreadTerminalActions.ts b/apps/web/src/components/terminal/useThreadTerminalActions.ts index d2e483c4b6115..f2052be1e566d 100644 --- a/apps/web/src/components/terminal/useThreadTerminalActions.ts +++ b/apps/web/src/components/terminal/useThreadTerminalActions.ts @@ -89,8 +89,6 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) { readonly extraEnv?: Record; readonly stopOnSettle?: boolean; readonly size?: { readonly cols: number; readonly rows: number }; - /** The server types this once the shell reads input; see `initialInputHandled` on the result. */ - readonly initialInput?: string; }) => { if (!threadRef || !canWrite() || !project) return null; const location = input.location ?? defaultLaunchLocation(); @@ -111,7 +109,6 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) { }), ...input.size, ...(input.stopOnSettle !== undefined ? { stopOnSettle: input.stopOnSettle } : {}), - ...(input.initialInput !== undefined ? { initialInput: input.initialInput } : {}), }, }); return { terminalId, result }; @@ -137,11 +134,16 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) { })(); }; - const writeToTerminal = (terminalId: string, data: string) => { + /** afterShellStartup has the server hold the input until a starting shell reads it. */ + const writeToTerminal = ( + terminalId: string, + data: string, + options?: { readonly afterShellStartup: boolean }, + ) => { if (!threadRef || !canWrite()) return null; return writeTerminal({ environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId, terminalId, data }, + input: { threadId: threadRef.threadId, terminalId, data, ...options }, }); }; diff --git a/packages/client-runtime/src/state/terminal.test.ts b/packages/client-runtime/src/state/terminal.test.ts index 6fb2d21b19ea1..0acfb7e6fbbb4 100644 --- a/packages/client-runtime/src/state/terminal.test.ts +++ b/packages/client-runtime/src/state/terminal.test.ts @@ -154,13 +154,15 @@ it("replays the measured grid on every new attachment generation", () => { ]); }); -it("writes the launch's initial input once the first snapshot lands", () => { +it("sends the launch's initial input once, for the server to type after shell startup", () => { const { attached, emit, mount, calls, of } = setup({ initialInput: "pnpm dev\r" }); mount(attached); expect(of("write")).toEqual([]); emit({ status: "running", version: 1 }); emit({ status: "running", version: 2 }); - expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "pnpm dev\r" }]); + expect(of("write")).toEqual([ + { threadId, terminalId: "term-1", data: "pnpm dev\r", afterShellStartup: true }, + ]); // The shell gets the measured grid before the launched command runs. expect(calls.map((call) => call.command)).toEqual(["resize", "write"]); }); diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index f62c2549daf1d..e364f63ff703d 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -226,7 +226,7 @@ export interface TerminalSessionOptions { readonly terminalId: string; }; readonly gridSize: TerminalGridSize; - /** Written once, as soon as the first attachment snapshot lands. */ + /** Sent once when the first attachment snapshot lands; the server types it after shell startup. */ readonly initialInput?: string | undefined; /** Read right before every command, so revoking operate stops them at once. */ readonly canOperate: () => boolean; @@ -364,7 +364,8 @@ export function createTerminalSession( initialInputPending = false; void runAtomCommand(registry, atoms.write, { environmentId, - input: { threadId, terminalId, data: options.initialInput }, + // The first snapshot can land while the shell still starts; the server holds the input. + input: { threadId, terminalId, data: options.initialInput, afterShellStartup: true }, }); } diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 99c279a17bc56..48ba0d643c822 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -69,10 +69,6 @@ export const TerminalOpenInput = Schema.Struct({ env: Schema.optional(TerminalEnvSchema), providerInstanceId: Schema.optional(ProviderInstanceId), stopOnSettle: Schema.optional(Schema.Boolean), - // Typed once the shell reads input, after any earlier input still waiting; older servers ignore it. - initialInput: Schema.optional( - Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)), - ), }); export type TerminalOpenInput = typeof TerminalOpenInput.Type; @@ -99,6 +95,8 @@ export type TerminalObserveInput = Schema.Codec.Encoded; @@ -138,8 +136,6 @@ export const TerminalSessionSnapshot = Schema.Struct({ // The PTY grid every renderer of this terminal should draw; absent from older servers. cols: Schema.optional(TerminalColsSchema), rows: Schema.optional(TerminalRowsSchema), - // Set by terminal.open when the server delivers initialInput; absent means the client types it. - initialInputHandled: Schema.optional(Schema.Boolean), }); export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type; From 514429a6de48ccec7ebe7c9869249e47c3082137 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 20:12:50 +0000 Subject: [PATCH 3/3] fix(terminal): a held startup write keeps its terminal from idle close A write held for shell startup did not count as input, so closeIdle saw no activity and could close the terminal with the command still queued. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/terminal/Manager.test.ts | 15 +++++++++++---- apps/server/src/terminal/Manager.ts | 2 +- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index d5f0a085cc30d..01ffd1b4cf277 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1113,11 +1113,17 @@ it.layer( yield* Effect.addFinalizer(() => Effect.sync(unsubscribeOutput)); yield* manager.open(openInput({ terminalId: "typed" })); yield* manager.open(openInput({ terminalId: "echoed" })); - const [typed, echoed] = ptyAdapter.processes; + yield* manager.open(openInput({ terminalId: "held" })); + const [typed, echoed, held] = ptyAdapter.processes; duringCheck = (pid) => - pid === typed!.pid + pid === typed!.pid || pid === held!.pid ? manager - .write({ threadId: "thread-1", terminalId: "typed", data: "make build\r" }) + .write({ + threadId: "thread-1", + terminalId: pid === typed!.pid ? "typed" : "held", + data: "make build\r", + afterShellStartup: pid === held!.pid, + }) .pipe(Effect.orDie) : Effect.gen(function* () { echoed!.emitData("make build\r\n"); @@ -1126,7 +1132,8 @@ it.layer( yield* manager.closeIdle({ threadId: "thread-1" }); - expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([false, false]); + expect(held!.writes).toEqual([]); + expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([false, false, false]); }), ); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 344fd0d7638f6..62a7c22ec12de 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3514,11 +3514,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId, }); } + session.inputCount += 1; if (input.afterShellStartup === true && session.heldWrites !== null) { session.heldWrites.push(input.data); return; } - session.inputCount += 1; yield* Effect.try({ try: () => process.write(input.data), catch: (cause) =>