The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep the chat in front of the terminal in Focus layout (#81019)
Austin Pickett5c6aff143067
diff --git a/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsxindex 77eeb480d63..a9c013301b2 100644--- a/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx+++ b/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx@@ -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)+ })})diff --git a/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx b/apps/desktop/src/app/right-sidebar/terminal/persistent.tsxindex d3a7b0c8290..9f7180a036d 100644--- a/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx+++ b/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx@@ -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: booleantop: numberleft: numberwidth: 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.heightexport 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 }: PersistentTerminalPfor (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 }: PersistentTerminalPdisplay: '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 bodydiff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 1bdb521efab..5bbcecaffb6 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -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', () => {diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 0f13a375c08..543074f0265 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -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 fastdiff --git a/apps/desktop/src/components/pane-shell/pane-visibility.ts b/apps/desktop/src/components/pane-shell/pane-visibility.tsindex 16f9d402ad8..0a7169e68be 100644--- a/apps/desktop/src/components/pane-shell/pane-visibility.ts+++ b/apps/desktop/src/components/pane-shell/pane-visibility.ts@@ -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 =>diff --git a/apps/desktop/src/components/pane-shell/tree/store.ts b/apps/desktop/src/components/pane-shell/tree/store.tsindex 53286d4c417..daf7d77fe23 100644--- a/apps/desktop/src/components/pane-shell/tree/store.ts+++ b/apps/desktop/src/components/pane-shell/tree/store.ts@@ -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}diff --git a/apps/desktop/src/components/pane-shell/tree/tool-pane-toggle.test.ts b/apps/desktop/src/components/pane-shell/tree/tool-pane-toggle.test.tsindex 6e24300d6d3..e8dac0adb7d 100644--- a/apps/desktop/src/components/pane-shell/tree/tool-pane-toggle.test.ts+++ b/apps/desktop/src/components/pane-shell/tree/tool-pane-toggle.test.ts@@ -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 })