Skip to content

The agent that grows with you

fix(webapp): close the browser terminal tab when its host shell exits

unsupportedpastels14c34063a918
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx
index c7f5da78d34..74dce944a99 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx
@@ -299,6 +299,21 @@ it('replays server history once, suppresses parser replies, and detaches on remo
expect(Socket.instances[2].url.searchParams.has('attach')).toBe(false)
})
+// Typing `exit` ends the host shell: the tab closes as it does in native Desktop, instead of
+// staying open as an expired terminal.
+it('closes a persistent browser tab when its host shell exits', async () => {
+ seedWebappSession('test-token')
+ Socket.persistent = true
+ vi.stubGlobal('WebSocket', Socket)
+ installBrowserDesktopBridge()
+ const id = createTerminal('/work')
+ render(<Harness id={id} />)
+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())
+ act(() => Socket.instances[0].close(4410, 'Process exited'))
+ expect($terminals.get().some(tab => tab.id === id)).toBe(false)
+ expect(emulator.output).not.toContain('Press Enter to create a new shell')
+})
+
it('close others and close all terminate mounted and unmounted persisted shells', async () => {
seedWebappSession('test-token')
Socket.persistent = true
diff --git a/apps/desktop/src/lib/browser-terminal.test.ts b/apps/desktop/src/lib/browser-terminal.test.ts
index 2afbbdeeb81..68a7ed21fea 100644
--- a/apps/desktop/src/lib/browser-terminal.test.ts
+++ b/apps/desktop/src/lib/browser-terminal.test.ts
@@ -187,6 +187,31 @@ describe('persistent browser terminals', () => {
expect(localStorage.length).toBe(0)
})
+ // The server closes with 4410 both when the shell exits (`exit`, Ctrl-D) and when it ends the
+ // shell itself (expiry, a deleted profile, shutdown); only an exit carries the reason.
+ it('reports a host shell that exited as an exit, as native Desktop does, and forgets it', async () => {
+ const api = install()
+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })
+ const exit = vi.fn()
+ api.onExit(session.id, exit)
+ Socket.instances[0].close(4410, 'Process exited')
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(Socket.instances).toHaveLength(1)
+ expect(exit).toHaveBeenCalledExactlyOnceWith({ code: null, signal: null })
+ expect(localStorage.length).toBe(0)
+ })
+
+ it('reports a 4410 close without the exit reason as expired', async () => {
+ const api = install()
+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })
+ const exit = vi.fn()
+ api.onExit(session.id, exit)
+ Socket.instances[0].close(4410)
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(Socket.instances).toHaveLength(1)
+ expect(exit).toHaveBeenCalledExactlyOnceWith({ code: null, signal: 'expired' })
+ })
+
it('never retries denied attachments or silently adopts the active profile', async () => {
const api = install()
const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })
diff --git a/apps/desktop/src/lib/browser-terminal.ts b/apps/desktop/src/lib/browser-terminal.ts
index 0e8df7b695a..ecf437a55b7 100644
--- a/apps/desktop/src/lib/browser-terminal.ts
+++ b/apps/desktop/src/lib/browser-terminal.ts
@@ -47,6 +47,9 @@ interface TerminalState {
}
const META = '\u0000HERMES_TERMINAL_META:'
+// 4410 also ends a shell the server closed (expiry, a deleted profile, shutdown); only a shell
+// that exited by itself (`exit`, Ctrl-D) carries this reason (pty_session.WS_CLOSE_PROCESS_EXITED_REASON).
+const PROCESS_EXITED_REASON = 'Process exited'
const MAX_RETRIES = 5
const RETRY_BACKOFF = { baseDelayMs: 500, capMs: 8000 }
const START_TIMEOUT = 10_000
@@ -267,6 +270,9 @@ async function dialTerminal(state: TerminalState, context: DialContext): Promise
if (!state.terminalId) {
finish(state, event.code === 4410 ? null : 'disconnected')
+ } else if (event.code === 4410 && event.reason === PROCESS_EXITED_REASON) {
+ // The shell ended: report a process exit, which closes the tab as in native Desktop.
+ finish(state, null)
} else if (signal !== 'disconnected') {
finish(state, signal)
} else {
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.py
index 7b030197574..3d6d1aa7f28 100644
--- a/hermes_cli/pty_session.py
+++ b/hermes_cli/pty_session.py
@@ -19,6 +19,9 @@ from fastapi import WebSocketDisconnect
logger = logging.getLogger(__name__)
WS_CLOSE_PROCESS_EXITED = 4410
+# 4410 also ends a session the server closed (expiry, a deleted profile, shutdown). Only a child
+# that exited by itself carries this reason, so the Webapp terminal can close its tab on `exit`.
+WS_CLOSE_PROCESS_EXITED_REASON = "Process exited"
WS_CLOSE_SUPERSEDED = 4409
# Going Away: the viewer stopped taking output, but its session lives on and the same
# token reattaches. The dashboard chat tab and the Webapp terminal both redial on 1001;
@@ -140,7 +143,7 @@ class PtySession:
ws = self._ws
async with self._output_lock:
if self._ws is ws:
- await _close_ws(ws, WS_CLOSE_PROCESS_EXITED)
+ await _close_ws(ws, WS_CLOSE_PROCESS_EXITED, WS_CLOSE_PROCESS_EXITED_REASON)
return
if not chunk: # idle tick
await asyncio.sleep(0)
@@ -275,7 +278,7 @@ class PtySession:
return False
if not self.alive:
self.detach(ws)
- await _close_ws(ws, WS_CLOSE_PROCESS_EXITED)
+ await _close_ws(ws, WS_CLOSE_PROCESS_EXITED, WS_CLOSE_PROCESS_EXITED_REASON)
return False
if force_redraw:
return await self.write(ws, TUI_FORCE_REDRAW)
diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.py
index 20e09070e1f..a2bd810bcd4 100644
--- a/tests/hermes_cli/test_pty_session.py
+++ b/tests/hermes_cli/test_pty_session.py
@@ -58,6 +58,7 @@ class FakeWS:
def __init__(self):
self.sent = [] # list of ("bytes"|"text", payload)
self.close_code = None
+ self.close_reason = None
async def send_bytes(self, data):
self.sent.append(("bytes", bytes(data)))
@@ -67,6 +68,7 @@ class FakeWS:
async def close(self, code=1000, reason=""):
self.close_code = code
+ self.close_reason = reason
class FailingWS(FakeWS):
@@ -519,6 +521,46 @@ async def test_eof_marks_dead_and_closes_socket_4410():
await s.close()
+# 4410 also ends a shell the server closed (expiry, a deleted profile, shutdown). Only a shell that
+# exited by itself says so in the close reason, so a viewer can end its tab the way native Desktop
+# does when its shell exits, and keep the tab for the other cases.
+async def test_eof_close_says_the_process_exited():
+ from hermes_cli.pty_session import PtySession
+ s = PtySession("k", FakeBridge([b"logout", None]), buffer_cap=1024, read_timeout=0.01)
+ await s.start()
+ ws = FakeWS()
+ await s.attach(ws)
+ await async_wait_until(lambda: ws.close_code is not None, timeout=2.0)
+ assert (ws.close_code, ws.close_reason) == (4410, "Process exited")
+ await s.close()
+
+
+async def test_attaching_to_a_shell_that_exited_while_detached_says_it_exited():
+ from hermes_cli.pty_session import PtySession
+ s = PtySession("k", FakeBridge([b"logout", None]), buffer_cap=1024, read_timeout=0.01)
+ await s.start()
+ await async_wait_until(lambda: not s.alive, timeout=2.0)
+ ws = FakeWS()
+ assert await s.attach(ws, initial_text="meta") is False
+ assert ws.sent == [("text", "meta"), ("bytes", b"logout")]
+ assert (ws.close_code, ws.close_reason) == (4410, "Process exited")
+ await s.close()
+
+
+async def test_a_server_close_keeps_4410_without_the_exit_reason():
+ from hermes_cli.pty_session import PtySession
+ s = PtySession("k", FakeBridge([]), buffer_cap=1024, read_timeout=0.01)
+ await s.start()
+ ws = FakeWS()
+ await s.attach(ws)
+ await s.close()
+ assert ws.close_code == 4410
+ assert ws.close_reason != "Process exited"
+
+
from hermes_cli.pty_session import PtySessionRegistry, RegistryFull