The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): close the tab of a host shell that exited while it was away
unsupportedpastels19c077149465
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.tsindex a70b0f67d3f..47b62fa0400 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.ts@@ -243,10 +243,13 @@ export function createSessionAttemptController(}release()- const expired = error && typeof error === 'object' && 'signal' in error && error.signal === 'expired'+ const signal = error && typeof error === 'object' && 'signal' in error ? error.signal : nullconst message = error instanceof Error ? error.message : String(error)- if (expired) {+ if (signal === 'exited') {+ // The shell exited while no tab was attached: close the tab, as an attached exit does.+ removeExitedTerminal(id)+ } else if (signal === 'expired') {resumeOnly = falsearmRetry(TERMINAL_EXIT_MESSAGES.expired)} else if (isBrowserHostedDesktop()) {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.tsxindex 74dce944a99..eefa28d78f8 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@@ -94,6 +94,8 @@ class Socket {static OPEN = 1static instances: Socket[] = []static persistent = false+ // Set: every new socket is closed with this instead of answering.+ static refusal: [number, string] | null = nullurl: URLsent: string[] = []readyState = 1@@ -103,6 +105,12 @@ class Socket {this.url = new URL(url)Socket.instances.push(this)queueMicrotask(() => {+ if (Socket.refusal) {+ this.close(...Socket.refusal)++ return+ }+const metadata = Socket.persistent? { shell: 'fish', cwd: '/work', terminalId: this.url.searchParams.get('attach') || `shell-${Socket.instances.length}`, closed: this.url.searchParams.get('action') === 'close' }: { shell: 'fish' }@@ -169,6 +177,7 @@ afterEach(() => {$terminals.set([])Socket.instances = []Socket.persistent = false+ Socket.refusal = nullemulator.output = ''vi.unstubAllGlobals()vi.restoreAllMocks()@@ -314,6 +323,23 @@ it('closes a persistent browser tab when its host shell exits', async () => {expect(emulator.output).not.toContain('Press Enter to create a new shell')})+// The shell exited while no view was attached (`exit`, then the tab was hidden or the page reloaded).+it('closes a persistent browser tab whose shell exited while it was detached', async () => {+ seedWebappSession('test-token')+ Socket.persistent = true+ vi.stubGlobal('WebSocket', Socket)+ installBrowserDesktopBridge()+ const id = createTerminal('/work')+ const firstView = render(<Harness id={id} />)+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ firstView.unmount()+ Socket.refusal = [4410, 'Process exited']+ render(<Harness id={id} />)+ await waitFor(() => expect($terminals.get().some(tab => tab.id === id)).toBe(false))+ expect(Socket.instances[1].url.searchParams.get('attach')).toBe('shell-1')+ 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 = truediff --git a/apps/desktop/src/lib/browser-terminal.test.ts b/apps/desktop/src/lib/browser-terminal.test.tsindex 68a7ed21fea..9e15ac72979 100644--- a/apps/desktop/src/lib/browser-terminal.test.ts+++ b/apps/desktop/src/lib/browser-terminal.test.ts@@ -201,6 +201,29 @@ describe('persistent browser terminals', () => {expect(localStorage.length).toBe(0)})+ // The shell exited while the tab was away: the redial is refused with the exit reason.+ it('reports a redial refused because the shell exited as an exit, 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(1006)+ Socket.reply = socket => socket.close(4410, 'Process exited')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(2)+ expect(exit).toHaveBeenCalledExactlyOnceWith({ code: null, signal: null })+ expect(localStorage.length).toBe(0)+ })++ it('rejects resuming a saved shell that exited with the exit signal, and forgets it', async () => {+ const api = install()+ await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ Socket.reply = socket => socket.close(4410, 'Process exited')+ await expect(api.start({ restoreKey: 'tab-one', resumeOnly: true })).rejects.toMatchObject({ signal: 'exited' })+ expect(Socket.instances[1].url.searchParams.get('attach')).toBe('opaque-server-id')+ 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' })diff --git a/apps/desktop/src/lib/browser-terminal.ts b/apps/desktop/src/lib/browser-terminal.tsindex 040dba87470..ebe8f583e37 100644--- a/apps/desktop/src/lib/browser-terminal.ts+++ b/apps/desktop/src/lib/browser-terminal.ts@@ -50,6 +50,8 @@ 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'+// The signal of a dial refused that way (the shell exited while no tab was attached): a process exit.+const EXITED = 'exited'const MAX_RETRIES = 5const RETRY_BACKOFF = { baseDelayMs: 500, capMs: 8000 }const START_TIMEOUT = 10_000@@ -258,11 +260,12 @@ async function dialTerminal(state: TerminalState, context: DialContext): Promiseif (!current()) {return}settleOpen(state)const signal = CLOSE_SIGNALS[event.code] ?? 'disconnected'+ const exited = event.code === 4410 && event.reason === PROCESS_EXITED_REASONif (signal === 'expired') {forget(state)}if (!handshakeComplete) {- fail(new TerminalConnectionError(event.reason || `Host terminal closed (${event.code})`, signal))+ fail(new TerminalConnectionError(event.reason || `Host terminal closed (${event.code})`, exited ? EXITED : signal))return}@@ -271,7 +274,7 @@ async function dialTerminal(state: TerminalState, context: DialContext): Promiseif (!state.terminalId) {finish(state, event.code === 4410 ? null : 'disconnected')- } else if (event.code === 4410 && event.reason === PROCESS_EXITED_REASON) {+ } else if (exited) {// The shell ended: report a process exit, which closes the tab as in native Desktop.finish(state, null)} else if (signal !== 'disconnected') {@@ -374,6 +377,8 @@ export function createBrowserTerminal(options: BrowserTerminalOptions): Terminal// A 401 from the ticket route: signed out, and every further attempt would be refused.if (isGatewayReauthRequired(error)) {finish(state, 'signed-out')+ } else if (error instanceof TerminalConnectionError && error.signal === EXITED) {+ finish(state, null)} else if (error instanceof TerminalConnectionError && error.signal !== 'disconnected') {finish(state, error.signal)} else {diff --git a/hermes_cli/web_host_terminal_sessions.py b/hermes_cli/web_host_terminal_sessions.pyindex ca303501cd6..81323306328 100644--- a/hermes_cli/web_host_terminal_sessions.py+++ b/hermes_cli/web_host_terminal_sessions.py@@ -16,6 +16,7 @@ import jsonfrom pathlib import Pathimport reimport secrets+import timefrom fastapi import HTTPException, WebSocket, WebSocketDisconnect@@ -44,6 +45,10 @@ class TerminalExpired(Exception):pass+class TerminalExited(TerminalExpired):+ """The shell exited by itself (``exit``, Ctrl-D); the server did not end it."""++def _home_live(home: Path) -> bool:"""A named home must exist and carry no deletion tombstone; any other home only has to exist."""try:@@ -95,6 +100,10 @@ def _request_home(profile: str | None) -> Path:class HostTerminalRegistry(PtySessionRegistry):+ # The most exited shells remembered at once: a tab that redials after the reaper took its+ # shell still learns that it exited (``resolve``).+ _EXITS_KEPT = 4 * _MAX_SHELLS+def __init__(self):# Every live shell keeps a read in flight. On the loop's default executor, retained# shells would queue the keystroke fences, ownership checks, uploads and SessionDB@@ -103,6 +112,9 @@ class HostTerminalRegistry(PtySessionRegistry):ttl=RETENTION_SECONDS, max_sessions=_MAX_SHELLS, buffer_cap=1024 * 1024, read_timeout=0.2,drain_executor=ThreadPoolExecutor(_MAX_SHELLS, thread_name_prefix="host-pty-drain"))self.owners: dict[str, HostOwner] = {}+ # Token -> (owner identity, when it was reaped) of shells that exited by themselves, for+ # the retention TTL.+ self.exits: dict[str, tuple[tuple[str, str], float]] = {}def _reap_one_idle_or_raise(self) -> None:# Retention is a promise, not an LRU hint; never evict a live shell to@@ -140,6 +152,9 @@ class HostTerminalRegistry(PtySessionRegistry):session = self._sessions.get(token)owner = self.owners.get(token)if session is None or owner is None:+ gone = self.exits.get(token)+ if gone is not None and gone[0] == identity:+ raise TerminalExited()raise TerminalExpired()if owner.identity != identity:raise TerminalDenied()@@ -152,8 +167,11 @@ class HostTerminalRegistry(PtySessionRegistry):await asyncio.to_thread(validate)# No await between the final check and the caller's attach claim. The# home was just checked off-loop; every input write checks it again.- if (self._sessions.get(token) is not session- or (not closing and (not session.alive or self.expired(session)))):+ if self._sessions.get(token) is not session:+ raise TerminalExpired()+ if not closing and _exited(session):+ raise TerminalExited()+ if not closing and self.expired(session):raise TerminalExpired()return session, owner@@ -169,22 +187,39 @@ class HostTerminalRegistry(PtySessionRegistry):# One thread hop per tick keeps every shell's marker reads off the loop.owners = list(self.owners.items())retired = await asyncio.to_thread(lambda: {token for token, owner in owners if not owner.current()})+ now = time.monotonic() if now is None else nowfor token, owner in owners:session = self._sessions.get(token)if session is not None and (token in retired or self._reapable(session, now)):+ if token not in retired and _exited(session):+ self._remember_exit(token, owner, now)await self.remove(token)for token in list(self.owners):if token not in self._sessions:self.owners.pop(token, None)+ for token in [token for token, (_, at) in self.exits.items() if now - at > self._ttl]:+ del self.exits[token]++ def _remember_exit(self, token: str, owner: HostOwner, now: float) -> None:+ self.exits[token] = (owner.identity, now)+ while len(self.exits) > self._EXITS_KEPT:+ del self.exits[next(iter(self.exits))]async def close_all(self):await super().close_all()self.owners.clear()+ self.exits.clear()# Every drain is cancelled by now; a read still in flight returns within its# timeout, so let it finish behind us. A closed registry never spawns again.self._drain_executor.shutdown(wait=False)+def _exited(session: PtySession) -> bool:+ """Whether a session still in the registry lost its shell: the server pops a session before+ it closes one, so only the shell's own exit leaves a dead one behind."""+ return not session.alive or not session.bridge.is_alive()++def get_host_terminals(app) -> HostTerminalRegistry:registry = getattr(app.state, "host_terminals", None)if registry is None or registry._closed:@@ -418,6 +453,7 @@ async def _pump_input(ws: WebSocket, registry: HostTerminalRegistry, token: str,async def host_terminal(ws: WebSocket) -> None:"""Called only after both the existing WS gate and host policy have passed."""+ from hermes_cli.pty_session import WS_CLOSE_PROCESS_EXITED, WS_CLOSE_PROCESS_EXITED_REASONfrom hermes_cli.web_server_chat import _pty_failsession = Nonetry:@@ -440,6 +476,9 @@ async def host_terminal(ws: WebSocket) -> None:await _pump_input(ws, registry, token, session, owner)except TerminalDenied:await ws.close(code=4403, reason="Terminal belongs to another identity or profile")+ except TerminalExited:+ # The same close an attached tab gets when its shell exits: the tab closes too.+ await ws.close(code=WS_CLOSE_PROCESS_EXITED, reason=WS_CLOSE_PROCESS_EXITED_REASON)except (TerminalExpired, FileNotFoundError, HTTPException):await ws.close(code=4410, reason="Terminal or profile expired; open a new terminal")except RegistryFull:diff --git a/tests/hermes_cli/test_web_host_terminal_persistence.py b/tests/hermes_cli/test_web_host_terminal_persistence.pyindex da0ee4c5d3d..e59e1c7d6f8 100644--- a/tests/hermes_cli/test_web_host_terminal_persistence.py+++ b/tests/hermes_cli/test_web_host_terminal_persistence.py@@ -11,7 +11,7 @@ from starlette.websockets import WebSocketDisconnectfrom hermes_cli import web_host_terminal, web_server, web_server_chatfrom hermes_cli.web_routers.webapp import routerfrom hermes_cli.web_session_sockets import HOST_TERMINAL_SOCKET-from tests.waiting import async_wait_until+from tests.waiting import async_wait_until, wait_until@pytest.fixture@@ -384,6 +384,37 @@ def test_real_profile_a_b_a_and_process_exit_never_respawns(host_app, tmp_path):assert set(host_app.state.host_terminals._sessions) <= set(tokens.values())[email protected]("linux")[email protected]("reaped", [False, True], ids=["before-reap", "after-reap"])+def test_a_shell_that_exits_while_detached_closes_the_redial_as_an_exit(host_app, tmp_path, monkeypatch, reaped):+ """A tab that redials after its shell exited (``exit`` while the tab was away) is told the+ shell exited, as an attached tab is, so it closes instead of offering a new shell. That holds+ before the reaper takes the dead shell and after."""+ from hermes_cli import web_host_terminal_sessions+ if not reaped:+ async def no_reaper(_registry, *, interval):+ await asyncio.Event().wait()+ monkeypatch.setattr(web_host_terminal_sessions, "run_reaper", no_reaper)+ go = tmp_path / "go"+ with TestClient(host_app) as client:+ registry = host_app.state.host_terminals+ with client.websocket_connect(url()) as ws:+ token = metadata(ws)["terminalId"]+ ws.send_bytes(f"printf 'WAIT%s\\n' ING; while [ ! -e '{go}' ]; do sleep 0.05; done; exit\n".encode())+ output_until(ws, b"WAITING")+ session = registry._sessions[token]+ wait_until(lambda: not session.attached, what="the tab detached")+ go.touch()+ if reaped:+ wait_until(lambda: token not in registry._sessions, what="the reaper took the shell")+ else:+ wait_until(lambda: not session.alive, what="the shell exited")+ with pytest.raises(WebSocketDisconnect) as error:+ with client.websocket_connect(url("&attach=" + token)) as ws:+ ws.receive_text()+ assert (error.value.code, error.value.reason) == (4410, "Process exited")++@pytest.mark.platforms("linux")def test_real_shell_rejects_input_after_profile_deletion(host_app, tmp_path):import os