fix(terminal): keep the user's focus when an agent splits a terminal (#42204)

This commit is contained in:
Kelvin Amoaba
2026-11-14 00:44:02 +00:00
committed by GitHub
parent 235d446873
commit 746b031870
17 changed files with 234 additions and 36 deletions
@@ -131,6 +131,8 @@ export type RuntimeNotifier = {
sourceLeafId?: string
telemetrySource?: TerminalPaneSplitSource
newLeafId?: string
/** An agent's split: the new pane leaves the user's active pane and keyboard focus alone. */
activate?: false
}
): void
/** `recordInteraction: false` marks a title the host applied, not one the user typed. */
@@ -101,7 +101,8 @@ export abstract class OrcaRuntimeWithSplitTerminal extends OrcaRuntimeWithStopEx
worktreeId: leaf.worktreeId,
sourceLeafId: leaf.leafId,
telemetrySource: opts.telemetrySource,
newLeafId
newLeafId,
...(opts.activate === false ? { activate: false } : {})
})
return await this.awaitRendererSplit(split, newLeafId)
}
+2 -1
View File
@@ -176,7 +176,8 @@ export function registerRuntimeWindowLifecycle(
worktreeId: opts.worktreeId,
sourceLeafId: opts.sourceLeafId,
telemetrySource: opts.telemetrySource,
newLeafId: opts.newLeafId
newLeafId: opts.newLeafId,
...(opts.activate === false ? { activate: false } : {})
})
},
renameTerminal: (tabId, title, options) =>
@@ -158,6 +158,7 @@ export const uiTerminalAndSessionTabsApi = {
sourceLeafId?: string
telemetrySource?: TerminalPaneSplitSource
newLeafId?: string
activate?: false
}) => void
): (() => void) => {
const listener = (
@@ -171,6 +172,7 @@ export const uiTerminalAndSessionTabsApi = {
sourceLeafId?: string
telemetrySource?: TerminalPaneSplitSource
newLeafId?: string
activate?: false
}
) => callback(data)
ipcRenderer.on('ui:splitTerminal', listener)
@@ -240,6 +240,7 @@ export type UiCommandEventApi = {
sourceLeafId?: string
telemetrySource?: TerminalPaneSplitSource
newLeafId?: string
activate?: false
}) => void
) => () => void
onRenameTerminal: (
@@ -76,7 +76,8 @@ export function installTerminalPaneMountEvents(args: {
}
const splitOptions = {
...(detail.newLeafId ? { leafId: detail.newLeafId } : {}),
...(detail.ptyId ? { ptyId: detail.ptyId } : {})
...(detail.ptyId ? { ptyId: detail.ptyId } : {}),
...(detail.activate === false ? { activate: false } : {})
}
if (detail.command) {
const createdPane = splitPaneWithOneShotStartup(ptyDeps, { command: detail.command }, () =>
+2
View File
@@ -48,6 +48,8 @@ export type SplitTerminalPaneDetail = {
telemetrySource?: TerminalPaneSplitSource
newLeafId?: string
ptyId?: string
/** An agent's split: the new pane leaves the user's active pane and keyboard focus alone. */
activate?: false
}
export type RequestActiveTerminalPaneSplitDetail = {
@@ -35,6 +35,7 @@ import { registerSettingsAndSidebarIpcBridge } from './settings-sidebar-ipc-brid
import { registerQuitAndStopAllSessionsIpcBridge } from './quit-and-stop-all-sessions-ipc-bridge'
import { registerTabLifecycleIpcBridge } from './tab-lifecycle-ipc-bridge'
import { registerTerminalPresentationIpcBridge } from './terminal-presentation-ipc-bridge'
import { registerTerminalTabMountIpcBridge } from './terminal-tab-mount-ipc-bridge'
import { registerPtySourceDisownedIpcBridge } from './pty-source-disowned-ipc-bridge'
import { registerTerminalRequestIpcBridge } from './terminal-request-ipc-bridge'
import { registerAgentLaunchTabIpcBridge } from './agent-launch-tab-ipc-bridge'
@@ -133,6 +134,7 @@ export function installAppLifetimeIpcEvents(): () => void {
)
registerTerminalPresentationIpcBridge(unsubs)
registerTerminalTabMountIpcBridge(unsubs)
registerTerminalRequestIpcBridge(unsubs)
registerAgentLaunchTabIpcBridge(unsubs)
registerPtySourceDisownedIpcBridge(unsubs)
@@ -1,7 +1,6 @@
import { presentAgentLaunchTab } from '@/lib/agent-session/launch/pane/agent-launch-tab-presentation'
import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount'
import { hasRegisteredRuntimeTerminalTab } from '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
import { planMobileTerminalTabMount } from '@/components/terminal-pane/mounting/mobile-terminal-tab-mount'
import { resolveTerminalTabPtyOwnership } from '@/lib/workspace/tabs/terminal-tab-for-pty-id'
import {
dispatchTerminalPaneSplitRequest,
@@ -202,7 +201,8 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v
sourcePtyId: existingLayout?.ptyIdsByLeafId?.[splitFromLeafId],
telemetrySource: splitTelemetrySource,
newLeafId: leafId,
ptyId
ptyId,
...(shouldActivate ? {} : { activate: false })
}
const targetMounted = hasRegisteredRuntimeTerminalTab(tab.id, worktreeId)
if (!targetMounted) {
@@ -289,30 +289,5 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v
)
)
// Why: background-mount a mobile-subscribed tab's PTY without navigating the desktop (STA-1840).
unsubs.push(
window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => {
if (!worktreeId) {
return
}
// Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree.
const mount = planMobileTerminalTabMount(
useAppStore.getState(),
{
worktreeId,
...(tabId ? { tabId } : {}),
...(ptyId ? { ptyId } : {})
},
{
isTabMounted: (tabId, targetWorktreeId) =>
hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId)
}
)
if (mount) {
requestBackgroundTerminalWorktreeMount(mount)
}
})
)
// Why: CLI-driven terminal creation waits for the tabId reply so it can hand the caller a usable handle immediately.
}
@@ -0,0 +1,105 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestStore, seedStore } from '../../store/testing/app-store-test-fixture'
import { makeTab } from '../../store/terminals/testing/terminal-tab.test-fixture'
import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture'
import { createStoreSessionMockApi } from '../../store/testing/app-store-session-api.test-fixture'
const mocks = vi.hoisted(() => {
const store: { current: ReturnType<typeof createTestStore> | null } = { current: null }
return { store, dispatchSplit: vi.fn() }
})
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false }))
vi.mock('../../store', () => ({
useAppStore: {
getState: () => mocks.store.current!.getState(),
setState: (...args: Parameters<ReturnType<typeof createTestStore>['setState']>) =>
mocks.store.current!.setState(...args),
subscribe: () => () => {}
}
}))
vi.mock(
'@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry',
async (importOriginal) => ({
...(await importOriginal<object>()),
hasRegisteredRuntimeTerminalTab: () => true
})
)
vi.mock('@/components/terminal-pane/layout/split/terminal-pane-split-request-routing', () => ({
dispatchTerminalPaneSplitRequest: mocks.dispatchSplit,
queueTerminalPaneSplitRequest: vi.fn()
}))
vi.mock('@/components/terminal-pane/input/focus/focus-terminal-tab-surface', () => ({
focusTerminalTabSurface: vi.fn()
}))
import { registerTerminalPresentationIpcBridge } from './terminal-presentation-ipc-bridge'
const WORKTREE = 'repo1::/repo1/main'
const TAB = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
const SOURCE_LEAF = '11111111-1111-4111-8111-111111111111'
const NEW_LEAF = '22222222-2222-4222-8222-222222222222'
type Listener = (payload: Record<string, unknown>) => void
function revealBackgroundSplit(): void {
const listeners = new Map<string, Listener>()
const ui = new Proxy(
{},
{
get: (_target, name) =>
typeof name === 'string' && name.startsWith('on')
? (listener: Listener) => {
listeners.set(name, listener)
return () => {}
}
: vi.fn()
}
)
vi.stubGlobal('window', { dispatchEvent: vi.fn(), api: { ...createStoreSessionMockApi(), ui } })
const store = createTestStore()
mocks.store.current = store
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: WORKTREE, repoId: 'repo1', path: '/repo1/main' })]
},
tabsByWorktree: {
[WORKTREE]: [makeTab({ id: TAB, worktreeId: WORKTREE, ptyId: 'pty-1' })]
},
terminalLayoutsByTabId: {
[TAB]: {
root: { type: 'leaf', leafId: SOURCE_LEAF },
activeLeafId: SOURCE_LEAF,
expandedLeafId: null,
ptyIdsByLeafId: { [SOURCE_LEAF]: 'pty-1' }
}
}
})
registerTerminalPresentationIpcBridge([])
listeners.get('onCreateTerminal')?.({
worktreeId: WORKTREE,
ptyId: 'pty-2',
tabId: TAB,
leafId: NEW_LEAF,
splitFromLeafId: SOURCE_LEAF,
splitDirection: 'vertical',
activate: false,
presentation: 'background'
})
}
beforeEach(() => {
vi.unstubAllGlobals()
mocks.dispatchSplit.mockReset()
})
describe('a runtime split revealed in the window', () => {
it('asks the pane not to take focus when the split is in the background', () => {
revealBackgroundSplit()
expect(mocks.dispatchSplit).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ newLeafId: NEW_LEAF, activate: false })
)
})
})
@@ -0,0 +1,31 @@
import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount'
import { hasRegisteredRuntimeTerminalTab } from '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
import { planMobileTerminalTabMount } from '@/components/terminal-pane/mounting/mobile-terminal-tab-mount'
import { useAppStore } from '../../store/index'
export function registerTerminalTabMountIpcBridge(unsubs: (() => void)[]): void {
// Why: background-mount a mobile-subscribed tab's PTY without navigating the desktop (STA-1840).
unsubs.push(
window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => {
if (!worktreeId) {
return
}
// Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree.
const mount = planMobileTerminalTabMount(
useAppStore.getState(),
{
worktreeId,
...(tabId ? { tabId } : {}),
...(ptyId ? { ptyId } : {})
},
{
isTabMounted: (tabId, targetWorktreeId) =>
hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId)
}
)
if (mount) {
requestBackgroundTerminalWorktreeMount(mount)
}
})
)
}
@@ -120,7 +120,8 @@ export function routeRuntimeTerminalSplitRequest(request: RuntimeTerminalSplitRe
command: request.command,
sourceLeafId: request.sourceLeafId,
telemetrySource: request.telemetrySource,
newLeafId: request.newLeafId
newLeafId: request.newLeafId,
...(request.activate === false ? { activate: false } : {})
}
if (hasRegisteredRuntimeTerminalTab(request.tabId, worktreeId)) {
dispatchTerminalPaneSplitRequest(detail)
@@ -47,6 +47,7 @@ type SplitManagedPaneArgs = {
spawnHints?: Parameters<NonNullable<PaneManagerOptions['onPaneCreated']>>[1]
) => void
getDragCallbacks: () => DragReorderCallbacks
activePaneId: number | null
setActivePaneId: (paneId: number | null) => void
isDestroyed: () => boolean
}
@@ -66,13 +67,24 @@ export function splitManagedPane(args: SplitManagedPaneArgs): ManagedPane | null
const divider = args.createDivider(isVertical)
const movedPaneStates = prepareMovedPanesForSplit(existingContainer, existing, args.panes)
const activate = args.opts?.activate !== false
const focusedBefore = activate ? null : document.activeElement
wrapInSplit(existingContainer, newPane.container, isVertical, divider, {
ratio: args.opts?.ratio,
newPaneFirst: args.newPaneFirst
})
args.setActivePaneId(newPane.id)
openSplitPane(args, newPane, existing.leafId, args.opts?.cwd)
if (activate) {
args.setActivePaneId(newPane.id)
} else if (
focusedBefore instanceof HTMLElement &&
focusedBefore.isConnected &&
document.activeElement !== focusedBefore
) {
// Reparenting the source pane drops its focus; give the user's keyboard back.
focusedBefore.focus({ preventScroll: true })
}
openSplitPane(args, newPane, existing.leafId, activate)
for (const movedPaneState of movedPaneStates) {
scheduleSplitScrollRestore(
@@ -143,15 +155,22 @@ function openSplitPane(
args: SplitManagedPaneArgs,
newPane: ManagedPaneInternal,
parentLeafId: string,
cwd?: string
activate: boolean
): void {
const cwd = args.opts?.cwd
openTerminal(newPane, {
ligatures: args.managerOptions.terminalLigaturesEnabled?.(),
inlineImages: args.managerOptions.terminalInlineImagesEnabled?.()
})
applyPaneOpacity(args.panes.values(), newPane.id, args.styleOptions)
applyPaneOpacity(
args.panes.values(),
activate ? newPane.id : args.activePaneId,
args.styleOptions
)
applyDividerStyles(args.root, args.styleOptions)
newPane.terminal.focus()
if (activate) {
newPane.terminal.focus()
}
updateMultiPaneState(args.getDragCallbacks())
// Forward creation hints to inherit local cwd or adopt the runtime-spawned PTY in web splits.
args.publishPaneCreated(newPane, {
@@ -33,6 +33,7 @@ type SplitPaneAroundLeafIdsArgs = {
spawnHints?: Parameters<NonNullable<PaneManagerOptions['onPaneCreated']>>[1]
) => void
getDragCallbacks: () => DragReorderCallbacks
activePaneId: number | null
setActivePaneId: (paneId: number | null) => void
isDestroyed: () => boolean
}
@@ -61,6 +62,7 @@ export function splitPaneAroundMountedSubtree(
createDivider: args.createDivider,
publishPaneCreated: args.publishPaneCreated,
getDragCallbacks: args.getDragCallbacks,
activePaneId: args.activePaneId,
setActivePaneId: args.setActivePaneId,
isDestroyed: args.isDestroyed
})
@@ -0,0 +1,49 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Terminal } from '@xterm/xterm'
// Why: happy-dom has no canvas, so xterm cannot open; focus is what this checks.
vi.mock('./pane-lifecycle', async (importOriginal) => {
const actual: object = await importOriginal()
return { ...actual, openTerminal: vi.fn() }
})
const { PaneManager } = await import('./pane-manager')
const LEAF_A = '11111111-1111-4111-8111-111111111111'
const LEAF_B = '22222222-2222-4222-8222-222222222222'
describe('PaneManager split focus', () => {
let root: HTMLDivElement
let manager: InstanceType<typeof PaneManager>
beforeEach(() => {
vi.stubGlobal('requestAnimationFrame', () => 1)
vi.stubGlobal('cancelAnimationFrame', () => {})
root = document.createElement('div')
document.body.appendChild(root)
manager = new PaneManager(root, { linkOpenHint: () => '' })
})
afterEach(() => {
manager.destroy()
root.remove()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('leaves the active pane and keyboard focus alone for a split that must not activate', () => {
const source = manager.createInitialPane({ leafId: LEAF_A, focus: false })
// Stands in for xterm's input, which the split reparents along with its pane.
const input = source.container.appendChild(document.createElement('textarea'))
input.focus()
const focus = vi.spyOn(Terminal.prototype, 'focus')
const created = manager.splitPane(source.id, 'vertical', { leafId: LEAF_B, activate: false })
expect(created?.leafId).toBe(LEAF_B)
expect(manager.getActivePane()?.leafId).toBe(LEAF_A)
expect(focus).not.toHaveBeenCalled()
expect(document.activeElement).toBe(input)
})
})
@@ -27,6 +27,7 @@ export function splitPaneOnManager(
createDivider: (isVertical) => host.createDivider(isVertical),
publishPaneCreated: (pane, spawnHints) => host.publishPaneCreated(pane, spawnHints),
getDragCallbacks: () => host.getDragCallbacks(),
activePaneId: host.getActivePaneId(),
setActivePaneId: (id) => {
host.setActivePaneId(id)
},
@@ -55,6 +56,7 @@ export function splitPaneAroundLeafIdsOnManager(
createDivider: (isVertical) => host.createDivider(isVertical),
publishPaneCreated: (pane, spawnHints) => host.publishPaneCreated(pane, spawnHints),
getDragCallbacks: () => host.getDragCallbacks(),
activePaneId: host.getActivePaneId(),
setActivePaneId: (id) => {
host.setActivePaneId(id)
},
@@ -27,6 +27,8 @@ export type PaneSpawnHints = {
export type PaneSplitOptions = Omit<PaneSpawnHints, 'placement'> & {
ratio?: number
leafId?: string
/** False for a split the user did not ask for: the active pane and keyboard focus stay put. */
activate?: boolean
}
export type ClosedPaneInfo = {