Skip to content

The agent that grows with you

fix(desktop): preserve terminal startup output

Gillef98f5e74e00e
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 8017435b891..9998a1176bd 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -350,6 +350,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
}
},
terminal: {
+ attach: id => ipcRenderer.invoke('hermes:terminal:attach', id),
cwd: id => ipcRenderer.invoke('hermes:terminal:cwd', id),
dispose: id => ipcRenderer.invoke('hermes:terminal:dispose', id),
resize: (id, size) => ipcRenderer.invoke('hermes:terminal:resize', id, size),
diff --git a/apps/desktop/electron/terminal-ipc.ts b/apps/desktop/electron/terminal-ipc.ts
index 0028cf45c65..9dc7e2851f6 100644
--- a/apps/desktop/electron/terminal-ipc.ts
+++ b/apps/desktop/electron/terminal-ipc.ts
@@ -13,6 +13,7 @@ import nodePty from 'node-pty'
import { resolveTerminalConnectionForSender } from './connection-apply'
import { ensureSpawnHelperExecutable } from './spawn-helper-perms'
import { buildInteractiveSshArgs } from './ssh-connection'
+import { createTerminalOutputGate } from './terminal-output-gate'
import { buildWindowsInteractiveCommand } from './windows-remote-lifecycle'
export interface TerminalIpcDeps {
@@ -312,12 +313,6 @@ export function registerTerminalIpc({
)
: nodePty.spawn(command, args, { cols, cwd, env: terminalShellEnv(), name: 'xterm-256color', rows })
- terminalSessions.set(id, {
- pty: ptyProcess,
- webContentsId: event.sender.id,
- ...(remote ? { sshScope: sshTarget.scope, remoteCwd: String(payload?.cwd || '') } : {})
- })
-
const send = (suffix, payload) => {
if (event.sender.isDestroyed()) {
return
@@ -326,16 +321,40 @@ export function registerTerminalIpc({
event.sender.send(terminalChannel(id, suffix), payload)
}
- ptyProcess.onData(data => send('data', data))
+ const outputGate = createTerminalOutputGate({
+ onExitFlushed: () => terminalSessions.delete(id),
+ sendData: data => send('data', data),
+ sendExit: payload => send('exit', payload)
+ })
+
+ terminalSessions.set(id, {
+ outputGate,
+ pty: ptyProcess,
+ webContentsId: event.sender.id,
+ ...(remote ? { sshScope: sshTarget.scope, remoteCwd: String(payload?.cwd || '') } : {})
+ })
+
+ ptyProcess.onData(data => outputGate.data(data))
ptyProcess.onExit(({ exitCode, signal }) => {
- terminalSessions.delete(id)
- send('exit', { code: exitCode, signal: signal || null })
+ outputGate.exit({ code: exitCode, signal: signal == null ? null : String(signal) })
})
event.sender.once('destroyed', () => disposeTerminalSession(id))
return { cwd: remote ? null : cwd, id, shell: remote ? 'ssh' : name }
})
+ ipcMain.handle('hermes:terminal:attach', (event, id) => {
+ const sessionInfo = terminalSessions.get(String(id || ''))
+
+ if (!sessionInfo || sessionInfo.webContentsId !== event.sender.id) {
+ return false
+ }
+
+ sessionInfo.outputGate.attach()
+
+ return true
+ })
+
ipcMain.handle('hermes:terminal:write', (_event, id, data) => {
const sessionInfo = terminalSessions.get(String(id || ''))
diff --git a/apps/desktop/electron/terminal-output-gate.test.ts b/apps/desktop/electron/terminal-output-gate.test.ts
new file mode 100644
index 00000000000..87f5718ca94
--- /dev/null
+++ b/apps/desktop/electron/terminal-output-gate.test.ts
@@ -0,0 +1,57 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { createTerminalOutputGate } from './terminal-output-gate'
+
+test('holds the initial shell prompt until the renderer attaches', () => {
+ const events: string[] = []
+
+ const gate = createTerminalOutputGate({
+ onExitFlushed: () => events.push('cleanup'),
+ sendData: data => events.push(`data:${data}`),
+ sendExit: payload => events.push(`exit:${payload.code}`)
+ })
+
+ gate.data('$ ')
+ assert.deepEqual(events, [])
+
+ gate.attach()
+ assert.deepEqual(events, ['data:$ '])
+
+ gate.data('pwd\r\n')
+ assert.deepEqual(events, ['data:$ ', 'data:pwd\r\n'])
+})
+
+test('flushes buffered output before an early shell exit', () => {
+ const events: string[] = []
+
+ const gate = createTerminalOutputGate({
+ onExitFlushed: () => events.push('cleanup'),
+ sendData: data => events.push(`data:${data}`),
+ sendExit: payload => events.push(`exit:${payload.code}:${payload.signal}`)
+ })
+
+ gate.data('startup failed\r\n')
+ gate.exit({ code: 1, signal: null })
+ assert.deepEqual(events, [])
+
+ gate.attach()
+ assert.deepEqual(events, ['data:startup failed\r\n', 'exit:1:null', 'cleanup'])
+})
+
+test('attach is idempotent and never replays startup output twice', () => {
+ const events: string[] = []
+
+ const gate = createTerminalOutputGate({
+ onExitFlushed: () => events.push('cleanup'),
+ sendData: data => events.push(`data:${data}`),
+ sendExit: payload => events.push(`exit:${payload.code}`)
+ })
+
+ gate.data('$ ')
+ gate.attach()
+ gate.attach()
+
+ assert.deepEqual(events, ['data:$ '])
+})
diff --git a/apps/desktop/electron/terminal-output-gate.ts b/apps/desktop/electron/terminal-output-gate.ts
new file mode 100644
index 00000000000..4cbf5a13f6b
--- /dev/null
+++ b/apps/desktop/electron/terminal-output-gate.ts
@@ -0,0 +1,62 @@
+export interface TerminalExitPayload {
+ code: number | null
+ signal: string | null
+}
+
+interface TerminalOutputGateOptions {
+ onExitFlushed: () => void
+ sendData: (data: string) => void
+ sendExit: (payload: TerminalExitPayload) => void
+}
+
+const MAX_PENDING_OUTPUT = 1024 * 1024
+
+export function createTerminalOutputGate({ onExitFlushed, sendData, sendExit }: TerminalOutputGateOptions) {
+ let attached = false
+ let pendingData = ''
+ let pendingExit: TerminalExitPayload | null = null
+
+ const flushExit = (payload: TerminalExitPayload) => {
+ sendExit(payload)
+ onExitFlushed()
+ }
+
+ return {
+ attach(): void {
+ if (attached) {
+ return
+ }
+
+ attached = true
+
+ if (pendingData) {
+ sendData(pendingData)
+ pendingData = ''
+ }
+
+ if (pendingExit) {
+ const payload = pendingExit
+ pendingExit = null
+ flushExit(payload)
+ }
+ },
+ data(chunk: string): void {
+ if (attached) {
+ sendData(chunk)
+
+ return
+ }
+
+ pendingData = `${pendingData}${chunk}`.slice(-MAX_PENDING_OUTPUT)
+ },
+ exit(payload: TerminalExitPayload): void {
+ if (attached) {
+ flushExit(payload)
+
+ return
+ }
+
+ pendingExit = payload
+ }
+ }
+}
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
index 9f9aec104ec..efa82cd232d 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
@@ -854,7 +854,7 @@ export function useTerminalSession({
// user last `cd`'d; the main side falls back to the launch cwd (then
// home) if that dir no longer exists.
.start({ cols: term.cols, cwd: initialRestoreCwdRef.current || cwd, rows: term.rows })
- .then(session => {
+ .then(async session => {
if (disposed) {
void terminalApi.dispose(session.id)
@@ -871,8 +871,6 @@ export function useTerminalSession({
selectionRef.current = initial
selectionLabelRef.current = initial ? terminalSelectionLabel(term, shellNameRef.current, initial) : ''
- setStatus('open')
-
cleanup.push(
terminalApi.onData(session.id, data => {
armedWrite(data)
@@ -892,6 +890,14 @@ export function useTerminalSession({
})
)
+ const attached = await terminalApi.attach(session.id)
+
+ if (!attached) {
+ throw new Error('Terminal session disappeared before its output stream attached')
+ }
+
+ setStatus('open')
+
window.requestAnimationFrame(() => {
term.clearSelection() // drop any selection painted over transient boot rows
})
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index d3d00e635f6..53c17ad4b16 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -426,6 +426,7 @@ declare global {
) => Promise<{ root: string; label: string }[]>
}
terminal: {
+ attach: (id: string) => Promise<boolean>
/** Best-effort current working directory of the live PTY child (POSIX
* only; null on Windows or when unavailable). Used to reopen a tab
* where the user last `cd`'d. */