fix(desktop): keep the chat in front of the terminal in Focus layout (#81019)

* fix(desktop): hide the terminal overlay when its pane is inactive

One xterm is CSS-overlayed onto whichever `<TerminalSlot />` is active,
positioned with `position: fixed` from the slot's bounding rect. Keep-alive
tab layers stay MOUNTED when inactive — hidden with `visibility: hidden` +
`data-pane-hidden`, deliberately preserving their layout box so scroll state
and xterm survive a tab round-trip.

So an inactive terminal slot still reports a full-size rect identical to the
front tab's, and `rect.width > 0 && rect.height > 0` cannot tell the two
apart. The overlay stayed painted at z-4 over whatever tab the user switched
to, swallowing its clicks.

Sample the hidden state alongside the geometry: `Rect` carries `hidden` from
`isElementInHiddenPane(slot)`, `sameRect` compares it so a tab switch wakes
the tracker, the ancestor MutationObserver watches `PANE_HIDDEN_ATTR`, and
the overlay gates on `!rect.hidden`. `TerminalWorkspace` stays mounted
throughout — PTYs are never torn down, only the surface stops painting.

`opacity: 0` rides alongside `visibility: hidden` because Electron can keep
xterm's WebGL canvas composited after an ancestor goes hidden.

Refs #71407

* fix(desktop): collapse an active tool pane onto the workspace, not a neighbour

`setPaneCollapsed` on the ACTIVE pane of a shared zone that holds the
uncloseable workspace handed the active slot to `group.panes[at - 1]` — the
tab to its left, whichever that happened to be.

The workspace can't minimize (it would strand the app), so tab-switching to a
sibling is the right shape; picking a positional neighbour is not. In the
Focus preset the terminal is a tab in the workspace's own group:

    [workspace, files, review, terminal]

Collapsing the active terminal therefore selected `review`. The user asked for
the terminal to go away and landed on a diff pane they never opened — and with
the overlay still painting (before the previous commit), it read as "the
terminal came back".

Hand the slot to the uncloseable pane itself. That pane is the zone's anchor:
it's the one member guaranteed to be a real destination rather than another
tool the user was not asking for. The positional fallback stays for the
defensive case of collapsing the uncloseable pane itself.

This is deliberately broader than one entry point — every route into
`setPaneCollapsed` for a shared zone gets it: the rail, the tab toggle, and
⌃`. Pure tool-only zones are untouched and still fold as a unit.

* fix(desktop): front the workspace when a fresh chat starts

`startFreshSessionDraft` resets the whole view — messages, usage, timers,
route intent, cwd — but left `$terminalTakeover` set. That atom is not a
cosmetic flag: `controller.tsx` binds it as the terminal's toggle store via
`bindToolPaneCollapse`, so while it stays true the terminal keeps the pane
fronted and ⌘N appeared to bounce straight back into the shell.

Clear it, then `revealTreePane('workspace')`. The reveal is not redundant
with the clear: takeover can already be false while the terminal is simply
the active tab (the flag stays true behind a stacked sibling, and tile flows
never touch it), so the state the user sees and the state the flag describes
drift apart. Clearing homes the common case; revealing states the intent
outright — a new chat shows the chat.

The terminal is not torn down. Tool panels collapse to a rail and keep their
PTYs; re-opening finds the same shell.

The `+` / ⌘T tile path needs no takeover clear — it fronts its new tile
through `revealTreePane` and relies on the hidden-pane-aware overlay.

* fix(desktop): reveal the workspace without closing the terminal

The fresh-session commit cleared `$terminalTakeover` on the way to fronting
the workspace. That atom is not a Focus-only fronting flag — it is the
terminal's open/closed state in every layout, and clearing it is wrong twice
over.

Only the Focus preset stacks the terminal with the workspace. Default,
Terminal deck, and Quad each give it a zone of its own, where it sits beside
the chat and obscures nothing — and there ⌘N minimized a terminal the user
had deliberately open.

The flag is also persisted, so the damage outlived the session. On the next
boot the Focus terminal tab is still in the strip and its zone is not
minimized, so clicking it only calls `activateTreePane`; `PersistentTerminal`
mounts its workspace solely while takeover is true, so the tab fronted empty.

`revealTreePane('workspace')` already carries the whole intent. Behind another
tab the terminal is HIDDEN, not closed: it keeps its PTYs, and the overlay
stops painting on the pane-hidden marker from the first commit in this branch
— which is what was actually covering the chat. Removing the clear costs
nothing and keeps the toggle store truthful.

Two regression tests, both verified to fail when the clear is reinstated: a
terminal in its own zone stays open and visible across a fresh chat, and a
Focus terminal tab still mounts after a restart.

Reported by Copilot review on #81019.

---------

Co-authored-by: izumi0uu <izumi0uu@gmail.com>
Co-authored-by: Ritesh Patel <60716910+DECRUX9812@users.noreply.github.com>
This commit is contained in:
Austin Pickett
2026-08-07 07:23:03 -06:00
committed by GitHub
parent 23dce021a5
commit 5c6aff1430
7 changed files with 340 additions and 8 deletions
@@ -2,10 +2,17 @@ import { act, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { hiddenPaneProps, PANE_HIDDEN_ATTR } from '@/components/pane-shell/pane-visibility'
import { $paneStates } from '@/store/panes'
import { $terminalTakeover } from '../store'
import { PersistentTerminal, TerminalSlot } from './persistent'
vi.mock('../store', async () => ({
$terminalTakeover: (await import('nanostores')).atom(false)
}))
vi.mock('./terminals', () => ({
ensureTerminal: vi.fn()
}))
@@ -125,6 +132,17 @@ function Harness() {
)
}
function HiddenPaneHarness({ hidden }: { hidden: boolean }) {
return (
<>
<div {...hiddenPaneProps(hidden)}>
<TerminalSlot className="slot" />
</div>
<PersistentTerminal onAddSelectionToChat={() => undefined} />
</>
)
}
describe('PersistentTerminal rect tracking', () => {
beforeEach(() => {
;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
@@ -164,6 +182,7 @@ describe('PersistentTerminal rect tracking', () => {
afterEach(() => {
cleanup()
$terminalTakeover.set(false)
vi.unstubAllGlobals()
vi.restoreAllMocks()
setVisibility(false)
@@ -333,4 +352,62 @@ describe('PersistentTerminal rect tracking', () => {
expect(raf.pending()).toBe(1)
})
it('hides the overlay but keeps its workspace mounted when the terminal tab becomes inactive', () => {
const raf = installRaf()
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))
$terminalTakeover.set(true)
render(<HiddenPaneHarness hidden={false} />)
const overlay = container!.lastElementChild as HTMLElement
const workspace = container!.querySelector('[data-testid="terminal-workspace"]')
expect(overlay.style.visibility).toBe('visible')
expect(overlay.style.opacity).toBe('1')
expect(overlay.style.pointerEvents).toBe('auto')
expect(workspace).not.toBeNull()
expect(mutationObserveCalls.some(call => call.options?.attributeFilter?.includes(PANE_HIDDEN_ATTR))).toBe(true)
// Let the initial changed-rect follow-up settle. The hidden-pane transition
// must wake the observer from an otherwise idle state.
act(() => {
raf.runNext()
})
expect(raf.pending()).toBe(0)
act(() => {
root!.render(<HiddenPaneHarness hidden />)
mutationObserverCallback?.([], {} as MutationObserver)
})
expect(raf.pending()).toBe(1)
act(() => {
raf.runNext()
})
expect(overlay.style.visibility).toBe('hidden')
expect(overlay.style.opacity).toBe('0')
expect(overlay.style.pointerEvents).toBe('none')
expect(container!.querySelector('[data-testid="terminal-workspace"]')).toBe(workspace)
act(() => {
raf.runNext()
})
expect(raf.pending()).toBe(0)
act(() => {
root!.render(<HiddenPaneHarness hidden={false} />)
mutationObserverCallback?.([], {} as MutationObserver)
})
act(() => {
raf.runNext()
})
expect(overlay.style.visibility).toBe('visible')
expect(overlay.style.opacity).toBe('1')
expect(overlay.style.pointerEvents).toBe('auto')
expect(container!.querySelector('[data-testid="terminal-workspace"]')).toBe(workspace)
})
})
@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'
import { atom } from 'nanostores'
import { type CSSProperties, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { isElementInHiddenPane, PANE_HIDDEN_ATTR } from '@/components/pane-shell/pane-visibility'
import { $layoutTree } from '@/components/pane-shell/tree/store'
import { markRightPanePerf } from '@/debug/right-pane-events'
import { createRendererLoopPauseController } from '@/lib/renderer-loop-pause'
@@ -50,6 +51,7 @@ interface PersistentTerminalProps {
}
interface Rect {
hidden: boolean
top: number
left: number
width: number
@@ -57,7 +59,7 @@ interface Rect {
}
const sameRect = (a: Rect | null, b: Rect) =>
!!a && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height
!!a && a.hidden === b.hidden && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height
export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalProps) {
const slot = useStore($slot)
@@ -112,7 +114,16 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
// full pixel footprint, so half-pixel rects can't leak page bg through.
const top = Math.floor(r.top)
const left = Math.floor(r.left)
const next: Rect = { top, left, width: Math.ceil(r.right) - left, height: Math.ceil(r.bottom) - top }
// Inactive keep-alive panes deliberately retain the same rect as the
// foreground pane, so visibility must be sampled independently.
const next: Rect = {
hidden: isElementInHiddenPane(slot),
top,
left,
width: Math.ceil(r.right) - left,
height: Math.ceil(r.bottom) - top
}
if (!sameRect(prev, next)) {
prev = next
@@ -182,7 +193,7 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
for (let node: HTMLElement | null = slot; node; node = node.parentElement) {
positionObserver?.observe(node, {
attributeFilter: ['class', 'style', 'hidden', 'aria-hidden', 'data-state'],
attributeFilter: ['class', 'style', 'hidden', 'aria-hidden', 'data-state', PANE_HIDDEN_ATTR],
attributes: true,
childList: true,
subtree: false
@@ -218,7 +229,7 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
}
}, [slot])
const visible = Boolean(rect && rect.width > 0 && rect.height > 0)
const visible = Boolean(rect && !rect.hidden && rect.width > 0 && rect.height > 0)
const style: CSSProperties = {
position: 'fixed',
@@ -229,6 +240,10 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
display: 'flex',
flexDirection: 'column',
visibility: visible ? 'visible' : 'hidden',
// Electron may keep xterm's WebGL canvas visually composited after an
// ancestor becomes visibility:hidden. Opacity clears that compositor layer
// while preserving the mounted DOM, terminal dimensions, and live PTY.
opacity: visible ? 1 : 0,
pointerEvents: visible ? 'auto' : 'none',
zIndex: 4,
// Match the live skin surface so the header strip (transparent) and body
@@ -3,6 +3,7 @@ import type { MutableRefObject } from 'react'
import { useEffect } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { $terminalTakeover, setTerminalTakeover } from '@/app/right-sidebar/store'
import { noteActiveTreeGroup, revealTreePane } from '@/components/pane-shell/tree/store'
import { getSession, getSessionMessages, type SessionInfo } from '@/hermes'
import { createClientSessionState } from '@/lib/chat-runtime'
@@ -432,6 +433,30 @@ describe('startFreshSessionDraft', () => {
expect($currentCwd.get()).toBe('')
expect($newChatWorkspaceTarget.get()).toBeNull()
})
it('fronts the workspace without closing a terminal that is merely behind a tab', async () => {
// Regression: a persisted terminal takeover kept the terminal fronted
// after New Session / ⌘N. The fix is to reveal the workspace — NOT to
// clear the takeover atom. That atom is the terminal's open/closed state
// in every layout: clearing it here closed a terminal sitting in its own
// zone (Default / Terminal deck / Quad), and persisted a `false` that left
// the Focus tab unable to mount its workspace after a restart. Behind a
// tab the terminal is hidden, not closed.
const navigate = vi.fn()
const requestGateway = vi.fn(async () => ({}) as never)
let handle: HarnessHandle | null = null
setTerminalTakeover(true)
expect($terminalTakeover.get()).toBe(true)
render(<Harness navigate={navigate} onReady={value => (handle = value)} requestGateway={requestGateway} />)
await waitFor(() => expect(handle).not.toBeNull())
act(() => handle!.startFreshSessionDraft({ preserveRoute: true, workspaceTarget: null }))
expect(revealTreePane).toHaveBeenCalledWith('workspace')
expect($terminalTakeover.get()).toBe(true)
})
})
describe('createBackendSessionForSend profile routing', () => {
@@ -297,6 +297,16 @@ export function useSessionActions({
setAwaitingResponse(false)
clearNotifications()
setIntroSeed(seed => seed + 1)
// A fresh chat takes the screen. Front the workspace — and ONLY that:
// `$terminalTakeover` is the terminal's open/closed state in every
// layout, not a Focus-only overlay flag, so clearing it here would close
// a terminal sitting harmlessly in its own zone (Default, Terminal deck,
// Quad) and would persist a `false` that leaves the Focus tab unable to
// mount its workspace on the next boot. Behind another tab the terminal
// is hidden, not closed: it keeps its PTYs and the overlay stops
// painting on the pane-hidden marker, which is what actually cleared the
// chat.
revealTreePane('workspace')
// Clear the durable route intent synchronously, before React Router
// publishes /new. Submit uses that intent to heal an existing-session
// rebind race, so leaving the old id here could revive it on a very fast
@@ -42,9 +42,12 @@ export const PaneGroupContext = createContext(NO_PANE_GROUP)
export const usePaneGroup = (): string => useContext(PaneGroupContext)
/** Whether an element belongs to an inactive keep-alive pane. */
export const isElementInHiddenPane = (element: Element): boolean => Boolean(element.closest(HIDDEN_PANE))
/** `querySelectorAll` minus anything inside an inactive tab. */
export const queryAllVisible = <T extends HTMLElement>(selector: string, root: ParentNode = document): T[] =>
[...root.querySelectorAll<T>(selector)].filter(el => !el.closest(HIDDEN_PANE))
[...root.querySelectorAll<T>(selector)].filter(el => !isElementInHiddenPane(el))
/** `querySelector` minus anything inside an inactive tab. */
export const queryVisible = <T extends HTMLElement>(selector: string, root: ParentNode = document): null | T =>
@@ -1380,11 +1380,22 @@ export function setPaneCollapsed(paneId: string, collapsed: boolean) {
if (group.panes.length > 1) {
if (collapsed && group.active === paneId) {
if (group.panes.some(isUncloseablePane)) {
// Workspace can't minimize (strands the app) → tab-switch to a sibling
// (guaranteed to exist by length > 1).
// Workspace can't minimize (strands the app) → hand the active slot to
// the uncloseable (workspace) pane rather than an arbitrary adjacent
// sibling. [workspace, files, review, terminal] with the terminal
// active must land on workspace (New Session semantics), not on review
// via `panes[at - 1]` — which left the user stranded on a tool pane
// and (before the overlay fix) the terminal visually foreground.
const anchor = group.panes.find(isUncloseablePane)
const at = group.panes.indexOf(paneId)
activateTreePane(group.id, group.panes[at - 1] ?? group.panes[at + 1])
if (anchor && anchor !== paneId) {
activateTreePane(group.id, anchor)
} else {
// Defensive: collapsing the uncloseable pane itself (never bound to
// a tool toggle store) — fall back to the sibling.
activateTreePane(group.id, group.panes[at - 1] ?? group.panes[at + 1])
}
} else {
setTreeGroupMinimized(group.id, true) // pure tool zone folds as a unit
}
@@ -1,6 +1,7 @@
import { atom } from 'nanostores'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { $terminalTakeover, setTerminalTakeover } from '@/app/right-sidebar/store'
import { registry } from '@/contrib/registry'
import { allPaneIds, group, split } from './model'
@@ -8,9 +9,11 @@ import {
$dismissedPanes,
$hiddenTreePanes,
$layoutTree,
activateTreePane,
bindToolPaneCollapse,
closeToolPane,
isPaneVisible,
revealTreePane,
setTreeGroupHeaderHidden,
togglePaneVisible
} from './store'
@@ -44,6 +47,8 @@ beforeEach(() => {
for (const [id, data] of [
['workspace', { placement: 'main', uncloseable: true }],
['files', { placement: 'right' }],
['review', { placement: 'right' }],
['terminal', { placement: 'bottom' }],
['logs', { placement: 'bottom' }]
] as const) {
@@ -170,6 +175,192 @@ describe('toggling the terminal while it is stacked with logs', () => {
})
})
describe('collapsing the active terminal in a shared group with the workspace', () => {
// The terminal is a TAB in the workspace's own group under the Focus preset:
// [workspace, files, review, terminal]. Collapsing it used to hand the slot
// to `panes[at - 1]` — 'review' — so ⌃` / the rail / the statusbar toggle
// dropped the user on a diff pane they never opened, and with the overlay
// still painting it read as "the terminal came back". The slot belongs to
// the uncloseable workspace, the one member guaranteed to be a real
// destination.
function focusGroup() {
$layoutTree.set(group(['workspace', 'files', 'review', 'terminal'], { active: 'terminal', id: 'g-focus' }))
}
const focusActive = () => {
const tree = $layoutTree.get()
return tree?.type === 'group' ? tree.active : undefined
}
it('⌃` / the rail toggle lands on workspace, not review', () => {
focusGroup()
// Production wiring (controller.tsx): the takeover atom IS the terminal's
// toggle store; the closer/opener write it back.
bindToolPaneCollapse(
'terminal',
$terminalTakeover,
() => setTerminalTakeover(false),
() => setTerminalTakeover(true)
)
// User had the terminal open and active.
setTerminalTakeover(true)
expect($terminalTakeover.get()).toBe(true)
expect(focusActive()).toBe('terminal')
expect(isPaneVisible('terminal')).toBe(true)
// The user presses ⌃` (or clicks the rail / statusbar toggle) to put the
// terminal away. bindToolPaneCollapse routes a false store through
// setPaneCollapsed.
setTerminalTakeover(false)
expect($terminalTakeover.get()).toBe(false)
expect(isPaneVisible('terminal')).toBe(false)
// THE regression: used to be 'review' (group.panes[at - 1]).
expect(focusActive()).toBe('workspace')
expect(isPaneVisible('workspace')).toBe(true)
})
it('openNewSessionTile (+ / ⌘T): the new session tab fronts and the terminal tab goes hidden', () => {
const stored = 'stored-1'
const tilePaneId = `session-tile:${stored}`
const dispose = registry.register({
area: 'panes',
data: { placement: 'main' },
id: tilePaneId,
render: () => null,
title: 'new session'
})
disposers.push(dispose)
// The tile lands in the same shared zone as the workspace + terminal
// (Focus preset: docked 'center' into the focused chat zone).
$layoutTree.set(
group(['workspace', 'files', 'review', 'terminal', tilePaneId], { active: 'terminal', id: 'g-focus' })
)
bindToolPaneCollapse(
'terminal',
$terminalTakeover,
() => setTerminalTakeover(false),
() => setTerminalTakeover(true)
)
setTerminalTakeover(true)
expect(focusActive()).toBe('terminal')
expect(isPaneVisible('terminal')).toBe(true)
// Exactly what openNewSessionTile does after openSessionTile + patch:
// `revealTreePane(`session-tile:${stored}`)` (use-session-actions:521).
revealTreePane(tilePaneId)
expect(focusActive()).toBe(tilePaneId)
expect(isPaneVisible('terminal')).toBe(false)
// The terminal layer gets data-pane-hidden (tree-group spreads
// hiddenPaneProps(!isActive)), which the PersistentTerminal overlay now
// measures — so the terminal surface stops covering the new session tab.
expect(isPaneVisible(tilePaneId)).toBe(true)
expect($terminalTakeover.get()).toBe(true) // toggle store stays truthful
})
it('startFreshSessionDraft (⌘N): fronts the workspace and leaves the terminal open behind its tab', () => {
focusGroup()
bindToolPaneCollapse(
'terminal',
$terminalTakeover,
() => setTerminalTakeover(false),
() => setTerminalTakeover(true)
)
setTerminalTakeover(true)
expect(focusActive()).toBe('terminal')
// What startFreshSessionDraft does: reveal, and nothing else. It must NOT
// clear the takeover atom — that is the terminal's open/closed state, not
// a fronting flag.
revealTreePane('workspace')
expect(focusActive()).toBe('workspace')
expect(isPaneVisible('workspace')).toBe(true)
// Hidden behind the workspace tab, so the overlay stops painting (the
// actual cause of the chat being covered) …
expect(isPaneVisible('terminal')).toBe(false)
// … while the terminal stays OPEN: its PTYs live and clicking the tab
// brings back a mounted workspace.
expect($terminalTakeover.get()).toBe(true)
})
})
describe('a terminal that owns its own zone (Default / Terminal deck / Quad)', () => {
// Only the Focus preset stacks the terminal with the workspace. Everywhere
// else it sits in a group of its own, beside the chat rather than over it —
// so a fresh chat has no reason to touch it.
it('stays open and visible when a fresh chat fronts the workspace', () => {
$layoutTree.set(
split('row', [group(['workspace'], { id: 'grp-main' }), group(['terminal'], { id: 'grp-terminal' })], [3, 1])
)
bindToolPaneCollapse(
'terminal',
$terminalTakeover,
() => setTerminalTakeover(false),
() => setTerminalTakeover(true)
)
setTerminalTakeover(true)
expect(isPaneVisible('terminal')).toBe(true)
revealTreePane('workspace')
expect(isPaneVisible('workspace')).toBe(true)
// Regression: clearing takeover inside startFreshSessionDraft minimized
// this zone, folding a terminal that was never obscuring anything.
expect(isPaneVisible('terminal')).toBe(true)
expect($terminalTakeover.get()).toBe(true)
})
it('survives a restart with a clickable, mountable terminal tab', () => {
$layoutTree.set(group(['workspace', 'files', 'review', 'terminal'], { active: 'terminal', id: 'g-focus' }))
bindToolPaneCollapse(
'terminal',
$terminalTakeover,
() => setTerminalTakeover(false),
() => setTerminalTakeover(true)
)
setTerminalTakeover(true)
revealTreePane('workspace')
// ── restart: the tree and the takeover atom are both persisted ──
const persistedTakeover = $terminalTakeover.get()
bindToolPaneCollapse(
'terminal',
$terminalTakeover,
() => setTerminalTakeover(false),
() => setTerminalTakeover(true)
)
// Regression: a persisted `false` left the tab in the strip and
// un-minimized, but PersistentTerminal mounts its workspace only while
// takeover is true — so clicking the tab (a bare activateTreePane) fronted
// an empty pane.
expect(persistedTakeover).toBe(true)
activateTreePane('g-focus', 'terminal')
expect(isPaneVisible('terminal')).toBe(true)
expect($terminalTakeover.get()).toBe(true)
})
})
describe('a zone whose header the user hid', () => {
it('keeps it hidden after a stacked sibling is closed and toggled back', () => {
stackTree({ headerHidden: true })