The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the host terminal stops and shows the sign-in view after sign-out
emozilla57e02a36e01f
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 52ff947ae42..2b4514d74a5 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@@ -15,7 +15,8 @@ const TERMINAL_EXIT_MESSAGES: Record<string, string> = {expired: 'Terminal expired or exited. Press Enter to create a new shell.',superseded: 'Terminal is attached in another window. Press Enter to take it back.',denied: 'Terminal access denied. Check your sign-in and profile, then press Enter to retry.',- capacity: 'Terminal capacity reached. Close another terminal, then press Enter to retry.'+ capacity: 'Terminal capacity reached. Close another terminal, then press Enter to retry.',+ 'signed-out': 'Signed out of Hermes. Sign this browser in again, then press Enter to reconnect.'}// True once the page/app is tearing down (Cmd+Q, Alt+F4, window close, reload).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 2e4d51380ca..fa8614c4b88 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@@ -2,6 +2,8 @@ import { act, cleanup, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'+import { WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'+import { $desktopBoot } from '@/store/boot'import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'import { $terminals, closeAllTerminals, closeOtherTerminals, createTerminal, updateTerminalReviveBuffer } from './terminals'@@ -321,3 +323,25 @@ it('preserves saved tabs when page unload closes the browser socket', async () =expect(Socket.instances[0].readyState).toBe(3)expect($terminals.get().find(tab => tab.id === id)?.reviveBuffer).toBe(SAVED_HISTORY)})++// Sign-out closes the tab's sockets with 4401. The terminal keeps its tab and scrollback and says+// how to get back in, instead of reconnecting against a refused credential.+it('keeps a signed-out tab and says to sign in again instead of reconnecting', 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(4401, 'signed out'))++ await waitFor(() => expect(screen.getByText('closed')).toBeTruthy())+ expect(emulator.output).toMatch(/Signed out of Hermes\. Sign this browser in again/)+ expect(emulator.output).not.toMatch(/Reconnecting/)+ expect(Socket.instances).toHaveLength(1)+ expect($terminals.get().some(tab => tab.id === id)).toBe(true)+ expect($desktopBoot.get().error).toBe(WEBAPP_LAUNCH_REQUIRED)+ $desktopBoot.set({ ...$desktopBoot.get(), error: null, visible: false })+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.tsindex 001eb34a42b..dfb1286441c 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts@@ -5,7 +5,7 @@ import { BROWSER_BRIDGE_STUBS } from '@/lib/browser-bridge-stubs'import { createBrowserClipboardBridge } from '@/lib/browser-clipboard'import { createBrowserConnectionBridge } from '@/lib/browser-connection'import { createBrowserFilesBridge } from '@/lib/browser-files'-import { watchWebappLaunchLink } from '@/lib/browser-launch-session'+import { watchWebappLaunchLink, WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'import { createBrowserProfileBridge } from '@/lib/browser-profile'import { createBrowserSettings } from '@/lib/browser-settings'import { createBrowserTerminal } from '@/lib/browser-terminal'@@ -13,6 +13,7 @@ import { authenticatedWebsocketUrl, browserApi, browserBootstrap } from '@/lib/bimport { createBrowserUploadsBridge } from '@/lib/browser-uploads'import { createBrowserWindowOpener, sessionWindowTarget } from '@/lib/browser-window'import { createBrowserZoom } from '@/lib/browser-zoom'+import { failDesktopBoot } from '@/store/boot'import { $connection } from '@/store/session'import { windowProfileOverride } from '@/store/windows'@@ -130,7 +131,12 @@ export function installBrowserDesktopBridge(): boolean {basePath: bootstrap.basePath,currentProfile,websocketUrl: profile => authenticatedWebsocketUrl(bootstrap, '/api/host-terminal', profile),- defaultCwd: async profile => (await api<{ cwd?: string }>({ path: '/api/fs/default-cwd', profile })).cwd || ''+ defaultCwd: async profile => (await api<{ cwd?: string }>({ path: '/api/fs/default-cwd', profile })).cwd || '',+ // The chat's sign-in view for a launch-link tab. Behind the sign-in gate the next ticket+ // request already takes the tab to the login page.+ onSignedOut: () => {+ if (!bootstrap.authRequired) {failDesktopBoot(WEBAPP_LAUNCH_REQUIRED)}+ }}),...createBrowserProfileBridge({ basePath: bootstrap.basePath, currentProfile, openWindow }),zoom: createBrowserZoom(bootstrap.basePath)diff --git a/apps/desktop/src/lib/browser-terminal.test.ts b/apps/desktop/src/lib/browser-terminal.test.tsindex dfd243e4ebc..133541485bd 100644--- a/apps/desktop/src/lib/browser-terminal.test.ts+++ b/apps/desktop/src/lib/browser-terminal.test.ts@@ -1,6 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'+import { $desktopBoot } from '@/store/boot'import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'import { installBrowserDesktopBridge } from './browser-desktop-bridge'@@ -248,3 +251,85 @@ describe('persistent browser terminals', () => {expect(Socket.instances.at(-1)!.url.searchParams.has('attach')).toBe(false)})})++describe('host terminal after sign-out', () => {+ /** A Webapp tab on the loopback bind, signed in by its launch link. */+ function installWebapp() {+ Reflect.deleteProperty(window, 'hermesDesktop')+ Object.assign(window, { __HERMES_AUTH_REQUIRED__: false, __HERMES_BASE_PATH__: '/one' })+ seedWebappSession('launch-link-session')+ installBrowserDesktopBridge()++ return window.hermesDesktop!.terminal+ }++ const signedOutTicket = () =>+ vi.fn(async () => new Response(JSON.stringify({ detail: 'Unauthorized' }), { status: 401 }))++ afterEach(() => {+ clearWebappSession()+ $desktopBoot.set({ ...$desktopBoot.get(), error: null, visible: false })+ })++ // `hermes webapp --sign-out` closes the tab's sockets with 4401. That is final: redialing only+ // hits a ticket route that answers 401, so the terminal stops at once and the tab shows the+ // sign-in view the chat shows.+ it('stops on a 4401 close without redialing and shows the Webapp sign-in view', async () => {+ const api = installWebapp()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ const exit = vi.fn()+ api.onExit(session.id, exit)+ const ticketsBefore = vi.mocked(fetch).mock.calls.length++ Socket.instances[0].close(4401, 'signed out')+ await vi.advanceTimersByTimeAsync(60_000)++ expect(Socket.instances).toHaveLength(1)+ expect(fetch).toHaveBeenCalledTimes(ticketsBefore)+ expect(exit).toHaveBeenCalledExactlyOnceWith({ code: null, signal: 'signed-out' })+ expect($desktopBoot.get().error).toBe(WEBAPP_LAUNCH_REQUIRED)+ })++ it('stops reconnecting once the ticket route answers 401', async () => {+ const api = installWebapp()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ const exit = vi.fn()+ api.onExit(session.id, exit)+ const ticket = signedOutTicket()+ vi.stubGlobal('fetch', ticket)++ Socket.instances[0].close(1006)+ await vi.advanceTimersByTimeAsync(120_000)++ expect(ticket).toHaveBeenCalledTimes(1)+ expect(Socket.instances).toHaveLength(1)+ expect(exit).toHaveBeenCalledExactlyOnceWith({ code: null, signal: 'signed-out' })+ expect($desktopBoot.get().error).toBe(WEBAPP_LAUNCH_REQUIRED)+ })++ it('shows the sign-in view when a new terminal cannot get a ticket', async () => {+ const api = installWebapp()+ vi.stubGlobal('fetch', signedOutTicket())++ await expect(api.start({ cwd: '/original', restoreKey: 'tab-two' })).rejects.toThrow(WEBAPP_LAUNCH_REQUIRED)++ expect(Socket.instances).toHaveLength(0)+ expect($desktopBoot.get().error).toBe(WEBAPP_LAUNCH_REQUIRED)+ })++ // Behind the sign-in gate the chat's next ticket request takes the tab to the login page; the+ // Webapp's launch-link view would name the wrong way to sign in, so the terminal only stops.+ it('stops on a 4401 close behind the sign-in gate without the launch-link view', 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(4401, 'signed out')+ await vi.advanceTimersByTimeAsync(60_000)++ expect(Socket.instances).toHaveLength(1)+ expect(exit).toHaveBeenCalledExactlyOnceWith({ code: null, signal: 'signed-out' })+ expect($desktopBoot.get().error).not.toBe(WEBAPP_LAUNCH_REQUIRED)+ })+})diff --git a/apps/desktop/src/lib/browser-terminal.ts b/apps/desktop/src/lib/browser-terminal.tsindex 7042ba881d3..aeb1f72e1eb 100644--- a/apps/desktop/src/lib/browser-terminal.ts+++ b/apps/desktop/src/lib/browser-terminal.ts@@ -1,4 +1,4 @@-import { isStableOpen, reconnectBackoffDelayMs } from '@hermes/shared'+import { isGatewayReauthRequired, isStableOpen, reconnectBackoffDelayMs } from '@hermes/shared'import type { HermesTerminalExit, HermesTerminalSession, HermesTerminalState } from '@/global'@@ -17,6 +17,8 @@ interface BrowserTerminalOptions {currentProfile: () => string | nullwebsocketUrl: (profile: string | null) => Promise<string>defaultCwd: (profile: string | null) => Promise<string>+ /** The tab's sign-in ended (a 4401 close or a 401 ticket): show the sign-in view. */+ onSignedOut?: () => void}interface TerminalState {@@ -48,7 +50,11 @@ const META = '\u0000HERMES_TERMINAL_META:'const MAX_RETRIES = 5const RETRY_BACKOFF = { baseDelayMs: 500, capMs: 8000 }const START_TIMEOUT = 10_000-const CLOSE_SIGNALS: Record<number, string> = { 4403: 'denied', 4409: 'superseded', 4410: 'expired', 1013: 'capacity' }++// 4401 is what sign-out closes a tab's sockets with; no redial succeeds until the tab signs in again.+const CLOSE_SIGNALS: Record<number, string> = {+ 4401: 'signed-out', 4403: 'denied', 4409: 'superseded', 4410: 'expired', 1013: 'capacity'+}class TerminalConnectionError extends Error {constructor(message: string, readonly signal = 'disconnected') {@@ -330,6 +336,8 @@ export function createBrowserTerminal(options: BrowserTerminalOptions): TerminalsetStatus(state, 'disconnected')state.exit = { code: null, signal }state.exitListeners.forEach(listener => listener(state.exit!))++ if (signal === 'signed-out') {options.onSignedOut?.()}}const reconnect = (state: TerminalState) => {@@ -349,7 +357,10 @@ export function createBrowserTerminal(options: BrowserTerminalOptions): Terminalif (paused || state.stopped || generation !== state.generation) {return}stopSocket(state)- if (error instanceof TerminalConnectionError && error.signal !== 'disconnected') {+ // 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 !== 'disconnected') {finish(state, error.signal)} else {reconnect(state)@@ -527,6 +538,11 @@ export function createBrowserTerminal(options: BrowserTerminalOptions): Terminal} catch (error) {stopSocket(state)terminals.delete(state.id)++ if (isGatewayReauthRequired(error) || (error instanceof TerminalConnectionError && error.signal === 'signed-out')) {+ options.onSignedOut?.()+ }+throw error}},