The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a terminal tab records its gateway before its first start
Tekniumf9cf1f0f5d68
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-gateway.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-gateway.tsindex 9834d33a753..ed834882054 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-gateway.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-gateway.ts@@ -5,7 +5,7 @@ import type { DesktopConnectionsRegistry, DesktopRegistryConnection } from '@/glimport { $activeConnectionId, $connectionsRegistry } from '@/store/connections'import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'-import { bindTerminalSessionHost, type TerminalEntry } from './terminals'+import { bindTerminalDefaultGateway, type TerminalEntry } from './terminals'/** The gateway a terminal tab was opened on. Only This device and SSH gateways* carry a shell; the SSH tunnel is keyed by (connection, profile). */@@ -35,16 +35,21 @@ export function shellGatewayFor(}/** A new terminal opens on the gateway picked in Sessions. */-export const defaultTerminalGateway = () =>- shellGatewayFor($activeConnectionId.get(), $activeGatewayProfile.get(), $connectionsRegistry.get())+const $defaultTerminalGateway = computed(+ [$activeConnectionId, $activeGatewayProfile, $connectionsRegistry],+ shellGatewayFor+)++export const defaultTerminalGateway = () => $defaultTerminalGateway.get()/** The tab's shell rides an SSH gateway's tunnel (only SSH gateways keep a* connection id other than This device on a tab). */export const runsOverSsh = (gateway: TerminalGateway | undefined): boolean =>Boolean(gateway && gateway.connectionId !== LOCAL_CONNECTION_ID)-// Entering a session re-selects a tab in its cwd only on the session's host.-bindTerminalSessionHost(() => defaultTerminalGateway()?.connectionId)+// New tabs record this gateway, and entering a session re-selects a tab in its+// cwd only on the session's host.+bindTerminalDefaultGateway($defaultTerminalGateway)export const terminalGatewayOf = (term: TerminalEntry | undefined): TerminalGateway | undefined =>term?.connectionId ? { connectionId: term.connectionId, ...(term.profile ? { profile: term.profile } : {}) } : undefineddiff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-ownership.test.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-ownership.test.tsnew file mode 100644index 00000000000..1ce01a33999--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-ownership.test.ts@@ -0,0 +1,106 @@+import { waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++// Real terminal, connection and session stores; only the native terminal IPC+// is stubbed. Every test loads fresh modules so a "relaunch" re-reads storage.+async function loadStores() {+ vi.resetModules()+ const terminals = await import('./terminals')+ const gateway = await import('./terminal-gateway')+ const attempt = await import('./terminal-session-attempt')+ const { $connectionsRegistry } = await import('@/store/connections')+ const { $connection, $currentCwd } = await import('@/store/session')++ return { ...terminals, ...gateway, ...attempt, $connection, $connectionsRegistry, $currentCwd }+}++type Stores = Awaited<ReturnType<typeof loadStores>>++const registryWith = (...ssh: Array<{ host: string; id: string }>) =>+ ({+ version: 2,+ primary: 'local',+ connections: [+ { id: 'local', kind: 'local', label: 'This device' },+ ...ssh.map(entry => ({ ...entry, kind: 'ssh', label: entry.id.toUpperCase() }))+ ]+ }) as never++function controllerFor(stores: Stores, id: string, start: ReturnType<typeof vi.fn>) {+ const write = vi.fn()++ const controller = stores.createSessionAttemptController(id, {+ isDisposed: () => false,+ isReplayingHistory: () => false,+ onStarted: () => {},+ resolveCwd: () => '/repo',+ restoreHistory: () => {},+ sessionIdRef: { current: null },+ setStatus: () => {},+ term: { clearSelection: () => {}, cols: 80, rows: 24, write } as never,+ terminalApi: {+ attach: vi.fn(async () => true),+ dispose: vi.fn(async () => true),+ onData: () => () => {},+ onExit: () => () => {},+ start,+ write: vi.fn()+ } as never,+ writeOutput: () => {}+ })++ return { controller, write }+}++const session = (connectionId: string) => ({ connectionId, cwd: '/repo', id: `pty-${connectionId}`, shell: 'bash' })++beforeEach(() => {+ window.localStorage.clear()+ delete window.document.documentElement.dataset.hermesDesktopHost+})++describe('a terminal tab owns the gateway it was opened on', () => {+ it('a failed first start retries on the same gateway after a Sessions pick', async () => {+ const stores = await loadStores()+ stores.$connectionsRegistry.set(registryWith({ host: 'nas.example', id: 'nas' }))+ stores.$connection.set({ connectionId: 'nas' } as never)++ // The plain + button: no explicit gateway.+ const id = stores.createTerminal('/repo')+ expect(stores.$terminals.get().find(term => term.id === id)).toMatchObject({ connectionId: 'nas' })+ const start = vi.fn().mockRejectedValueOnce(new Error('NAS offline')).mockResolvedValue(session('nas'))+ const { controller, write } = controllerFor(stores, id, start)++ controller.start()+ await waitFor(() => expect(write).toHaveBeenCalled())+ expect(start.mock.calls[0]![0].connectionId).toBe('nas')++ stores.$connection.set({ connectionId: 'local' } as never)+ controller.input('\r')+ await waitFor(() => expect(start).toHaveBeenCalledTimes(2))+ controller.release()++ expect(start.mock.calls[1]![0].connectionId).toBe('nas')+ expect(stores.$terminals.get().find(term => term.id === id)?.connectionId).toBe('nas')+ })++ it('a restored tab with no gateway pins the one it first tried, even when that start fails', async () => {+ const stores = await loadStores()+ const id = stores.createTerminal('/repo') // no registry yet: nothing to record++ stores.$connectionsRegistry.set(registryWith({ host: 'nas.example', id: 'nas' }))+ stores.$connection.set({ connectionId: 'nas' } as never)+ const start = vi.fn().mockRejectedValueOnce(new Error('NAS offline')).mockResolvedValue(session('nas'))+ const { controller, write } = controllerFor(stores, id, start)++ controller.start()+ await waitFor(() => expect(write).toHaveBeenCalled())+ stores.$connection.set({ connectionId: 'local' } as never)+ controller.input('\r')+ await waitFor(() => expect(start).toHaveBeenCalledTimes(2))+ controller.release()++ expect(start.mock.calls[1]![0].connectionId).toBe('nas')+ })++})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 1ad387afb9a..14bd4afeb2e 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@@ -135,28 +135,37 @@ export function createSessionAttemptController(term.write(`${message}\r\n`)}+ const showUnavailable = (reason: keyof typeof TERMINAL_UNAVAILABLE_KEYS) => {+ restoreHistory()+ setStatus('closed')+ term.write(`\r\n${translateNow(TERMINAL_UNAVAILABLE_KEYS[reason])}\r\n`)+ }+// The tab's own gateway; a tab from an older Desktop takes the one picked- // in Sessions (never the window-backend route, which a pick doesn't move).+ // in Sessions (never the window-backend route, which a pick doesn't move)+ // and records it BEFORE the start, so a failed start retries on it too.const tab = $terminals.get().find(entry => entry.id === id)+const gateway = terminalGatewayOf(tab) ?? defaultTerminalGateway()+ if (gateway) {+ adoptTerminalGateway(id, gateway)+ }+void terminalApi// Prefer the last observed cwd so retry/relaunch stays in the same directory..start({ cols: term.cols, cwd: resolveCwd(), restoreKey: id, resumeOnly, rows: term.rows, ...gateway }).then(async session => {- const ranOn = gateway ?? (session.connectionId ? { connectionId: session.connectionId } : undefined)-- if (ranOn) {- adoptTerminalGateway(id, ranOn)+ // No registry to pick from (Webapp, early boot): main routed it.+ if (!gateway && session.connectionId) {+ adoptTerminalGateway(id, { connectionId: session.connectionId })}if (session.unavailable) {// The gateway is gone or has no shell: an exited tab, never a// local shell under the remote's name.if (!isDisposed() && current) {- restoreHistory()- setStatus('closed')- term.write(`\r\n${translateNow(TERMINAL_UNAVAILABLE_KEYS[session.unavailable])}\r\n`)+ showUnavailable(session.unavailable)}returndiff --git a/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts b/apps/desktop/src/app/right-sidebar/terminal/terminals.test.tsindex 1af35728b52..1d10ff86657 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts@@ -247,9 +247,9 @@ describe('session cwd → terminal tab linking', () => {})it("selects the session's own host's tab when two hosts share the path", async () => {- const { $activeTerminalId, $currentCwd, bindTerminalSessionHost, createTerminal } = await loadTerminalStore()- let host = 'nas'- bindTerminalSessionHost(() => host)+ const { $activeTerminalId, $currentCwd, bindTerminalDefaultGateway, createTerminal } = await loadTerminalStore()+ const $host = atom<{ connectionId: string } | undefined>({ connectionId: 'nas' })+ bindTerminalDefaultGateway($host)const nasTab = createTerminal('/repo', { connectionId: 'nas', profile: 'default' })const localTab = createTerminal('/repo', { connectionId: 'local' })@@ -260,11 +260,11 @@ describe('session cwd → terminal tab linking', () => {expect($activeTerminalId.get()).toBe(nasTab)// An active tab on the wrong host with the same path does not keep focus.- host = 'local'+ $host.set({ connectionId: 'local' })$currentCwd.set('/repo/')expect($activeTerminalId.get()).toBe(localTab)- host = 'nas'+ $host.set({ connectionId: 'nas' })$currentCwd.set('/repo')expect($activeTerminalId.get()).toBe(nasTab)})diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts b/apps/desktop/src/app/right-sidebar/terminal/terminals.tsindex f64ad41f94a..8f426bb69a9 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminals.ts@@ -1,7 +1,7 @@import { randomUuid } from '@hermes/shared'import type { WebglAddon } from '@xterm/addon-webgl'import type { Terminal } from '@xterm/xterm'-import { atom, computed } from 'nanostores'+import { atom, computed, type ReadableAtom } from 'nanostores'import { readKey, writeKey } from '@/lib/storage'import { notifyError } from '@/store/notifications'@@ -280,12 +280,21 @@ export const $activeTerminal = computed(const newId = () => randomUuid()+// The gateway picked in Sessions, as a shell host. terminal-gateway.ts binds the+// registry-backed store on load; this module stays free of the connection+// stores. Unbound (or with no registry, like the Webapp) there is one host.+let $defaultGateway: ReadableAtom<TerminalGateway | undefined> = atom(undefined)++let unbindDefaultGateway = () => {}+/** Append a fresh terminal and focus it. Captures the current cwd once (its only- * tie to session/project state). Without an explicit gateway the tab takes the- * one picked in Sessions when its shell first starts. Returns the id. */+ * tie to session/project state) and the gateway: an explicit one, else the one+ * picked in Sessions now, so a failed first start can never retry elsewhere.+ * Returns the id. */export function createTerminal(cwd: string = $currentCwd.get(), gateway?: TerminalGateway): string {const id = newId()- $terminals.set([...$terminals.get(), { id, title: 'Terminal', auto: true, cwd, kind: 'user', ...gateway }])+ const owner = gateway ?? $defaultGateway.get()+ $terminals.set([...$terminals.get(), { id, title: 'Terminal', auto: true, cwd, kind: 'user', ...owner }])$activeTerminalId.set(id)return id@@ -387,25 +396,20 @@ const terminalCwd = (term: TerminalEntry) => normalizePath(term.restoreCwd || te// A path names a directory on one host: `/repo` on the NAS is not `/repo` here,// so only tabs on the session's gateway (or a fresh tab that has not recorded// one yet) can match.-type SessionShellHost = () => string | undefined--// The registry-backed resolver lives in terminal-gateway.ts, which binds it on-// load; this module stays free of the connection stores. Until then (or with no-// registry, like the Webapp) there is one host and the path alone decides.-let sessionShellHost: SessionShellHost = () => undefined--export function bindTerminalSessionHost(resolve: SessionShellHost): void {- sessionShellHost = resolve+export function bindTerminalDefaultGateway(source: ReadableAtom<TerminalGateway | undefined>): void {+ unbindDefaultGateway()+ $defaultGateway = source+ unbindDefaultGateway = () => {}}-$currentCwd.listen(cwd => {+function followSessionCwd(cwd: string) {const target = normalizePath(cwd)if (!target) {return}- const host = sessionShellHost()+ const host = $defaultGateway.get()?.connectionIdconst linked = (term: TerminalEntry | undefined) =>term?.kind === 'user' &&@@ -423,7 +427,9 @@ $currentCwd.listen(cwd => {if (match) {$activeTerminalId.set(match.id)}-})+}++$currentCwd.listen(followSessionCwd)/** Move the active tab by `direction` (+1 next / -1 prev), wrapping around. */export function cycleTerminal(direction: 1 | -1): void {