From 47ecaa1ead9467fa1b1731e44ed2559a6c1b3b0f Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:03:27 -0400 Subject: [PATCH] fix: commands you put in the terminal send their output back to the agent An agent's "Put in terminal" card stopped tracking the command when the user pressed Enter, and only Run sent output back by itself, so nothing ever reached the agent. The terminal now follows an entered insert until the command it started ends: PowerShell's prompt marker, or a POSIX shell's line editor coming back on while a fresh process table shows the shell in front of its terminal again (`+` in its ps state, so a REPL, ssh or nested shell keeps it going and a background job doesn't). A builtin waiting for input isn't ended by idle polls, a line typed ahead ends it at the first prompt, and the output stops where that prompt began. Request cards now send their output by itself in both modes, behind a new `followsInsertedCommands` capability. "Send output so far" shows for running commands that would send by themselves, and an old "submitted" run no longer blocks moving a thread. --- apps/server/src/commandRuns/CommandRuns.ts | 10 +- .../environment/Layers/ServerEnvironment.ts | 1 + apps/server/src/mcp/commandTools.ts | 2 +- .../src/orchestration/threadMoveDecisions.ts | 2 +- .../src/terminal/Layers/Manager.test.ts | 164 +++++++- apps/server/src/terminal/Layers/Manager.ts | 354 +++++++++++++++++- apps/server/src/terminal/Services/Manager.ts | 9 +- .../src/components/ChatMarkdown.browser.tsx | 1 + .../components/chat/CommandRuns.browser.tsx | 5 + apps/web/src/components/chat/CommandRuns.tsx | 49 ++- .../components/chat/useCommandRunActions.ts | 3 + docs/terminal-command-runs.md | 39 +- packages/contracts/src/environment.ts | 7 + packages/contracts/src/orchestration.ts | 25 +- packages/shared/src/commandRuns.ts | 13 +- 15 files changed, 617 insertions(+), 67 deletions(-) diff --git a/apps/server/src/commandRuns/CommandRuns.ts b/apps/server/src/commandRuns/CommandRuns.ts index 5859c6db4..ec2eaa10b 100644 --- a/apps/server/src/commandRuns/CommandRuns.ts +++ b/apps/server/src/commandRuns/CommandRuns.ts @@ -4,7 +4,8 @@ * block in a reply. This service records the request, starts each run in a * free terminal tab or a new one, follows the tab's run updates into the * thread, and hands a run's output to the agent it was for: by itself when a - * request's Run finishes, or when the user asks. + * request's command finishes (run, or put in the terminal and entered), or + * when the user asks. * * The terminal does the running; orchestration keeps the record and decides * every send, so Stop, reverts, skips and rooms are respected in one place. @@ -191,12 +192,12 @@ const make = Effect.gen(function* () { return { outcome: "shown" as const, detail: oneClick - ? "Shown to the user as a card with Run, Put in terminal and Skip. Nothing runs until they choose. If they click Run, the output comes back to you as a message when the command finishes. If you can't go on without it, say in a sentence what you're waiting for and end your turn." + ? "Shown to the user as a card with Run, Put in terminal and Skip. Nothing runs until they choose. When the command they run finishes, the output comes back to you as a message. If you can't go on without it, say in a sentence what you're waiting for and end your turn." : `Shown to the user as a card. It can't run with one click (${assessment.cautions .map((caution) => caution.label.replace(/\.$/, "").toLowerCase()) .join( "; ", - )}), so the user puts it in the terminal, checks it and presses Enter, then sends you the output when they're done. If you can't go on without it, say in a sentence what you're waiting for and end your turn.`, + )}), so the user puts it in the terminal, checks it and presses Enter. When it finishes, what the terminal showed comes back to you as a message (they may have changed the command first). If you can't go on without it, say in a sentence what you're waiting for and end your turn.`, }; }); @@ -446,7 +447,8 @@ const make = Effect.gen(function* () { turnId: origin.turnId, participantId: origin.participantId, cwd: input.cwd, - autoSend: input.source.kind === "request" && input.mode === "run", + // A card's command answers the agent that asked, however it ran. + autoSend: input.source.kind === "request", }, createdAt: yield* nowIso, }) diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index d44616256..e734d179d 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -90,6 +90,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function browserLoopbackTunnel: true, browserScreenshotTypes: true, commandRuns: true, + followsInsertedCommands: true, computerLinks: true, scheduledTasks: true, eventTasks: true, diff --git a/apps/server/src/mcp/commandTools.ts b/apps/server/src/mcp/commandTools.ts index d3d9dd1d5..70af4050b 100644 --- a/apps/server/src/mcp/commandTools.ts +++ b/apps/server/src/mcp/commandTools.ts @@ -37,7 +37,7 @@ export const AskUserToRunTool = Tool.make(ASK_USER_TO_RUN_TOOL_NAME, { description: [ "Ask the user to run a shell command in their Threadlines terminal, when you can't run it yourself: it needs their password or a sign-in, your sandbox or permissions blocked it, or it is a long-running process like a dev server they should own.", "It shows a card in the chat with Run, Put in terminal and Skip, and returns right away; nothing runs until the user chooses.", - "When they click Run, the output comes back to you as a message once the command finishes. Risky commands (deleting files, discarding changes, sudo, publishing and the like) can't run with one click: the user puts them in the terminal, presses Enter themselves and sends you the output.", + "When the command they run finishes, the output comes back to you as a message. Risky commands (deleting files, discarding changes, sudo, publishing and the like) can't run with one click: the user puts them in the terminal and presses Enter themselves, and the output comes back the same way.", "Use it instead of asking the user to copy a command into a terminal. Don't use it for commands you can run yourself.", ].join(" "), parameters: AskUserToRunParameters, diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index f13aea1ea..72d1a05ae 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -84,7 +84,7 @@ export function threadMoveRefusal( } if ( (thread.commandRuns ?? []).some((run) => - ["starting", "running", "waiting", "submitted"].includes(run.status), + ["starting", "running", "waiting"].includes(run.status), ) || (thread.workflowRuns ?? []).some((run) => run.status === "running") || thread.voiceActive === true diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index be769f92b..14f62d432 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -2266,17 +2266,31 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( }), ); - it.effect("puts a command at the prompt once the shell is ready and follows it to Enter", () => + it.effect("puts a command at the prompt once the shell is ready and follows it to its end", () => Effect.gen(function* () { + // In front of the terminal at its own prompt, or behind a program it started. + const shellInFront = yield* Ref.make(true); + let shellPid = 0; const { manager, ptyAdapter } = yield* createManager(50, { platform: "darwin", shellResolver: () => "/bin/zsh", + // Polling never gets a look in: the prompt alone ends it. + subprocessChecker: () => Effect.succeed(false), + subprocessPollIntervalMs: 60_000, + freshProcessRowsReader: () => + Ref.get(shellInFront).pipe( + Effect.map((front) => [ + { ...processRow(shellPid, 1, "/bin/zsh"), status: front ? "Ss+" : "Ss" }, + ]), + ), }); const updates = yield* collectRunUpdates(manager); + const types = Ref.get(updates).pipe(Effect.map((list) => list.map((update) => update.type))); yield* manager.startCommandRun( commandRunInput({ mode: "insert", command: "git add .\ngit commit" }), ); const pty = ptyAdapter.processes[0]!; + shellPid = pty.pid; expect(ptyAdapter.spawnInputs[0]?.args).toEqual(["-o", "nopromptsp"]); expect(pty.writes).toEqual([]); @@ -2286,14 +2300,148 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( pty.emitData("git add .\r\ngit commit"); yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "\r" }); - yield* waitFor( - Ref.get(updates).pipe(Effect.map((list) => list.some((u) => u.type === "submitted"))), + yield* waitFor(types.pipe(Effect.map((list) => list.includes("running")))); + // A program it started that reads lines (the commit message editor) + // turns the line editor on too: while it runs in front, the command goes on. + yield* Ref.set(shellInFront, false); + pty.emitData("\u001b[?2004l\r\nmessage: \u001b[?2004h"); + yield* Effect.sleep("150 millis"); + expect(yield* types).toEqual(["waiting", "running"]); + + // Back at the shell's own prompt: done, with what the tab showed. + yield* Ref.set(shellInFront, true); + pty.emitData("\u001b[?2004l\r\n[main 1a2b3c] fix\r\nprompt % \u001b[?2004h"); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("finished")))); + expect((yield* Ref.get(updates)).at(-1)).toEqual({ + type: "finished", + runId: "run-1", + at: expect.any(String), + startedAt: expect.any(String), + exitCode: null, + output: "git add .\ngit commit\nmessage:\n[main 1a2b3c] fix\nprompt %", + }); + }), + ); + + it.effect("keeps following an entered insert until its shell's prompt is back", () => + Effect.gen(function* () { + let shellPid = 0; + const nextCommandRunning = yield* Ref.make(false); + const { manager, ptyAdapter } = yield* createManager(50, { + platform: "darwin", + shellResolver: () => "/bin/zsh", + subprocessChecker: () => Ref.get(nextCommandRunning), + subprocessPollIntervalMs: 20, + // By the time anyone looks, the line typed ahead runs in front. + freshProcessRowsReader: () => + Effect.sync(() => [{ ...processRow(shellPid, 1, "/bin/zsh"), status: "Ss" }]), + }); + const updates = yield* collectRunUpdates(manager); + const types = Ref.get(updates).pipe(Effect.map((list) => list.map((update) => update.type))); + yield* manager.startCommandRun(commandRunInput({ mode: "insert", command: "read answer" })); + const pty = ptyAdapter.processes[0]!; + shellPid = pty.pid; + pty.emitData("prompt % \u001b[?2004h"); + yield* waitFor(Effect.sync(() => pty.writes.length === 1)); + yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "\r" }); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("running")))); + // A builtin waiting for input runs no process: idle polls don't end it. + pty.emitData("read answer\u001b[?2004l\r\n"); + yield* Effect.sleep("250 millis"); + expect(yield* types).toEqual(["waiting", "running"]); + + // Answered, and the next command typed before the prompt is back: the + // command ends at that prompt, before the next one takes the terminal. + yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "yes\r" }); + yield* manager.write({ + threadId: "thread-1", + terminalId: "terminal-run", + data: "npm run dev\r", + }); + yield* Ref.set(nextCommandRunning, true); + pty.emitData("yes\r\nprompt % \u001b[?2004hnpm run dev\u001b[?2004l\r\nready on :3000\r\n"); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("finished")))); + expect((yield* Ref.get(updates)).at(-1)).toMatchObject({ + type: "finished", + output: "read answer\nyes\nprompt %", + }); + }), + ); + + it.effect("never takes an answer typed to the command for a line typed ahead", () => + Effect.gen(function* () { + const shellInFront = yield* Ref.make(false); + let shellPid = 0; + const { manager, ptyAdapter } = yield* createManager(50, { + platform: "darwin", + shellResolver: () => "/bin/zsh", + subprocessChecker: () => Ref.get(shellInFront).pipe(Effect.map((front) => !front)), + subprocessPollIntervalMs: 20, + freshProcessRowsReader: () => + Ref.get(shellInFront).pipe( + Effect.map((front) => [ + { ...processRow(shellPid, 1, "/bin/zsh"), status: front ? "Ss+" : "Ss" }, + ]), + ), + }); + const updates = yield* collectRunUpdates(manager); + const types = Ref.get(updates).pipe(Effect.map((list) => list.map((update) => update.type))); + yield* manager.startCommandRun(commandRunInput({ mode: "insert", command: "ssh build-box" })); + const pty = ptyAdapter.processes[0]!; + shellPid = pty.pid; + pty.emitData("prompt % \u001b[?2004h"); + yield* waitFor(Effect.sync(() => pty.writes.length === 1)); + yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "\r" }); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("running")))); + // The password is a line entered before any prompt; the remote shell's + // prompt then stays up for the user, who works there. + pty.emitData("ssh build-box\u001b[?2004l\r\npassword: "); + yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "secret\r" }); + pty.emitData("\r\nremote $ \u001b[?2004h"); + yield* Effect.sleep("100 millis"); + yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "ls\r" }); + pty.emitData("ls\u001b[?2004l\r\nfile\r\nremote $ \u001b[?2004h"); + yield* Effect.sleep("150 millis"); + expect(yield* types).toEqual(["waiting", "running"]); + + yield* Ref.set(shellInFront, true); + pty.emitData("logout\r\nprompt % \u001b[?2004h"); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("finished")))); + expect((yield* Ref.get(updates)).at(-1)).toMatchObject({ + type: "finished", + output: expect.stringContaining("remote $ ls\nfile"), + }); + }), + ); + + it.effect("ends a PowerShell command entered from an insert at its prompt's marker", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(50, { + platform: "win32", + shellResolver: () => "pwsh.exe", + subprocessChecker: () => Effect.succeed(false), + subprocessPollIntervalMs: 20, + }); + const updates = yield* collectRunUpdates(manager); + const types = Ref.get(updates).pipe(Effect.map((list) => list.map((update) => update.type))); + yield* manager.startCommandRun( + commandRunInput({ mode: "insert", dialect: "powershell", command: "gh auth login" }), ); - expect((yield* Ref.get(updates)).map((update) => update.type)).toEqual([ - "waiting", - "submitted", - ]); - expect(yield* manager.readCommandRunOutput("run-1")).toBe("git add .\ngit commit"); + const pty = ptyAdapter.processes[0]!; + pty.emitData("\u001b]633;D\u0007PS C:\\repo> "); + yield* waitFor(Effect.sync(() => pty.writes.length === 1)); + yield* manager.write({ threadId: "thread-1", terminalId: "terminal-run", data: "\r" }); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("running")))); + // A cmdlet has no process to find: polling never ends it, the prompt does. + yield* Effect.sleep("150 millis"); + expect(yield* types).toEqual(["waiting", "running"]); + pty.emitData("gh auth login\r\nLogged in\r\n\u001b]633;D\u0007PS C:\\repo> "); + yield* waitFor(types.pipe(Effect.map((list) => list.includes("finished")))); + expect((yield* Ref.get(updates)).at(-1)).toMatchObject({ + type: "finished", + exitCode: null, + output: expect.stringContaining("Logged in"), + }); }), ); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 0acdc7d19..b7c2a353d 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -246,6 +246,8 @@ interface TerminalSessionState { shellName: string | null; /** A suggested command this tab is carrying out (docs/terminal-command-runs.md). */ commandRun: ActiveCommandRun | null; + /** An `insert` the user pressed Enter on, followed until the command it started ends. */ + followedInsert: FollowedInsert | null; /** * The user's input reached this shell (keys or a paste; not the terminal's * own replies, nor a script Threadlines typed). Its folder, variables and @@ -304,6 +306,63 @@ interface ActiveCommandRun { outputStarted: boolean; } +/** + * An `insert` after the user's Enter. The tab is theirs from then on, like any + * line they type; the run only watches for the command it started to end, to + * report its output. PowerShell's prompt marker says so. A POSIX shell that + * switches its line editor on and off says when it reads a line again, and + * the process table then says whether that is its own prompt (the shell is + * the terminal's foreground job again) or a program in front of it that reads + * lines too (a REPL, ssh, a nested shell). A shell that says neither is done + * once polling sees nothing run under it. + */ +interface FollowedInsert { + readonly runId: string; + /** The shell it was entered in; a restart spawns another. */ + readonly pid: number; + /** When Enter was pressed. */ + readonly startedAt: string; + /** The tab's command generation from that Enter on. */ + readonly generation: number; + /** + * The shell reports its line editor, so the command ends only after it is + * back on: idle polls alone would end a builtin still waiting for input + * (`read`). + */ + readonly promptSignals: boolean; + /** The line editor came back on since that Enter. */ + promptBack: boolean; + /** + * A line was entered before the line editor came back: maybe typed ahead + * for the shell, which takes it the moment its prompt is back (and runs it + * in front, so the process table can't tell that prompt from a program), + * or maybe an answer to the command (a password). + */ + typedAhead: boolean; + /** + * Where the first prompt after a line typed ahead began, while the line + * editor stays on there and nobody types: switching off then means the + * shell took the queued line, so the command ended at that prompt. + */ + queuedLinePromptAt: number | null; +} + +/** A followed insert ending: what the tab showed from the insert on, rendered off the drain loop. */ +interface FollowedInsertEnd { + readonly kind: "finished" | "interrupted"; + readonly insert: FollowedInsert; + /** Null when the tab kept nothing from the insert on. */ + readonly output: InsertOutput | null; +} + +/** What a tab showed from an insert on, raw. */ +interface InsertOutput { + readonly raw: string; + /** The tab's history no longer reaches back to the insert. */ + readonly clipped: boolean; + readonly cols: number; +} + /** When the process-table poll next looks at a terminal, and why sooner. */ interface SubprocessPollSchedule { delayMs: number; @@ -348,6 +407,10 @@ type DrainProcessEventAction = data: string; commandFinished: boolean; runEnd: CommandRunEnd | null; + /** A followed insert whose command the prompt just reported done. */ + insertEnd: FollowedInsertEnd | null; + /** A followed insert whose shell's line editor just came back on, and where. */ + insertAtPrompt: { insert: FollowedInsert; endAt: number } | null; /** An `insert` whose shell just reached its prompt. */ insertReady: string | null; /** Ports this chunk says are taken, not yet looked up for this command. */ @@ -365,6 +428,7 @@ type DrainProcessEventAction = exitCode: number | null; exitSignal: number | null; runEnd: CommandRunEnd | null; + insertEnd: FollowedInsertEnd | null; }; /** `now`, or a millisecond past `previous` when the clock has not moved on. */ @@ -385,6 +449,36 @@ function appendRunOutput(run: ActiveCommandRun, text: string): void { } } +/** + * What the tab has shown since an insert went in, up to `endAt` (a position + * in everything it ever showed) or now; null when it never went into this tab. + */ +function insertOutputOf( + session: TerminalSessionState, + runId: string, + endAt?: number, +): InsertOutput | null { + const mark = session.insertMarks.get(runId); + if (mark === undefined) return null; + const base = session.historyAppendedTotal - session.history.length; + return { + raw: session.history.slice( + Math.max(0, mark - base), + endAt === undefined ? undefined : Math.max(0, endAt - base), + ), + clipped: mark < base, + cols: session.cols, + }; +} + +/** Takes the followed insert of this shell, if any, to end it. */ +function takeFollowedInsert(session: TerminalSessionState, pid: number): FollowedInsert | null { + const followed = session.followedInsert; + if (followed === null || followed.pid !== pid) return null; + session.followedInsert = null; + return followed; +} + /** A `run` is the tab's only activity while it lasts; clear it when the run ends. */ function clearRunActivity(session: TerminalSessionState): void { session.commandPendingPublished = false; @@ -881,6 +975,8 @@ function sanitizeTerminalHistoryChunk( commandFinishedGenerations: number[]; /** Line editor on/off switches, in order. */ lineEditorSignals: boolean[]; + /** The length of visible text before each of `lineEditorSignals`. */ + lineEditorSignalOffsets: number[]; /** End-of-run markers, with the length of visible text before each. */ runMarkers: Array; } { @@ -889,6 +985,7 @@ function sanitizeTerminalHistoryChunk( let visibleText = ""; const commandFinishedGenerations: number[] = []; const lineEditorSignals: boolean[] = []; + const lineEditorSignalOffsets: number[] = []; const runMarkers: Array = []; let index = 0; @@ -910,6 +1007,7 @@ function sanitizeTerminalHistoryChunk( : null, commandFinishedGenerations, lineEditorSignals, + lineEditorSignalOffsets, runMarkers, }; }; @@ -934,7 +1032,10 @@ function sanitizeTerminalHistoryChunk( const sequence = input.slice(index, cursor + 1); const body = input.slice(index + 2, cursor); const lineEditorSignal = lineEditorSignalOf(body, input[cursor] ?? ""); - if (lineEditorSignal !== null) lineEditorSignals.push(lineEditorSignal); + if (lineEditorSignal !== null) { + lineEditorSignals.push(lineEditorSignal); + lineEditorSignalOffsets.push(visibleText.length); + } if (!shouldStripCsiSequence(body, input[cursor] ?? "")) { append(sequence); } @@ -991,7 +1092,10 @@ function sanitizeTerminalHistoryChunk( const sequence = input.slice(index, cursor + 1); const body = input.slice(index + 1, cursor); const lineEditorSignal = lineEditorSignalOf(body, input[cursor] ?? ""); - if (lineEditorSignal !== null) lineEditorSignals.push(lineEditorSignal); + if (lineEditorSignal !== null) { + lineEditorSignals.push(lineEditorSignal); + lineEditorSignalOffsets.push(visibleText.length); + } if (!shouldStripCsiSequence(body, input[cursor] ?? "")) { append(sequence); } @@ -1276,6 +1380,7 @@ function createSessionState(input: { historyAppendedTotal: input.history.length, shellName: null, commandRun: null, + followedInsert: null, insertMarks: new Map(), typedIn: false, scriptPending: false, @@ -2507,6 +2612,99 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ); }).pipe(Effect.forkIn(workerScope), Effect.asVoid); + /** + * Renders what the tab showed from an insert on and reports how the command + * the user entered ended, off the drain loop. A shell can't say its exit + * code, so a finished insert has none. + */ + const endFollowedInsert = (end: FollowedInsertEnd) => + Effect.gen(function* () { + const at = yield* nowIso; + const { runId, startedAt } = end.insert; + const captured = end.output; + const output = + captured === null + ? null + : clipCommandOutput( + yield* Effect.promise(() => renderTerminalText(captured.raw, captured.cols)), + captured.clipped, + ); + yield* publishRunUpdate( + end.kind === "finished" + ? { type: "finished", runId, at, startedAt, exitCode: null, output: output ?? "" } + : { type: "interrupted", runId, at, startedAt, output }, + ); + }).pipe(Effect.forkIn(workerScope), Effect.asVoid); + + /** + * Whether a shell is its terminal's foreground job, from a fresh process + * table (`+` in its state): no program it started runs in front of it. + * Null where that can't be read (Windows, a failed read). + */ + const shellInForeground = (pid: number) => + platform === "win32" + ? Effect.succeed(null) + : freshProcessRowsReader(platform).pipe( + Effect.withTracerEnabled(false), + Effect.map((rows) => { + const row = rows.find((entry) => entry.pid === pid); + return row === undefined ? null : row.status.includes("+"); + }), + Effect.catch((reason) => + Effect.logWarning("failed to check the terminal's foreground job", { + pid, + reason, + }).pipe(Effect.as(null)), + ), + ); + + /** + * The line editor came back on after an entered insert (at `endAt`): when + * the shell is in front again, it is at its own prompt and the command is + * over (a job it left in the background is not part of it). Otherwise a + * program it started reads lines, and the next time the line editor comes + * back on looks again. When the table can't be read, polling looks + * instead (see publishSubprocessActivityIfChanged), armed again in case + * it had stopped. PowerShell's prompt marker ends it there. + */ + const checkFollowedInsertAtPrompt = ( + session: TerminalSessionState, + insert: FollowedInsert, + endAt: number, + ) => + Effect.gen(function* () { + if (platform === "win32") return; + const inFront = yield* shellInForeground(insert.pid); + if (session.followedInsert !== insert || session.pid !== insert.pid) return; + if (inFront === null) { + session.subprocessPollingArmed = true; + session.consecutiveSubprocessIdlePolls = 0; + session.subprocessPoll = freshSubprocessPollSchedule(); + return; + } + if (!inFront) return; + const ended = takeFollowedInsert(session, insert.pid); + if (ended === null) return; + yield* endFollowedInsert({ + kind: "finished", + insert: ended, + output: insertOutputOf(session, ended.runId, endAt), + }); + }).pipe(Effect.forkIn(workerScope), Effect.asVoid); + + /** Ends a followed insert when its shell stops, with what the tab showed until then. */ + const interruptFollowedInsert = (session: TerminalSessionState, pid: number | null) => + Effect.suspend(() => { + const insert = pid === null ? null : takeFollowedInsert(session, pid); + return insert === null + ? Effect.void + : endFollowedInsert({ + kind: "interrupted", + insert, + output: insertOutputOf(session, insert.runId), + }); + }); + /** * Types a pending `insert` at the prompt of the process it was meant for: * as a bracketed paste when the line editor is reading (so no line runs @@ -2661,6 +2859,37 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith for (const signal of sanitized.lineEditorSignals) { session.lineEditorActive = signal; } + // An entered insert's shell switching its line editor in output + // printed after that Enter (a line typed ahead since counts too). + // Back on, it may be at its next prompt: checked right away, before + // the user can start something else there. The output ends where + // that prompt's line editor began. + const followed = session.followedInsert; + let insertAtPrompt: { insert: FollowedInsert; endAt: number } | null = null; + let queuedLineTakenAt: number | null = null; + const signals = sanitized.lineEditorSignals; + if ( + followed !== null && + followed.pid === expectedPid && + signals.length > 0 && + nextEvent.commandGeneration >= followed.generation + ) { + const chunkStart = session.historyAppendedTotal - sanitized.visibleText.length; + const firstOn = signals.indexOf(true); + if (followed.queuedLinePromptAt !== null && signals[0] === false) { + queuedLineTakenAt = followed.queuedLinePromptAt; + } else if (firstOn >= 0) { + const endAt = chunkStart + sanitized.lineEditorSignalOffsets[firstOn]!; + const firstPrompt = !followed.promptBack; + followed.promptBack = true; + if (firstPrompt && followed.typedAhead && signals.slice(firstOn).includes(false)) { + queuedLineTakenAt = endAt; + } else { + if (firstPrompt && followed.typedAhead) followed.queuedLinePromptAt = endAt; + insertAtPrompt = { insert: followed, endAt }; + } + } + } // A suggested command in this tab: a `run` collects its output up // to its own end marker; an `insert` waits for the first prompt. @@ -2731,6 +2960,26 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.consecutiveSubprocessIdlePolls = 0; session.terminalCommandInputState = createTerminalCommandInputState(); } + // The prompt reported the entered command done (PowerShell), or the + // shell took a line typed ahead at its prompt. Read now, before later + // output belongs to whatever comes next. + const finishedInsert = + commandFinished || queuedLineTakenAt !== null + ? takeFollowedInsert(session, expectedPid) + : null; + if (finishedInsert !== null) insertAtPrompt = null; + const insertEnd: FollowedInsertEnd | null = + finishedInsert === null + ? null + : { + kind: "finished", + insert: finishedInsert, + output: insertOutputOf( + session, + finishedInsert.runId, + commandFinished ? undefined : (queuedLineTakenAt ?? undefined), + ), + }; // The chunk's event carries the same time the snapshot now does, // later than anything before it: a client that opens the tab // after this chunk replays only the events its snapshot lacks. @@ -2746,6 +2995,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith data: nextEvent.data, commandFinished: commandFinished || (runEnd !== null && runEnd.run.mode === "run"), runEnd, + insertEnd, + insertAtPrompt, insertReady, portsInUse, commandGeneration: session.commandGeneration, @@ -2772,6 +3023,16 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith : null, cols: session.cols, }; + // So does a command the user entered from an insert. + const endedInsert = takeFollowedInsert(session, expectedPid); + const insertEnd: FollowedInsertEnd | null = + endedInsert === null + ? null + : { + kind: "interrupted", + insert: endedInsert, + output: insertOutputOf(session, endedInsert.runId), + }; const process = session.process; cleanupProcessHandles(session); @@ -2811,6 +3072,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith exitCode: session.exitCode, exitSignal: session.exitSignal, runEnd, + insertEnd, } as const; }); @@ -2846,6 +3108,16 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (action.runEnd !== null) { yield* endCommandRun(action.runEnd); } + if (action.insertEnd !== null) { + yield* endFollowedInsert(action.insertEnd); + } + if (action.insertAtPrompt !== null) { + yield* checkFollowedInsertAtPrompt( + session, + action.insertAtPrompt.insert, + action.insertAtPrompt.endAt, + ); + } if (action.insertReady !== null) { yield* insertCommand(session, action.insertReady, expectedPid); } @@ -2866,6 +3138,9 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (action.runEnd !== null) { yield* endCommandRun(action.runEnd); } + if (action.insertEnd !== null) { + yield* endFollowedInsert(action.insertEnd); + } yield* clearKillFiber(action.process); const createdAt = yield* nowIso; yield* publishEvent({ @@ -2921,6 +3196,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const updatedAt = yield* nowIso; const stoppedRun = session.commandRun; + // Before its pid goes: a command the user entered ends with the shell. + yield* interruptFollowedInsert(session, session.pid); yield* modifyManagerState((state) => { session.commandRun = null; session.lineEditorActive = null; @@ -3275,6 +3552,9 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const terminalPid = session.pid; const updatedAt = yield* nowIso; const createdAt = yield* nowIso; + // A command the user entered from an insert can end where polling stops + // looking. (Set inside the update; the cast keeps it from reading as null.) + let insertEnd = null as FollowedInsertEnd | null; const event = yield* modifyManagerState((state) => { const liveSession: Option.Option = Option.fromNullishOr( state.sessions.get(toSessionKey(session.threadId, session.terminalId)), @@ -3308,6 +3588,21 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith return [Option.none(), state] as const; } liveSession.value.subprocessPollingArmed = false; + // Where the shell reports its line editor, only once it was back on + // (normally the prompt check ends it first; this covers a process + // table that couldn't be read). + const followed = liveSession.value.followedInsert; + const ended = + followed !== null && (!followed.promptSignals || followed.promptBack) + ? takeFollowedInsert(liveSession.value, terminalPid) + : null; + if (ended !== null) { + insertEnd = { + kind: "finished", + insert: ended, + output: insertOutputOf(liveSession.value, ended.runId), + }; + } } const command = activity.hasRunningSubprocess @@ -3371,6 +3666,9 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith yield* publishEvent(event.value); yield* syncCatalogCommands(session.threadId, session.terminalId); } + if (insertEnd !== null) { + yield* endFollowedInsert(insertEnd); + } }); /** Tells clients a command was entered and may be about to run. */ @@ -3932,12 +4230,16 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.commandRun?.mode === "insert" && session.commandRun.phase === "waiting" ? session.commandRun : null; - if (waitingInsert !== null && (result.didSubmit || input.data.includes("\u0003"))) { - // The user ran the command they were given (or cleared it); from here - // the tab is theirs, so the insert is no longer followed. + // The user ran the command they were given (followed below, once the + // line is counted) or cleared it. Either way the tab is theirs from + // here, like any line they type. + const enteredInsert = waitingInsert !== null && result.didSubmit ? waitingInsert : null; + if (enteredInsert !== null) { + session.commandRun = null; + } else if (waitingInsert !== null && input.data.includes("\u0003")) { session.commandRun = null; yield* publishRunUpdate({ - type: result.didSubmit ? "submitted" : "cancelled", + type: "cancelled", runId: waitingInsert.runId, at: yield* nowIso, }); @@ -3988,6 +4290,35 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith yield* publishCommandPending(session as TerminalSessionState & { pid: number }); } } + const followed = session.followedInsert; + if (followed !== null && !replyOnly) { + if (result.didSubmit && !followed.promptBack) followed.typedAhead = true; + // Typed at the prompt that came back: no queued line is taken there. + if (followed.promptBack) followed.queuedLinePromptAt = null; + } + if (enteredInsert !== null) { + const at = yield* nowIso; + // Followed while the tab follows the line just entered: PowerShell's + // prompt marker or the POSIX prompt coming back ends it (FollowedInsert). + if ( + session.pid !== null && + (!session.commandCompletionMarkersEnabled || session.hasRunningSubprocess) + ) { + session.followedInsert = { + runId: enteredInsert.runId, + pid: session.pid, + startedAt: at, + generation: session.commandGeneration, + promptSignals: session.lineEditorActive !== null, + promptBack: false, + typedAhead: false, + queuedLinePromptAt: null, + }; + yield* publishRunUpdate({ type: "running", runId: enteredInsert.runId, at }); + } else { + yield* publishRunUpdate({ type: "submitted", runId: enteredInsert.runId, at }); + } + } yield* Effect.sync(() => process.write(input.data)); }, ); @@ -4360,15 +4691,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (run?.runId === runId && run.mode === "run") { return { raw: run.output, clipped: run.outputClipped, cols: session.cols }; } - const mark = session.insertMarks.get(runId); - if (mark !== undefined) { - const base = session.historyAppendedTotal - session.history.length; - return { - raw: session.history.slice(Math.max(0, mark - base)), - clipped: mark < base, - cols: session.cols, - }; - } + const inserted = insertOutputOf(session, runId); + if (inserted !== null) return inserted; } return null; }), diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index a34751877..d6adb237b 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -111,7 +111,10 @@ export interface TerminalCommandRunInput { /** * How a run moved on. `output` is the rendered text (redraws collapsed, end - * kept) a `run` left when it stopped. + * kept) a `run` left when it stopped, or what an `insert`'s tab showed from + * the insert on. An insert is `waiting` at the prompt, then `running` from + * the user's Enter until the command it started ends (`finished`, with no exit + * code); `submitted` when the shell can't say when that is. */ export type TerminalCommandRunUpdate = | { readonly type: "running"; readonly runId: string; readonly at: string } @@ -268,8 +271,8 @@ export interface TerminalManagerShape { /** * The output a run has so far, while its tab is open: a `run` still going, - * or everything an `insert`'s tab printed since the command went in. - * Null once the tab is gone. + * or everything an `insert`'s tab printed since the command went in (until + * now, also after its command ended). Null once the tab is gone. */ readonly readCommandRunOutput: (runId: string) => Effect.Effect; diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx index a35114380..f111d8a74 100644 --- a/apps/web/src/components/ChatMarkdown.browser.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.tsx @@ -1348,6 +1348,7 @@ describe("ChatMarkdown code block commands", () => { const REPLY = MessageId.make("reply-1"); const actionsWith = (runs: ReadonlyArray = []): CommandRunActions => ({ supported: true, + followsInserts: true, dialect: "posix", cwdLabel: "~/repo", runs, diff --git a/apps/web/src/components/chat/CommandRuns.browser.tsx b/apps/web/src/components/chat/CommandRuns.browser.tsx index 37b3ab373..295f6eb91 100644 --- a/apps/web/src/components/chat/CommandRuns.browser.tsx +++ b/apps/web/src/components/chat/CommandRuns.browser.tsx @@ -29,6 +29,7 @@ const request = (command: string): OrchestrationCommandRequest => ({ const actionsWith = (runs: ReadonlyArray = []): CommandRunActions => ({ supported: true, + followsInserts: true, dialect: "posix", cwdLabel: "~/repo", runs, @@ -81,6 +82,10 @@ describe("CommandRequestRow", () => { .element(page.getByRole("button", { name: "Put in terminal" })) .toBeInTheDocument(); expect(page.getByRole("button", { name: "Run", exact: true }).elements()).toHaveLength(0); + // Entered from the terminal, it still answers the agent by itself. + await expect + .element(page.getByText("Codex gets the output when it finishes")) + .toBeInTheDocument(); } finally { await screen.unmount(); } diff --git a/apps/web/src/components/chat/CommandRuns.tsx b/apps/web/src/components/chat/CommandRuns.tsx index c6497ea68..66a3dd3b0 100644 --- a/apps/web/src/components/chat/CommandRuns.tsx +++ b/apps/web/src/components/chat/CommandRuns.tsx @@ -43,6 +43,8 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; export interface CommandRunActions { /** The thread's server runs commands and the thread has a folder to run them in. */ readonly supported: boolean; + /** The server follows a command put in the terminal to its end, so a card's output goes back by itself. */ + readonly followsInserts: boolean; /** The shell family the server's terminal speaks. */ readonly dialect: CommandDialect; /** The folder runs start in, shortened for display (e.g. `~/badcode`). */ @@ -146,13 +148,18 @@ const CommandRunStatusLine = memo(function CommandRunStatusLine(props: { text = `Ran in ${where}`; break; case "finished": - dot = run.exitCode === null || run.exitCode === 0 ? "success" : "failure"; - text = - run.exitCode === null || run.exitCode === 0 - ? `Finished in ${where}` - : run.exitCode === 130 - ? `Stopped in ${where}` - : `Exited with code ${run.exitCode} in ${where}`; + if (run.mode === "insert") { + // The shell it was typed into never says how it went. + text = `Ran in ${where}`; + } else { + dot = run.exitCode === null || run.exitCode === 0 ? "success" : "failure"; + text = + run.exitCode === null || run.exitCode === 0 + ? `Finished in ${where}` + : run.exitCode === 130 + ? `Stopped in ${where}` + : `Exited with code ${run.exitCode} in ${where}`; + } if (duration !== null) text += ` · ${duration}`; break; case "cancelled": @@ -176,6 +183,10 @@ const CommandRunStatusLine = memo(function CommandRunStatusLine(props: { run.status === "submitted" || ((run.status === "finished" || run.status === "interrupted") && run.hasOutput)); const autoSendPending = run.autoSend && !sent && run.status !== "finished"; + // Output on its way by itself. A command still going can send what it has + // so far (a dev server never finishes); one not entered yet has nothing. + const sendsItself = autoSendPending && (run.status === "running" || run.status === "waiting"); + const sendable = canSend && !(sendsItself && run.status === "waiting"); const held = run.heldReason === "stopped" ? `You pressed Stop, so it wasn't sent to ${agent}.` @@ -204,10 +215,8 @@ const CommandRunStatusLine = memo(function CommandRunStatusLine(props: { {text} {sent ? · Sent to {agent} : null} {held !== null && !sent ? · {held} : null} - {autoSendPending && run.status === "running" ? ( - · {agent} gets the output when it finishes - ) : null} - {canSend && !(autoSendPending && run.status === "running") ? ( + {sendsItself ? · {agent} gets the output when it finishes : null} + {sendable ? ( <>