Skip to content

The agent that grows with you

fix(desktop): route Ctrl+W to the shell over an interactive terminal

Brooklyn Nicholson6489ef982cd2
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index a94264fb259..61f01c71455 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -7184,7 +7184,19 @@ function buildApplicationMenu() {
label: 'Window',
submenu: IS_MAC
? [{ role: 'minimize' }, { role: 'zoom' }, { role: 'front' }]
- : [{ role: 'minimize' }, { role: 'close' }]
+ : // Click-only Close: the `close` role would register its default
+ // CommandOrControl+W accelerator, claiming the chord before the
+ // before-input-event run that routes a terminal-focused Ctrl+W to the
+ // shell's word erase (#65457). The menu item still closes the focused
+ // window when clicked.
+ [
+ { role: 'minimize' },
+ {
+ click: (_menuItem, window) => window?.close(),
+ label: 'Close',
+ registerAccelerator: false
+ }
+ ]
})
template.push({
label: 'Help',
diff --git a/apps/desktop/src/app/context-menu/app-context-menu.test.tsx b/apps/desktop/src/app/context-menu/app-context-menu.test.tsx
index 8f43004057e..f8c32b763e6 100644
--- a/apps/desktop/src/app/context-menu/app-context-menu.test.tsx
+++ b/apps/desktop/src/app/context-menu/app-context-menu.test.tsx
@@ -414,7 +414,8 @@ describe('AppContextMenu', () => {
getSelection: () => 'picked text',
paste,
reload: vi.fn(),
- selectAll: vi.fn()
+ selectAll: vi.fn(),
+ wordErase: null
})
fireEvent.contextMenu(host.querySelector('canvas')!)
@@ -434,7 +435,8 @@ describe('AppContextMenu', () => {
getSelection: () => '',
paste: null,
reload: vi.fn(),
- selectAll: vi.fn()
+ selectAll: vi.fn(),
+ wordErase: null
})
fireEvent.contextMenu(host.querySelector('canvas')!)
diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
index d8e60c54868..f187a2dbb79 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { setApiRequestConnection, setApiRequestProfile } from '@/hermes'
import { createClientSessionState } from '@/lib/chat-runtime'
+import { registerTerminalContextMenu } from '@/app/right-sidebar/terminal/terminal-context-menu'
import { adoptNewSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
import { $confirmRequest, runConfirm, settleConfirm } from '@/store/confirm'
import { $hubInstalledOverride } from '@/store/hub-actions'
@@ -27,6 +28,10 @@ const { hudWindowMock, peerWindowMock } = vi.hoisted(() => ({
peerWindowMock: vi.fn(() => false)
}))
+const closeActiveTab = vi.hoisted(() => vi.fn(() => true))
+
+vi.mock('@/app/chat/close-tab', () => ({ closeActiveTab }))
+
vi.mock('@/store/mcp-deeplink-install', () => ({
requestMcpInstallFromDeepLink: vi.fn()
}))
@@ -102,6 +107,7 @@ describe('useDesktopIntegrations', () => {
}
vi.restoreAllMocks()
+ document.body.replaceChildren()
})
function render({
@@ -507,6 +513,90 @@ describe('useDesktopIntegrations', () => {
})
})
+ describe('⌘W close-preview routing over a focused terminal (#65457)', () => {
+ let closeRequested: (() => void) | undefined
+
+ function mountWithCloseIpc() {
+ desktopWindow.hermesDesktop = {
+ ...desktopWindow.hermesDesktop,
+ onClosePreviewRequested: (cb: () => void) => {
+ closeRequested = cb
+
+ return () => undefined
+ }
+ } as unknown as Window['hermesDesktop']
+
+ render({ profileReady: true, sessions: [] })
+ }
+
+ /** Mirror the production DOM shape: the handle is registered on the
+ * xterm host nested inside the [data-terminal] scope, which carries
+ * [data-interactive-terminal] only on the user PTY. */
+ function focusedTerminal(interactive: boolean): void {
+ const scope = document.createElement('div')
+ scope.dataset.terminal = ''
+
+ if (interactive) {
+ scope.dataset.interactiveTerminal = ''
+ }
+
+ const host = document.createElement('div')
+ scope.append(host)
+ document.body.append(scope)
+ scope.tabIndex = -1
+ ;(scope as HTMLElement).focus()
+ scopeCleanup.push(registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: () => undefined,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase: () => true
+ }))
+ }
+
+ const scopeCleanup: Array<() => void> = []
+
+ afterEach(() => {
+ for (const cleanup of scopeCleanup.splice(0)) {
+ cleanup()
+ }
+
+ document.body.replaceChildren()
+ closeRequested = undefined
+ closeActiveTab.mockClear()
+ })
+
+ it('re-delivers the chord to a focused interactive terminal instead of closing', () => {
+ mountWithCloseIpc()
+ focusedTerminal(true)
+
+ closeRequested?.()
+
+ // The terminal's wordErase verb consumed the chord; the close path
+ // never ran.
+ expect(closeActiveTab).not.toHaveBeenCalled()
+ })
+
+ it('still closes tabs when focus is on a read-only agent terminal', () => {
+ mountWithCloseIpc()
+ focusedTerminal(false)
+
+ closeRequested?.()
+
+ // The mirror's wordErase is null, so the rung falls through to
+ // closeActiveTab — its tab stays closeable.
+ expect(closeActiveTab).toHaveBeenCalledOnce()
+ })
+
+ it('still closes tabs when focus is outside any terminal', () => {
+ mountWithCloseIpc()
+
+ closeRequested?.()
+
+ expect(closeActiveTab).toHaveBeenCalledOnce()
+ })
+ })
+
describe('stale-result suppression during profile switch', () => {
it('remembers route for the new profile after switch, not the old one', () => {
const sessions = [
diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
index acb7b7eb60f..86792cc67ff 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
@@ -5,7 +5,10 @@ import { resumeAccountConnect } from '@/app/capabilities/connectors/data/deep-li
import { closeActiveTab } from '@/app/chat/close-tab'
import { commandFocusedPreview } from '@/app/chat/right-rail/preview-nav'
import { openSession } from '@/app/open-session'
-import { commandFocusedTerminal } from '@/app/right-sidebar/terminal/terminal-context-menu'
+import {
+ commandFocusedTerminal,
+ wordEraseFocusedTerminal
+} from '@/app/right-sidebar/terminal/terminal-context-menu'
import { openConnectionDoneLink } from '@/components/assistant-ui/connector-tool'
import { $diskPluginsScanPending } from '@/contrib/runtime-loader'
import { getSession } from '@/hermes'
@@ -478,9 +481,17 @@ export function useDesktopIntegrations({
// OS-standard window close, esp. secondary windows). The Win/Linux keyboard
// path is the `view.closeTab` keybind (use-keybinds), sharing closeActiveTab.
useEffect(() => {
- const unsubscribe = window.hermesDesktop?.onClosePreviewRequested?.(
- () => void closeActiveTab(id => navigate(sessionRoute(id)))
- )
+ const unsubscribe = window.hermesDesktop?.onClosePreviewRequested?.(() => {
+ // A focused user terminal owns the chord as the shell's word erase: main
+ // claimed the keystroke (before-input-event), so re-deliver the ^W byte
+ // to the PTY instead of closing the pane and killing the shell (#65457).
+ // Read-only agent mirrors and everything else keep the close meaning.
+ if (wordEraseFocusedTerminal()) {
+ return
+ }
+
+ void closeActiveTab(id => navigate(sessionRoute(id)))
+ })
return () => unsubscribe?.()
}, [navigate])
diff --git a/apps/desktop/src/app/hooks/use-keybinds-close-tab.test.tsx b/apps/desktop/src/app/hooks/use-keybinds-close-tab.test.tsx
new file mode 100644
index 00000000000..fb3a3377c4c
--- /dev/null
+++ b/apps/desktop/src/app/hooks/use-keybinds-close-tab.test.tsx
@@ -0,0 +1,141 @@
+import { renderHook } from '@testing-library/react'
+import { MemoryRouter } from 'react-router'
+import type { ReactNode } from 'react'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { group, split } from '@/components/pane-shell/tree/model'
+import { $layoutTree } from '@/components/pane-shell/tree/store'
+import { registry } from '@/contrib/registry'
+import { isMacPlatform } from '@/lib/platform'
+import { resetBinding, setBinding } from '@/store/keybinds'
+
+import { useKeybinds } from './use-keybinds'
+
+const mocks = vi.hoisted(() => ({
+ closeActiveTerminal: vi.fn(),
+ setMode: vi.fn()
+}))
+
+vi.mock('@/app/right-sidebar/terminal/terminals', () => ({
+ closeActiveTerminal: mocks.closeActiveTerminal,
+ createTerminal: vi.fn(),
+ cycleTerminal: vi.fn()
+}))
+
+vi.mock('@/themes/context', () => ({
+ useTheme: () => ({ resolvedMode: 'light', setMode: mocks.setMode })
+}))
+
+const deps = {
+ archiveSelectedSession: vi.fn(),
+ openNewSessionTab: vi.fn(),
+ requestGateway: vi.fn(),
+ startFreshSession: vi.fn(),
+ toggleCommandCenter: vi.fn(),
+ toggleSelectedPin: vi.fn()
+}
+
+/** Focus an input inside a terminal matching the production DOM shape
+ * (instance.tsx): the [data-terminal] scope carries
+ * [data-interactive-terminal] only on the user PTY. */
+function focusedTerminal(interactive: boolean): HTMLTextAreaElement {
+ const terminal = window.document.createElement('div')
+ terminal.dataset.terminal = ''
+
+ if (interactive) {
+ terminal.dataset.interactiveTerminal = ''
+ }
+
+ const input = window.document.createElement('textarea')
+ terminal.append(input)
+ window.document.body.append(terminal)
+ input.focus()
+
+ return input
+}
+
+function pressCloseChord(target: HTMLElement, init: KeyboardEventInit = {}): KeyboardEvent {
+ const event = new KeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ code: 'KeyW',
+ ctrlKey: !isMacPlatform(),
+ key: 'w',
+ metaKey: isMacPlatform(),
+ ...init
+ })
+
+ target.dispatchEvent(event)
+
+ return event
+}
+
+describe('close-tab chord over a focused terminal', () => {
+ let unmount: (() => void) | undefined
+
+ beforeAll(() => {
+ // The closeTerminal handler asks the live tree whether the terminal pane
+ // is on screen; give it one with the terminal active.
+ registry.register({ id: 'terminal', area: 'panes', title: 'terminal', render: () => null })
+ })
+
+ beforeEach(() => {
+ $layoutTree.set(split('row', [group(['workspace']), group(['terminal'])]))
+ setBinding('view.closeTab', ['mod+w'])
+ unmount = renderHook(() => useKeybinds(deps), {
+ wrapper: ({ children }: { children: ReactNode }) => <MemoryRouter>{children}</MemoryRouter>
+ }).unmount
+ })
+
+ afterEach(() => {
+ unmount?.()
+ unmount = undefined
+ $layoutTree.set(null)
+ resetBinding('view.closeTab')
+ mocks.closeActiveTerminal.mockReset()
+ window.document.body.replaceChildren()
+ })
+
+ it('leaves the default chord to an interactive terminal (word erase)', () => {
+ const event = pressCloseChord(focusedTerminal(true))
+
+ // Not claimed: xterm sees the keystroke and writes ^W to the PTY.
+ expect(event.defaultPrevented).toBe(false)
+ expect(mocks.closeActiveTerminal).not.toHaveBeenCalled()
+ })
+
+ it('keeps close-tab for a read-only agent terminal', () => {
+ const event = pressCloseChord(focusedTerminal(false))
+
+ expect(event.defaultPrevented).toBe(true)
+ expect(mocks.closeActiveTerminal).toHaveBeenCalledOnce()
+ })
+
+ it('keeps Ctrl/Cmd+Shift+W as the explicit close chord', () => {
+ const event = pressCloseChord(focusedTerminal(true), { key: 'W', shiftKey: true })
+
+ expect(event.defaultPrevented).toBe(true)
+ expect(mocks.closeActiveTerminal).toHaveBeenCalledOnce()
+ })
+
+ it('keeps a rebound close-tab chord closing in an interactive terminal', () => {
+ // The chord was rebound to alt+W: only the platform's bare close chord
+ // (mod+w) is the terminal's word erase.
+ setBinding('view.closeTab', ['mod+alt+w'])
+ const event = pressCloseChord(focusedTerminal(true), { altKey: true })
+
+ expect(event.defaultPrevented).toBe(true)
+ expect(mocks.closeActiveTerminal).toHaveBeenCalledOnce()
+ })
+
+ it('keeps closing non-terminal surfaces', () => {
+ const input = window.document.createElement('textarea')
+ window.document.body.append(input)
+ input.focus()
+
+ const event = pressCloseChord(input)
+
+ expect(event.defaultPrevented).toBe(true)
+ expect(mocks.closeActiveTerminal).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.ts
index 622eea911f7..11e7119845a 100644
--- a/apps/desktop/src/app/hooks/use-keybinds.ts
+++ b/apps/desktop/src/app/hooks/use-keybinds.ts
@@ -25,7 +25,7 @@ import {
TAB_SLOT_COUNT
} from '@/lib/keybinds/actions'
import { handleApprovalKey, releaseApprovalKey } from '@/lib/keybinds/approval-keys'
-import { actionAllowedInInput, comboFromEvent, isEditableTarget } from '@/lib/keybinds/combo'
+import { actionAllowedInInput, comboFromEvent, isEditableTarget, isFocusWithin, IS_MAC } from '@/lib/keybinds/combo'
import { composerFocusKeysAllowed, isComposerFocusSoftCombo, typeToFocusChar } from '@/lib/keybinds/composer-focus-keys'
import { stepReasoningEffort, writeSessionReasoningEffort } from '@/lib/reasoning-step'
import { openWorktreeDialog } from '@/store/coding-status'
@@ -555,6 +555,25 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
return
}
+ // The close-tab chord over a focused user terminal is the shell's word
+ // erase (readline ^W). Main already claimed the default chord on
+ // every platform (window-accelerator) and routes it through the IPC
+ // rung above, so this guards the DEFAULT binding when it reaches the
+ // dispatcher anyway, plus a chord rebound onto another key with the
+ // same bare shape. Returning without preventDefault hands the key to
+ // xterm, whose data handler writes the ^W byte to the PTY. Read-only
+ // agent mirrors carry only [data-terminal], so they keep close.
+ if (
+ actionId === 'view.closeTab' &&
+ event.key.toLowerCase() === 'w' &&
+ (IS_MAC ? event.metaKey : event.ctrlKey) &&
+ !event.altKey &&
+ !event.shiftKey &&
+ isFocusWithin('[data-interactive-terminal]')
+ ) {
+ return
+ }
+
// Built-in handlers first (they carry React context); contributed
// actions bring their own `run` through the registry.
const handler = handlersRef.current[actionId] ?? contributedKeybindHandler(actionId)
diff --git a/apps/desktop/src/app/right-sidebar/terminal/instance.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/instance.test.tsx
index 9d7ccb4e255..889260f9b64 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/instance.test.tsx
+++ b/apps/desktop/src/app/right-sidebar/terminal/instance.test.tsx
@@ -12,7 +12,13 @@ vi.mock('./use-agent-terminal', () => ({
}))
vi.mock('./use-terminal-session', () => ({
- useTerminalSession: () => ({ hostRef: { current: null }, selection: '', status: 'ready' })
+ useTerminalSession: () => ({
+ addSelectionToChat: vi.fn(),
+ hostRef: { current: null },
+ selection: '',
+ selectionStyle: null,
+ status: 'ready'
+ })
}))
describe('background terminal input guidance (#108233)', () => {
@@ -57,3 +63,25 @@ describe('background terminal input guidance (#108233)', () => {
expect($terminals.get()).toHaveLength(1)
})
})
+
+describe('terminal close-chord markers', () => {
+ it('marks a user PTY as interactive so the close chord reaches the shell', () => {
+ const { container } = render(
+ <TerminalInstance active cwd="/tmp" id="terminal-1" onAddSelectionToChat={vi.fn()} />
+ )
+
+ const terminal = container.firstElementChild
+
+ expect(terminal?.hasAttribute('data-terminal')).toBe(true)
+ expect(terminal?.hasAttribute('data-interactive-terminal')).toBe(true)
+ })
+
+ it('keeps the read-only agent mirror closeable', () => {
+ const { container } = render(<AgentTerminalInstance active id="terminal-1" procId="process-1" />)
+
+ const terminal = container.firstElementChild
+
+ expect(terminal?.hasAttribute('data-terminal')).toBe(true)
+ expect(terminal?.hasAttribute('data-interactive-terminal')).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/app/right-sidebar/terminal/instance.tsx b/apps/desktop/src/app/right-sidebar/terminal/instance.tsx
index bd837558a40..1612790ea39 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/instance.tsx
+++ b/apps/desktop/src/app/right-sidebar/terminal/instance.tsx
@@ -54,7 +54,11 @@ export function TerminalInstance({
return (
<div
className={cn(INSTANCE_CLASS, active ? 'visible' : 'invisible pointer-events-none')}
- // Focus-scope marker so isFocusWithin('[data-terminal]') can route ⌘W here.
+ // Focus-scope markers. The shared [data-terminal] routes close-tab
+ // commands here; [data-interactive-terminal] marks the surface as a live
+ // PTY, so the close-tab rung re-delivers the chord's control byte to
+ // the shell instead of closing the pane and killing it (#65457).
+ data-interactive-terminal=""
data-terminal=""
>
{status === 'starting' && (
@@ -108,7 +112,9 @@ export function AgentTerminalInstance({ active, id, procId }: AgentTerminalInsta
<div
className={cn(INSTANCE_CLASS, active ? 'visible' : 'invisible pointer-events-none')}
// Same focus-scope marker as the user terminal so isFocusWithin('[data-terminal]')
- // routes ⌘W here and closes the focused agent tab (not a preview).
+ // routes ⌘W here and closes the focused agent tab (not a preview). No
+ // [data-interactive-terminal]: this mirror has no PTY input, so the
+ // close-tab chord keeps its close meaning here.
data-terminal=""
>
<div className="flex shrink-0 flex-wrap items-center gap-2 py-2 text-xs text-(--ui-text-secondary)">
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.test.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.test.ts
index 5cca64d3851..0b6189df4d9 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.test.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.test.ts
@@ -1,12 +1,18 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { commandFocusedTerminal, registerTerminalContextMenu, terminalMenuHandleFor } from './terminal-context-menu'
+import {
+ commandFocusedTerminal,
+ registerTerminalContextMenu,
+ terminalMenuHandleFor,
+ wordEraseFocusedTerminal
+} from './terminal-context-menu'
const handle = (overrides: Partial<Parameters<typeof registerTerminalContextMenu>[1]> = {}) => ({
getSelection: () => '',
paste: null,
reload: vi.fn(),
selectAll: vi.fn(),
+ wordErase: null,
...overrides
})
@@ -106,3 +112,140 @@ describe('commandFocusedTerminal', () => {
scope.remove()
})
})
+
+/** Mirror the production DOM shape (instance.tsx): the handle is registered
+ * on the inner xterm host while the markers live on the enclosing scope. */
+function mountScope(markers: 'interactive' | 'readonly'): { host: HTMLElement; scope: HTMLElement } {
+ const scope = document.createElement('div')
+ scope.dataset.terminal = ''
+
+ if (markers === 'interactive') {
+ scope.dataset.interactiveTerminal = ''
+ }
+
+ const host = document.createElement('div')
+ scope.append(host)
+ document.body.append(scope)
+
+ return { host, scope }
+}
+
+describe('wordEraseFocusedTerminal', () => {
+ const cleanups: Array<() => void> = []
+
+ afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) {
+ cleanup()
+ }
+
+ document.body.replaceChildren()
+ })
+
+ it('routes the close chord to the focused interactive terminal and reports it consumed', () => {
+ const { host, scope } = mountScope('interactive')
+ const wordErase = vi.fn(() => true)
+ cleanups.push(registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: () => undefined,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase
+ }))
+
+ scope.tabIndex = -1
+ scope.focus()
+
+ expect(wordEraseFocusedTerminal()).toBe(true)
+ expect(wordErase).toHaveBeenCalledOnce()
+ })
+
+ it('keys the registry by the [data-terminal] scope, not the nested host', () => {
+ const { host } = mountScope('interactive')
+ const wordErase = vi.fn(() => true)
+ cleanups.push(registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: () => undefined,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase
+ }))
+
+ // The resolver walks up from a focus point INSIDE the host, exactly like
+ // the real xterm textareaFocus.
+ const focusPoint = document.createElement('textarea')
+ host.append(focusPoint)
+ focusPoint.focus()
+
+ expect(wordEraseFocusedTerminal()).toBe(true)
+ expect(terminalMenuHandleFor(focusPoint)).not.toBeNull()
+ })
+
+ it('keeps the read-only agent mirror closeable (null wordErase)', () => {
+ const { host, scope } = mountScope('readonly')
+ cleanups.push(registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: null,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase: null
+ }))
+
+ scope.tabIndex = -1
+ scope.focus()
+
+ expect(wordEraseFocusedTerminal()).toBe(false)
+ })
+
+ it('reports not consumed when the terminal has no live session', () => {
+ const { host, scope } = mountScope('interactive')
+ cleanups.push(registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: () => undefined,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase: () => false
+ }))
+
+ scope.tabIndex = -1
+ scope.focus()
+
+ // A sessionless terminal falls back to closing the tab.
+ expect(wordEraseFocusedTerminal()).toBe(false)
+ })
+
+ it('reports not consumed when focus is elsewhere', () => {
+ const { host } = mountScope('interactive')
+ cleanups.push(registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: () => undefined,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase: () => true
+ }))
+
+ const elsewhere = document.createElement('textarea')
+ document.body.append(elsewhere)
+ elsewhere.focus()
+
+ expect(wordEraseFocusedTerminal()).toBe(false)
+ })
+
+ it('stops routing after the handle unregisters (idempotent remove)', () => {
+ const { host, scope } = mountScope('interactive')
+ const wordErase = vi.fn(() => true)
+ const unregister = registerTerminalContextMenu(host, {
+ getSelection: () => '',
+ paste: () => undefined,
+ reload: () => {},
+ selectAll: () => undefined,
+ wordErase
+ })
+
+ scope.tabIndex = -1
+ scope.focus()
+ unregister()
+
+ expect(wordEraseFocusedTerminal()).toBe(false)
+ expect(wordErase).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.ts
index a3d22c93e41..6b89f3b4402 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.ts
@@ -21,6 +21,12 @@ export interface TerminalMenuHandle {
* terminal, and the app-level reload fallback must not fire there. */
reload: () => void
selectAll: () => void
+ /** Re-deliver the close-tab chord main claimed (#65457). User terminals
+ * write the ^W byte into their PTY (readline unix-word-rubout) instead of
+ * closing the pane and killing the shell; false when there is no live
+ * session, so the caller falls back to closing. Null on the read-only
+ * agent mirror — no PTY, and its tab stays deliberately closeable. */
+ wordErase: (() => boolean) | null
}
const handles = new WeakMap<Element, TerminalMenuHandle>()
@@ -41,6 +47,19 @@ export function registerTerminalContextMenu(host: Element, handle: TerminalMenuH
}
}
+/** Run the close-tab chord on the interactive terminal holding DOM focus —
+ * the terminal rung of the close-tab routing (use-desktop-integrations).
+ * Only a user terminal carries [data-interactive-terminal]; the read-only
+ * agent mirror stays closeable. False = nothing consumed the chord (focus is
+ * elsewhere, on a mirror, or the terminal has no live session), so the
+ * caller falls back to closing the tab. */
+export function wordEraseFocusedTerminal(): boolean {
+ const host = document.activeElement?.closest('[data-interactive-terminal]')
+ const handle = host ? handles.get(host) : undefined
+
+ return handle?.wordErase?.() ?? false
+}
+
/** The handle owning `element`, when the click landed inside a terminal. */
export function terminalMenuHandleFor(element: Element | null): TerminalMenuHandle | null {
const host = element?.closest('[data-terminal]')
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
index 88c1f667540..11fde1b2fcb 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
@@ -101,7 +101,10 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
getSelection: () => term.getSelection(),
paste: null,
reload: () => {},
- selectAll: () => term.selectAll()
+ selectAll: () => term.selectAll(),
+ // No PTY input, and the mirror's tab stays deliberately closeable, so
+ // the close-tab chord keeps its close meaning here.
+ wordErase: null
})
term.attachCustomKeyEventHandler(event => {
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 9ea13700673..70bb6b32b13 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
@@ -845,7 +845,22 @@ export function useTerminalSession({
void terminalApi.write(sessionId, '\x12')
}
},
- selectAll: () => term.selectAll()
+ selectAll: () => term.selectAll(),
+ // The close-tab chord main claimed over this terminal is the shell's
+ // word erase: re-deliver the ^W byte instead of closing the pane
+ // (#65457). False when the session is gone, so the caller closes.
+ wordErase: () => {
+ hasSessionActivityRef.current = true
+ const sessionId = sessionIdRef.current
+
+ if (!sessionId) {
+ return false
+ }
+
+ void terminalApi.write(sessionId, '\x17')
+
+ return true
+ }
})
)
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 6445b10e9ea..9db262b70cc 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -125,7 +125,7 @@ The **Artifacts** view collects what your sessions generate — **images, files,
The app is built for working on several things at once:
-- **Tabs** — **Cmd/Ctrl+T** opens a new session tab; **Ctrl+Tab** / **Ctrl+Shift+Tab** cycle sessions, and **Ctrl+1…9** jump to a recent session by position. **Cmd/Ctrl+W** closes the focused tab and **Cmd/Ctrl+Shift+T** reopens the last closed one.
+- **Tabs** — **Cmd/Ctrl+T** opens a new session tab; **Ctrl+Tab** / **Ctrl+Shift+Tab** cycle sessions, and **Ctrl+1…9** jump to a recent session by position. **Cmd/Ctrl+W** closes the focused tab — except over an interactive terminal, where it keeps its shell meaning (word erase) — and **Cmd/Ctrl+Shift+T** reopens the last closed one.
- **Multiple windows** — **Cmd/Ctrl+Shift+N** opens a new window, and any session can be popped out via its context menu (**New window**) or from the command palette. A popped-out window renders that single chat without the global sidebar — handy for parking a long-running session on another monitor. Live agent output streams into every window showing the session.
- **Panes** — **Cmd/Ctrl+B** toggles the left sidebar, **Cmd/Ctrl+J** the right one, and **Cmd/Ctrl+\\** swaps which side the sidebars sit on.