Fix sidebar virtual scroll anchoring (#2114)
This commit is contained in:
@@ -36,6 +36,7 @@ import { isFolderRepo } from '../../../../shared/repo-kind'
|
||||
import { runWorktreeBatchDelete, runWorktreeDelete } from './delete-worktree-flow'
|
||||
import { runSleepWorktrees } from './sleep-worktree-flow'
|
||||
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor'
|
||||
import { getLineageRenderInfo } from './worktree-list-groups'
|
||||
import { getWorkspaceStatus, getWorkspaceStatusVisualMeta } from './workspace-status'
|
||||
import { WorktreeOpenInSubMenu } from './WorktreeOpenInMenu'
|
||||
@@ -75,6 +76,68 @@ function shouldSuppressContextMenuFollowUpClick(contextMenuOpenedAt: number, now
|
||||
)
|
||||
}
|
||||
|
||||
function findSidebarVirtualRowByKey(sidebar: Element, rowKey: string): HTMLElement | null {
|
||||
return (
|
||||
Array.from(sidebar.querySelectorAll<HTMLElement>('[data-worktree-virtual-row]')).find(
|
||||
(element) => element.getAttribute('data-worktree-virtual-row-key') === rowKey
|
||||
) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
function preserveDeleteSiblingPosition(scope: HTMLElement | null): () => void {
|
||||
const sidebar = scope?.closest('[data-worktree-sidebar]')
|
||||
const row = scope?.closest('[data-worktree-virtual-row]')
|
||||
if (!(sidebar instanceof HTMLElement) || !(row instanceof HTMLElement)) {
|
||||
return () => {}
|
||||
}
|
||||
const rows = Array.from(
|
||||
sidebar.querySelectorAll<HTMLElement>('[data-worktree-virtual-row]')
|
||||
).sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top)
|
||||
const rowIndex = rows.indexOf(row)
|
||||
const anchorRow = rows[rowIndex + 1] ?? rows[rowIndex - 1] ?? null
|
||||
const anchorKey = anchorRow?.getAttribute('data-worktree-virtual-row-key')
|
||||
const rowKey = row.getAttribute('data-worktree-virtual-row-key')
|
||||
if (!anchorKey || !rowKey) {
|
||||
return () => {}
|
||||
}
|
||||
const previousScrollTop = sidebar.scrollTop
|
||||
const previousScrollHeight = sidebar.scrollHeight
|
||||
const desiredTop = row.getBoundingClientRect().top
|
||||
|
||||
return () => {
|
||||
let attempts = 0
|
||||
let stableFrames = 0
|
||||
const restore = (): void => {
|
||||
const currentSidebar = document.querySelector('[data-worktree-sidebar]')
|
||||
if (!(currentSidebar instanceof HTMLElement)) {
|
||||
return
|
||||
}
|
||||
const currentTarget = findSidebarVirtualRowByKey(currentSidebar, rowKey)
|
||||
const currentAnchor = currentTarget ?? findSidebarVirtualRowByKey(currentSidebar, anchorKey)
|
||||
if (currentAnchor) {
|
||||
const delta = currentAnchor.getBoundingClientRect().top - desiredTop
|
||||
if (Math.abs(delta) > 1) {
|
||||
currentSidebar.scrollTop += delta
|
||||
stableFrames = 0
|
||||
} else {
|
||||
stableFrames += 1
|
||||
}
|
||||
} else {
|
||||
currentSidebar.scrollTop = Math.max(
|
||||
0,
|
||||
previousScrollTop + currentSidebar.scrollHeight - previousScrollHeight
|
||||
)
|
||||
stableFrames = 0
|
||||
}
|
||||
attempts += 1
|
||||
if (attempts < 180 && (currentTarget || stableFrames < 6)) {
|
||||
window.requestAnimationFrame(restore)
|
||||
}
|
||||
}
|
||||
restore()
|
||||
}
|
||||
}
|
||||
|
||||
const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
worktree,
|
||||
children,
|
||||
@@ -100,6 +163,7 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId)
|
||||
const browserTabsByWorktree = useAppStore((s) => s.browserTabsByWorktree)
|
||||
const deleteStateByWorktreeId = useAppStore((s) => s.deleteStateByWorktreeId)
|
||||
const scopeRef = useRef<HTMLDivElement>(null)
|
||||
const contextMenuOpenedAtRef = useRef<number | null>(null)
|
||||
const activeContextWorktrees = menuOpen ? contextWorktrees : selectedWorktrees
|
||||
const isMultiContext = activeContextWorktrees.length > 1
|
||||
@@ -239,33 +303,51 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
openModal
|
||||
])
|
||||
|
||||
const handleCloseTerminals = useCallback(async () => {
|
||||
await runSleepWorktrees(sleepableWorktrees.map((item) => item.id))
|
||||
const handleCloseTerminals = useCallback(() => {
|
||||
const worktreeIds = sleepableWorktrees.map((item) => item.id)
|
||||
setMenuOpen(false)
|
||||
// Why: Sleep can remount the sidebar when it clears the active workspace.
|
||||
// Let Radix finish closing the menu first so its focus/portal teardown
|
||||
// cannot scroll the virtualized list during that remount.
|
||||
window.setTimeout(() => {
|
||||
void runSleepWorktrees(worktreeIds)
|
||||
}, 50)
|
||||
}, [sleepableWorktrees])
|
||||
|
||||
const handleDelete = useCallback(() => {
|
||||
// Folder mode handled inline because it routes to a different modal;
|
||||
// standard delete delegates to the shared runWorktreeDelete helper.
|
||||
const restoreSidebarPosition = preserveDeleteSiblingPosition(scopeRef.current)
|
||||
scopeRef.current
|
||||
?.closest('[data-worktree-sidebar]')
|
||||
?.dispatchEvent(new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT))
|
||||
setMenuOpen(false)
|
||||
if (isMultiContext) {
|
||||
runWorktreeBatchDelete(batchDeleteWorktrees.map((item) => item.id))
|
||||
return
|
||||
}
|
||||
if (isFolder) {
|
||||
// Why: folder mode reuses the worktree row UI for a synthetic root entry,
|
||||
// but users still expect "remove" to disconnect the folder from Orca,
|
||||
// not to run git-style delete semantics against the real folder on disk.
|
||||
openModal('confirm-remove-folder', {
|
||||
repoId: worktree.repoId,
|
||||
displayName: worktree.displayName
|
||||
})
|
||||
return
|
||||
}
|
||||
// Why delegate to runWorktreeDelete: keeps the skip-confirm vs. modal
|
||||
// decision tree (and its rationale) in one place shared with the memory
|
||||
// popover's inline Delete action. Folder mode short-circuits above
|
||||
// because the confirm-remove-folder modal is unique to this caller.
|
||||
runWorktreeDelete(worktree.id)
|
||||
// Why: Delete can remove the active row and remount the sidebar. Run it
|
||||
// after menu close for the same reason as Sleep above.
|
||||
window.setTimeout(() => {
|
||||
if (isMultiContext) {
|
||||
runWorktreeBatchDelete(batchDeleteWorktrees.map((item) => item.id))
|
||||
restoreSidebarPosition()
|
||||
return
|
||||
}
|
||||
if (isFolder) {
|
||||
// Why: folder mode reuses the worktree row UI for a synthetic root entry,
|
||||
// but users still expect "remove" to disconnect the folder from Orca,
|
||||
// not to run git-style delete semantics against the real folder on disk.
|
||||
openModal('confirm-remove-folder', {
|
||||
repoId: worktree.repoId,
|
||||
displayName: worktree.displayName
|
||||
})
|
||||
restoreSidebarPosition()
|
||||
return
|
||||
}
|
||||
// Why delegate to runWorktreeDelete: keeps the skip-confirm vs. modal
|
||||
// decision tree (and its rationale) in one place shared with the memory
|
||||
// popover's inline Delete action. Folder mode short-circuits above
|
||||
// because the confirm-remove-folder modal is unique to this caller.
|
||||
runWorktreeDelete(worktree.id)
|
||||
restoreSidebarPosition()
|
||||
}, 50)
|
||||
}, [
|
||||
batchDeleteWorktrees,
|
||||
isFolder,
|
||||
@@ -308,8 +390,21 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleCloseAutoFocus = useCallback((event: Event) => {
|
||||
// Why: Radix otherwise restores focus to the hidden context-menu trigger.
|
||||
// When Sleep/Delete clears the active workspace and remounts the sidebar,
|
||||
// that focus restore can scroll the virtual list away from the row the
|
||||
// user just acted on.
|
||||
event.preventDefault()
|
||||
const sidebar = scopeRef.current?.closest('[data-worktree-sidebar]')
|
||||
if (sidebar instanceof HTMLElement) {
|
||||
sidebar.focus({ preventScroll: true })
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={scopeRef}
|
||||
className="relative"
|
||||
{...{ [WORKTREE_CONTEXT_MENU_SCOPE_ATTR]: 'worktree' }}
|
||||
onContextMenuCapture={(event) => {
|
||||
@@ -345,6 +440,7 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
onPointerUpCapture={suppressOpeningPointerEvent}
|
||||
onMouseUpCapture={suppressOpeningPointerEvent}
|
||||
onClickCapture={suppressOpeningPointerEvent}
|
||||
onCloseAutoFocus={handleCloseAutoFocus}
|
||||
>
|
||||
{!isMultiContext && (
|
||||
<>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
/* eslint-disable max-lines */
|
||||
import React, { useMemo, useCallback, useRef, useState, useEffect, useLayoutEffect } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import {
|
||||
measureElement as measureVirtualElementSize,
|
||||
useVirtualizer
|
||||
} from '@tanstack/react-virtual'
|
||||
import { ChevronDown, CircleX, Plus, Workflow } from 'lucide-react'
|
||||
import { useAppStore } from '@/store'
|
||||
import {
|
||||
@@ -55,6 +58,7 @@ import {
|
||||
sidebarHasActiveFilters
|
||||
} from './visible-worktrees'
|
||||
import {
|
||||
VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT,
|
||||
useVirtualizedScrollAnchor,
|
||||
type VirtualizedScrollAnchor
|
||||
} from '@/hooks/useVirtualizedScrollAnchor'
|
||||
@@ -217,6 +221,22 @@ function getRenderRowKey(row: RenderRow): string {
|
||||
return `wt:${row.worktree.id}`
|
||||
}
|
||||
|
||||
function getVirtualRowIndex(element: Element): number | null {
|
||||
const index = parseInt(element.getAttribute('data-index') ?? '', 10)
|
||||
return Number.isNaN(index) ? null : index
|
||||
}
|
||||
|
||||
function getVirtualRowKey(element: Element): string | null {
|
||||
return element.getAttribute('data-worktree-virtual-row-key')
|
||||
}
|
||||
|
||||
function estimateRenderRowSize(row: RenderRow | undefined): number {
|
||||
if (row?.type === 'lineage-group') {
|
||||
return 104 + Math.max(0, row.rows.length - 1) * 96
|
||||
}
|
||||
return 120
|
||||
}
|
||||
|
||||
function getVirtualRowTransform(start: number): string {
|
||||
return `translateY(${start}px)`
|
||||
}
|
||||
@@ -274,6 +294,8 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
() => renderRows.findIndex((row) => renderRowContainsWorktree(row, activeWorktreeId)),
|
||||
[renderRows, activeWorktreeId]
|
||||
)
|
||||
const renderRowsRef = useRef(renderRows)
|
||||
renderRowsRef.current = renderRows
|
||||
const getVirtualItemKey = useCallback(
|
||||
(index: number) => {
|
||||
const row = renderRows[index]
|
||||
@@ -284,17 +306,50 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
},
|
||||
[renderRows]
|
||||
)
|
||||
const getExpectedVirtualRowKey = useCallback((element: Element) => {
|
||||
const index = getVirtualRowIndex(element)
|
||||
const row = index === null ? undefined : renderRowsRef.current[index]
|
||||
return row ? getRenderRowKey(row) : null
|
||||
}, [])
|
||||
const isCurrentVirtualRowElement = useCallback(
|
||||
(element: Element) => {
|
||||
const expectedKey = getExpectedVirtualRowKey(element)
|
||||
return (
|
||||
element.isConnected &&
|
||||
expectedKey !== null &&
|
||||
element.getAttribute('data-worktree-virtual-row-key') === expectedKey
|
||||
)
|
||||
},
|
||||
[getExpectedVirtualRowKey]
|
||||
)
|
||||
const measureCurrentVirtualRowElement = useCallback(
|
||||
(
|
||||
element: HTMLDivElement,
|
||||
entry: ResizeObserverEntry | undefined,
|
||||
instance: Parameters<typeof measureVirtualElementSize<HTMLDivElement>>[2]
|
||||
) => {
|
||||
if (!isCurrentVirtualRowElement(element)) {
|
||||
const index = getVirtualRowIndex(element)
|
||||
const measured = instance.getVirtualItems().find((item) => item.index === index)
|
||||
// Why: TanStack's ResizeObserver can deliver a stale row after a
|
||||
// collapse/delete/remount. Returning the current item size makes that
|
||||
// observation a no-op instead of writing the stale element's height
|
||||
// into whichever row now owns the old data-index.
|
||||
return (
|
||||
measured?.size ??
|
||||
estimateRenderRowSize(index === null ? undefined : renderRowsRef.current[index])
|
||||
)
|
||||
}
|
||||
return measureVirtualElementSize(element, entry, instance)
|
||||
},
|
||||
[isCurrentVirtualRowElement]
|
||||
)
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: renderRows.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: (index) => {
|
||||
const row = renderRows[index]
|
||||
if (row?.type === 'lineage-group') {
|
||||
return 104 + Math.max(0, row.rows.length - 1) * 96
|
||||
}
|
||||
return 120
|
||||
},
|
||||
estimateSize: (index) => estimateRenderRowSize(renderRows[index]),
|
||||
measureElement: measureCurrentVirtualRowElement,
|
||||
overscan: 10,
|
||||
gap: 6,
|
||||
// Why: tells the virtualizer to start its internal scrollOffset at the
|
||||
@@ -396,27 +451,30 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
() => renderRows.map(getRenderRowKey).join('\n'),
|
||||
[renderRows]
|
||||
)
|
||||
const renderRowsRef = useRef(renderRows)
|
||||
renderRowsRef.current = renderRows
|
||||
const totalSize = virtualizer.getTotalSize()
|
||||
const virtualItems = virtualizer.getVirtualItems()
|
||||
|
||||
const measureMountedRows = useCallback(() => {
|
||||
const currentRows = renderRowsRef.current
|
||||
virtualizer.elementsCache.forEach((element) => {
|
||||
const idx = parseInt(element.getAttribute('data-index') ?? '', 10)
|
||||
const row = Number.isNaN(idx) ? undefined : currentRows[idx]
|
||||
const expectedKey = row ? getRenderRowKey(row) : null
|
||||
if (
|
||||
!element.isConnected ||
|
||||
expectedKey === null ||
|
||||
element.getAttribute('data-worktree-virtual-row-key') !== expectedKey
|
||||
) {
|
||||
if (!isCurrentVirtualRowElement(element)) {
|
||||
return
|
||||
}
|
||||
virtualizer.measureElement(element)
|
||||
})
|
||||
}, [virtualizer])
|
||||
}, [isCurrentVirtualRowElement, virtualizer])
|
||||
const measureVirtualRowElement = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
if (!element) {
|
||||
virtualizer.measureElement(null)
|
||||
return
|
||||
}
|
||||
if (!isCurrentVirtualRowElement(element)) {
|
||||
return
|
||||
}
|
||||
virtualizer.measureElement(element)
|
||||
},
|
||||
[isCurrentVirtualRowElement, virtualizer]
|
||||
)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// Why: after delete/collapse, TanStack may briefly retain the removed row's
|
||||
@@ -430,7 +488,9 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
|
||||
useVirtualizedScrollAnchor({
|
||||
anchorRef: scrollAnchorRef,
|
||||
getItemElementKey: getVirtualRowKey,
|
||||
getRowKey: getRenderRowKey,
|
||||
itemElementSelector: '[data-worktree-virtual-row]',
|
||||
rows: renderRows,
|
||||
scrollElementRef: scrollRef,
|
||||
scrollOffsetRef,
|
||||
@@ -438,6 +498,17 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
virtualizer
|
||||
})
|
||||
|
||||
const recordCurrentScrollAnchor = useCallback(() => {
|
||||
scrollRef.current?.dispatchEvent(new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT))
|
||||
}, [])
|
||||
const toggleGroupWithScrollAnchor = useCallback(
|
||||
(groupKey: string) => {
|
||||
recordCurrentScrollAnchor()
|
||||
toggleGroup(groupKey)
|
||||
},
|
||||
[recordCurrentScrollAnchor, toggleGroup]
|
||||
)
|
||||
|
||||
const navigateWorktree = useCallback(
|
||||
(direction: 'up' | 'down') => {
|
||||
// Why: derive the cycling order from an all-expanded layout, not the
|
||||
@@ -689,7 +760,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
data-worktree-virtual-row
|
||||
data-worktree-virtual-row-key={String(vItem.key)}
|
||||
data-index={vItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
ref={measureVirtualRowElement}
|
||||
className="absolute left-0 right-0"
|
||||
style={{ transform: getVirtualRowTransform(vItem.start) }}
|
||||
>
|
||||
@@ -735,11 +806,11 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
? (event) => handleWorkspaceStatusDrop(event, headerWorkspaceStatus)
|
||||
: undefined
|
||||
}
|
||||
onClick={() => toggleGroup(row.key)}
|
||||
onClick={() => toggleGroupWithScrollAnchor(row.key)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
toggleGroup(row.key)
|
||||
toggleGroupWithScrollAnchor(row.key)
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -985,7 +1056,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
? (event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
toggleGroup(lineageToggleGroupKey)
|
||||
toggleGroupWithScrollAnchor(lineageToggleGroupKey)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
@@ -1004,7 +1075,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
data-worktree-virtual-row
|
||||
data-worktree-virtual-row-key={String(vItem.key)}
|
||||
data-index={vItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
ref={measureVirtualRowElement}
|
||||
className="absolute left-0 right-0"
|
||||
style={{ transform: getVirtualRowTransform(vItem.start) }}
|
||||
>
|
||||
@@ -1032,7 +1103,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
data-worktree-virtual-row
|
||||
data-worktree-virtual-row-key={String(vItem.key)}
|
||||
data-index={vItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
ref={measureVirtualRowElement}
|
||||
data-workspace-status-drop-target={itemWorkspaceStatus ? '' : undefined}
|
||||
data-workspace-status={itemWorkspaceStatus ?? undefined}
|
||||
className="absolute left-0 right-0"
|
||||
|
||||
@@ -12,7 +12,9 @@ const mocks = vi.hoisted(() => {
|
||||
ptyIdsByTabId: {} as Record<string, string[]>
|
||||
}
|
||||
const toastError = vi.fn()
|
||||
return { state, toastError }
|
||||
const markWorktreeSleepIntent = vi.fn()
|
||||
const clearWorktreeSleepIntent = vi.fn()
|
||||
return { clearWorktreeSleepIntent, markWorktreeSleepIntent, state, toastError }
|
||||
})
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
@@ -22,6 +24,10 @@ vi.mock('@/store', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { error: mocks.toastError } }))
|
||||
vi.mock('@/lib/worktree-sleep-intent', () => ({
|
||||
clearWorktreeSleepIntent: mocks.clearWorktreeSleepIntent,
|
||||
markWorktreeSleepIntent: mocks.markWorktreeSleepIntent
|
||||
}))
|
||||
|
||||
import { runSleepWorktree, runSleepWorktrees } from './sleep-worktree-flow'
|
||||
|
||||
@@ -32,6 +38,8 @@ describe('runSleepWorktree', () => {
|
||||
mocks.state.shutdownWorktreeTerminals.mockClear().mockResolvedValue(undefined)
|
||||
mocks.state.suppressPtyExit.mockClear()
|
||||
mocks.state.consumeSuppressedPtyExit.mockClear()
|
||||
mocks.markWorktreeSleepIntent.mockClear()
|
||||
mocks.clearWorktreeSleepIntent.mockClear()
|
||||
mocks.toastError.mockClear()
|
||||
mocks.state.activeWorktreeId = null
|
||||
mocks.state.tabsByWorktree = {}
|
||||
@@ -67,27 +75,19 @@ describe('runSleepWorktree', () => {
|
||||
expect(activeClear).toBeLessThan(browsersCall)
|
||||
})
|
||||
|
||||
it('suppresses active PTY exits before clearing the active slept worktree', async () => {
|
||||
it('marks active sleep intent before clearing the active slept worktree', async () => {
|
||||
mocks.state.activeWorktreeId = 'wt-1'
|
||||
mocks.state.tabsByWorktree = {
|
||||
'wt-1': [{ id: 'tab-1' }, { id: 'tab-2' }],
|
||||
'wt-2': [{ id: 'tab-other' }]
|
||||
}
|
||||
mocks.state.ptyIdsByTabId = {
|
||||
'tab-1': ['pty-1'],
|
||||
'tab-2': ['pty-2', 'pty-3'],
|
||||
'tab-other': ['pty-other']
|
||||
}
|
||||
|
||||
await runSleepWorktree('wt-1')
|
||||
|
||||
expect(mocks.state.suppressPtyExit).toHaveBeenCalledTimes(3)
|
||||
expect(mocks.state.suppressPtyExit).toHaveBeenNthCalledWith(1, 'pty-1')
|
||||
expect(mocks.state.suppressPtyExit).toHaveBeenNthCalledWith(2, 'pty-2')
|
||||
expect(mocks.state.suppressPtyExit).toHaveBeenNthCalledWith(3, 'pty-3')
|
||||
const suppressCall = mocks.state.suppressPtyExit.mock.invocationCallOrder[0]
|
||||
expect(mocks.markWorktreeSleepIntent).toHaveBeenCalledWith('wt-1')
|
||||
expect(mocks.clearWorktreeSleepIntent).toHaveBeenCalledWith('wt-1')
|
||||
const markCall = mocks.markWorktreeSleepIntent.mock.invocationCallOrder[0]
|
||||
const activeClear = mocks.state.setActiveWorktree.mock.invocationCallOrder[0]
|
||||
expect(suppressCall).toBeLessThan(activeClear)
|
||||
const terminalShutdown = mocks.state.shutdownWorktreeTerminals.mock.invocationCallOrder[0]
|
||||
const clearCall = mocks.clearWorktreeSleepIntent.mock.invocationCallOrder[0]
|
||||
expect(markCall).toBeLessThan(activeClear)
|
||||
expect(terminalShutdown).toBeLessThan(clearCall)
|
||||
})
|
||||
|
||||
it('leaves activeWorktreeId alone when sleeping a background worktree', async () => {
|
||||
@@ -97,6 +97,7 @@ describe('runSleepWorktree', () => {
|
||||
|
||||
expect(mocks.state.setActiveWorktree).not.toHaveBeenCalled()
|
||||
expect(mocks.state.suppressPtyExit).not.toHaveBeenCalled()
|
||||
expect(mocks.markWorktreeSleepIntent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a toast and skips terminals when browsers throws', async () => {
|
||||
@@ -108,7 +109,7 @@ describe('runSleepWorktree', () => {
|
||||
await runSleepWorktree('wt-1')
|
||||
|
||||
expect(mocks.state.shutdownWorktreeTerminals).not.toHaveBeenCalled()
|
||||
expect(mocks.state.consumeSuppressedPtyExit).toHaveBeenCalledWith('pty-1')
|
||||
expect(mocks.clearWorktreeSleepIntent).toHaveBeenCalledWith('wt-1')
|
||||
expect(mocks.toastError).toHaveBeenCalledWith(
|
||||
'Failed to sleep workspace',
|
||||
expect.objectContaining({ description: 'boom' })
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { toast } from 'sonner'
|
||||
import { useAppStore } from '@/store'
|
||||
import { clearWorktreeSleepIntent, markWorktreeSleepIntent } from '@/lib/worktree-sleep-intent'
|
||||
import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor'
|
||||
|
||||
/**
|
||||
* Shared "sleep worktree" flow (close all panels to free memory / CPU)
|
||||
@@ -18,22 +20,63 @@ export async function runSleepWorktree(worktreeId: string): Promise<void> {
|
||||
await runSleepWorktrees([worktreeId])
|
||||
}
|
||||
|
||||
function suppressActiveSleepPtyExitActivity(worktreeId: string): string[] {
|
||||
const { ptyIdsByTabId, suppressPtyExit, tabsByWorktree } = useAppStore.getState()
|
||||
const ptyIds: string[] = []
|
||||
for (const tab of tabsByWorktree[worktreeId] ?? []) {
|
||||
for (const ptyId of ptyIdsByTabId[tab.id] ?? []) {
|
||||
ptyIds.push(ptyId)
|
||||
suppressPtyExit(ptyId)
|
||||
}
|
||||
}
|
||||
return ptyIds
|
||||
function findSidebarWorktreeRow(worktreeId: string): HTMLElement | null {
|
||||
const rowKey = `wt:${worktreeId}`
|
||||
return (
|
||||
Array.from(document.querySelectorAll<HTMLElement>('[data-worktree-virtual-row]')).find(
|
||||
(element) => element.getAttribute('data-worktree-virtual-row-key') === rowKey
|
||||
) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
function releaseActiveSleepPtyExitSuppressions(ptyIds: readonly string[]): void {
|
||||
const { consumeSuppressedPtyExit } = useAppStore.getState()
|
||||
for (const ptyId of ptyIds) {
|
||||
consumeSuppressedPtyExit(ptyId)
|
||||
function preserveSidebarWorktreePosition(worktreeId: string): () => void {
|
||||
if (typeof document === 'undefined') {
|
||||
return () => {}
|
||||
}
|
||||
const getScroller = (): HTMLElement | null =>
|
||||
document.querySelector<HTMLElement>('[data-worktree-sidebar]')
|
||||
const scroller = getScroller()
|
||||
const row = findSidebarWorktreeRow(worktreeId)
|
||||
if (!scroller || !row) {
|
||||
return () => {}
|
||||
}
|
||||
scroller.dispatchEvent(new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT))
|
||||
const previousScrollTop = scroller.scrollTop
|
||||
const previousScrollHeight = scroller.scrollHeight
|
||||
const previousTop = row.getBoundingClientRect().top
|
||||
|
||||
return () => {
|
||||
let attempts = 0
|
||||
const restore = (): void => {
|
||||
const currentScroller = getScroller()
|
||||
if (!currentScroller) {
|
||||
attempts += 1
|
||||
if (attempts < 12) {
|
||||
window.requestAnimationFrame(restore)
|
||||
}
|
||||
return
|
||||
}
|
||||
const nextRow = findSidebarWorktreeRow(worktreeId)
|
||||
if (!nextRow) {
|
||||
// Why: a remount can first render the wrong virtual window. Put the
|
||||
// scroller near the same content after height changes so the row
|
||||
// mounts, then retry and correct by actual DOM position.
|
||||
currentScroller.scrollTop = Math.max(
|
||||
0,
|
||||
previousScrollTop + currentScroller.scrollHeight - previousScrollHeight
|
||||
)
|
||||
} else {
|
||||
const delta = nextRow.getBoundingClientRect().top - previousTop
|
||||
if (Math.abs(delta) > 1) {
|
||||
currentScroller.scrollTop += delta
|
||||
}
|
||||
}
|
||||
attempts += 1
|
||||
if (attempts < 12) {
|
||||
window.requestAnimationFrame(restore)
|
||||
}
|
||||
}
|
||||
window.requestAnimationFrame(restore)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,42 +90,48 @@ export async function runSleepWorktrees(worktreeIds: readonly string[]): Promise
|
||||
shutdownWorktreeBrowsers,
|
||||
shutdownWorktreeTerminals
|
||||
} = useAppStore.getState()
|
||||
let preSuppressedActivePtyIds: string[] = []
|
||||
let activeSleepIntentWorktreeId: string | null = null
|
||||
if (activeWorktreeId && worktreeIds.includes(activeWorktreeId)) {
|
||||
// Why: clearing the active workspace unmounts its TerminalPanes before
|
||||
// shutdownWorktreeTerminals can mark exits as intentional. Pre-suppress
|
||||
// those PTYs so the unmount does not stamp lastActivityAt and reorder the
|
||||
// slept card to the top.
|
||||
preSuppressedActivePtyIds = suppressActiveSleepPtyExitActivity(activeWorktreeId)
|
||||
const restoreSidebarPosition = preserveSidebarWorktreePosition(activeWorktreeId)
|
||||
// Why: clearing the active workspace can unmount TerminalPanes before
|
||||
// shutdownWorktreeTerminals writes PTY suppressions. Use a non-rendering
|
||||
// intent marker so those exits do not stamp activity, without inserting an
|
||||
// extra Zustand update that can disturb the sidebar's scroll restoration.
|
||||
markWorktreeSleepIntent(activeWorktreeId)
|
||||
activeSleepIntentWorktreeId = activeWorktreeId
|
||||
setActiveWorktree(null)
|
||||
restoreSidebarPosition()
|
||||
}
|
||||
const errors: string[] = []
|
||||
for (const worktreeId of worktreeIds) {
|
||||
try {
|
||||
// Why: sleep mirrors removeWorktree's shutdown sequence — browsers first
|
||||
// so destroyPersistentWebview unregisters the Chromium guests before any
|
||||
// other teardown runs, terminals second so the PTY kill uses the same
|
||||
// ordering on both paths. Without the browser thunk here, sleep leaks
|
||||
// browserPagesByWorkspace entries and live webviews for the slept worktree.
|
||||
await shutdownWorktreeBrowsers(worktreeId)
|
||||
} catch (err) {
|
||||
if (worktreeId === activeWorktreeId) {
|
||||
releaseActiveSleepPtyExitSuppressions(preSuppressedActivePtyIds)
|
||||
try {
|
||||
for (const worktreeId of worktreeIds) {
|
||||
try {
|
||||
// Why: sleep mirrors removeWorktree's shutdown sequence — browsers first
|
||||
// so destroyPersistentWebview unregisters the Chromium guests before any
|
||||
// other teardown runs, terminals second so the PTY kill uses the same
|
||||
// ordering on both paths. Without the browser thunk here, sleep leaks
|
||||
// browserPagesByWorkspace entries and live webviews for the slept worktree.
|
||||
await shutdownWorktreeBrowsers(worktreeId)
|
||||
} catch (err) {
|
||||
errors.push(err instanceof Error ? err.message : String(err))
|
||||
continue
|
||||
}
|
||||
try {
|
||||
// Why: sleep is reversible — the tab record stays in tabsByWorktree, the
|
||||
// layout stays in terminalLayoutsByTabId, only the live PTY processes are
|
||||
// released. keepIdentifiers preserves tab.ptyId / ptyIdsByLeafId /
|
||||
// lastKnownRelayPtyIdByTabId so wake re-spawns against the same on-disk
|
||||
// history dir (local) or relay session id (SSH); it also captures
|
||||
// serializer buffers into buffersByLeafId for SSH wake to reseed
|
||||
// scrollback. See DESIGN_DOC_TERMINAL_HISTORY_FIX_V2.md §3.3.c.
|
||||
await shutdownWorktreeTerminals(worktreeId, { keepIdentifiers: true })
|
||||
} catch (err) {
|
||||
errors.push(err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
errors.push(err instanceof Error ? err.message : String(err))
|
||||
continue
|
||||
}
|
||||
try {
|
||||
// Why: sleep is reversible — the tab record stays in tabsByWorktree, the
|
||||
// layout stays in terminalLayoutsByTabId, only the live PTY processes are
|
||||
// released. keepIdentifiers preserves tab.ptyId / ptyIdsByLeafId /
|
||||
// lastKnownRelayPtyIdByTabId so wake re-spawns against the same on-disk
|
||||
// history dir (local) or relay session id (SSH); it also captures
|
||||
// serializer buffers into buffersByLeafId for SSH wake to reseed
|
||||
// scrollback. See DESIGN_DOC_TERMINAL_HISTORY_FIX_V2.md §3.3.c.
|
||||
await shutdownWorktreeTerminals(worktreeId, { keepIdentifiers: true })
|
||||
} catch (err) {
|
||||
errors.push(err instanceof Error ? err.message : String(err))
|
||||
} finally {
|
||||
if (activeSleepIntentWorktreeId) {
|
||||
clearWorktreeSleepIntent(activeSleepIntentWorktreeId)
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { useCallback, useLayoutEffect, useMemo, type MutableRefObject, type RefObject } from 'react'
|
||||
import type { Virtualizer } from '@tanstack/react-virtual'
|
||||
|
||||
export type VirtualizedScrollAnchor = { key: string; offset: number } | null
|
||||
export type VirtualizedScrollAnchor = {
|
||||
fallbackKeys?: readonly string[]
|
||||
key: string
|
||||
offset: number
|
||||
} | null
|
||||
export const VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT = 'orca-record-virtualized-scroll-anchor'
|
||||
|
||||
type UseVirtualizedScrollAnchorOptions<
|
||||
TRow,
|
||||
@@ -9,7 +14,9 @@ type UseVirtualizedScrollAnchorOptions<
|
||||
TItemElement extends Element
|
||||
> = {
|
||||
anchorRef: MutableRefObject<VirtualizedScrollAnchor>
|
||||
getItemElementKey?: (element: TItemElement) => string | null
|
||||
getRowKey: (row: TRow) => string
|
||||
itemElementSelector?: string
|
||||
rows: readonly TRow[]
|
||||
scrollElementRef: RefObject<TScrollElement | null>
|
||||
scrollOffsetRef: MutableRefObject<number>
|
||||
@@ -31,7 +38,9 @@ export function useVirtualizedScrollAnchor<
|
||||
TItemElement extends Element
|
||||
>({
|
||||
anchorRef,
|
||||
getItemElementKey,
|
||||
getRowKey,
|
||||
itemElementSelector,
|
||||
rows,
|
||||
scrollElementRef,
|
||||
scrollOffsetRef,
|
||||
@@ -46,20 +55,75 @@ export function useVirtualizedScrollAnchor<
|
||||
return indexByKey
|
||||
}, [getRowKey, rows])
|
||||
|
||||
const findDomAnchor = useCallback(
|
||||
(scrollElement: TScrollElement) => {
|
||||
if (!itemElementSelector || !getItemElementKey) {
|
||||
return null
|
||||
}
|
||||
const scrollRect = scrollElement.getBoundingClientRect()
|
||||
type DomAnchorItem = { element: TItemElement; key: string; rect: DOMRect }
|
||||
const visibleItems = Array.from(
|
||||
scrollElement.querySelectorAll<TItemElement>(itemElementSelector)
|
||||
)
|
||||
.map((element) => {
|
||||
const key = getItemElementKey(element)
|
||||
if (!key || !rowIndexByKey.has(key) || !element.isConnected) {
|
||||
return null
|
||||
}
|
||||
const rect = element.getBoundingClientRect()
|
||||
if (rect.height <= 0 || rect.bottom <= scrollRect.top || rect.top >= scrollRect.bottom) {
|
||||
return null
|
||||
}
|
||||
return { element, key, rect }
|
||||
})
|
||||
.filter((item): item is DomAnchorItem => item != null)
|
||||
.sort((a, b) => a.rect.top - b.rect.top)
|
||||
|
||||
const [firstVisible] = visibleItems
|
||||
if (!firstVisible) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
fallbackKeys: visibleItems.slice(1).map((item) => item.key),
|
||||
key: firstVisible.key,
|
||||
offset: Math.min(
|
||||
firstVisible.rect.height,
|
||||
Math.max(0, scrollRect.top - firstVisible.rect.top)
|
||||
)
|
||||
}
|
||||
},
|
||||
[getItemElementKey, itemElementSelector, rowIndexByKey]
|
||||
)
|
||||
|
||||
const recordScrollAnchor = useCallback(
|
||||
(scrollTop: number) => {
|
||||
const firstVisible = virtualizer.getVirtualItems().find((item) => item.end > scrollTop)
|
||||
const scrollElement = scrollElementRef.current
|
||||
if (scrollElement) {
|
||||
const domAnchor = findDomAnchor(scrollElement)
|
||||
if (domAnchor) {
|
||||
anchorRef.current = domAnchor
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const virtualItems = virtualizer.getVirtualItems()
|
||||
const firstVisible = virtualItems.find((item) => item.end > scrollTop)
|
||||
const row = firstVisible ? rows[firstVisible.index] : undefined
|
||||
if (!firstVisible || !row) {
|
||||
anchorRef.current = null
|
||||
return
|
||||
}
|
||||
anchorRef.current = {
|
||||
fallbackKeys: virtualItems
|
||||
.slice(virtualItems.indexOf(firstVisible) + 1)
|
||||
.map((item) => rows[item.index])
|
||||
.filter((row): row is TRow => row != null)
|
||||
.map(getRowKey),
|
||||
key: getRowKey(row),
|
||||
offset: Math.max(0, scrollTop - firstVisible.start)
|
||||
}
|
||||
},
|
||||
[anchorRef, getRowKey, rows, virtualizer]
|
||||
[anchorRef, findDomAnchor, getRowKey, rows, scrollElementRef, virtualizer]
|
||||
)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -98,11 +162,17 @@ export function useVirtualizedScrollAnchor<
|
||||
scrollOffsetRef.current = el.scrollTop
|
||||
recordScrollAnchor(el.scrollTop)
|
||||
}
|
||||
const recordCurrentAnchor = (): void => {
|
||||
scrollOffsetRef.current = el.scrollTop
|
||||
recordScrollAnchor(el.scrollTop)
|
||||
}
|
||||
|
||||
el.addEventListener('scroll', onScroll, { passive: true })
|
||||
el.addEventListener(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, recordCurrentAnchor)
|
||||
return () => {
|
||||
scrollOffsetRef.current = el.scrollTop
|
||||
recordScrollAnchor(el.scrollTop)
|
||||
el.removeEventListener(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, recordCurrentAnchor)
|
||||
el.removeEventListener('scroll', onScroll)
|
||||
}
|
||||
}, [recordScrollAnchor, scrollElementRef, scrollOffsetRef])
|
||||
@@ -114,10 +184,40 @@ export function useVirtualizedScrollAnchor<
|
||||
return
|
||||
}
|
||||
|
||||
const index = rowIndexByKey.get(anchor.key)
|
||||
const resolvedKey = rowIndexByKey.has(anchor.key)
|
||||
? anchor.key
|
||||
: anchor.fallbackKeys?.find((key) => rowIndexByKey.has(key))
|
||||
if (!resolvedKey) {
|
||||
return
|
||||
}
|
||||
const index = rowIndexByKey.get(resolvedKey)
|
||||
if (index === undefined) {
|
||||
return
|
||||
}
|
||||
const offset = resolvedKey === anchor.key ? anchor.offset : 0
|
||||
|
||||
const restoreFromDomElement = (): boolean => {
|
||||
if (!itemElementSelector || !getItemElementKey) {
|
||||
return false
|
||||
}
|
||||
const element =
|
||||
Array.from(el.querySelectorAll<TItemElement>(itemElementSelector)).find(
|
||||
(candidate) => getItemElementKey(candidate) === resolvedKey && candidate.isConnected
|
||||
) ?? null
|
||||
if (!element) {
|
||||
return false
|
||||
}
|
||||
const scrollRect = el.getBoundingClientRect()
|
||||
const rect = element.getBoundingClientRect()
|
||||
const desiredTop = scrollRect.top - offset
|
||||
const delta = rect.top - desiredTop
|
||||
if (Math.abs(delta) > 1) {
|
||||
el.scrollTop += delta
|
||||
}
|
||||
scrollOffsetRef.current = el.scrollTop
|
||||
recordScrollAnchor(el.scrollTop)
|
||||
return true
|
||||
}
|
||||
|
||||
const restoreFromMeasuredItem = (): boolean => {
|
||||
const item = virtualizer.getVirtualItems().find((candidate) => candidate.index === index)
|
||||
@@ -125,7 +225,7 @@ export function useVirtualizedScrollAnchor<
|
||||
return false
|
||||
}
|
||||
const maxScrollTop = Math.max(0, el.scrollHeight - el.clientHeight)
|
||||
const nextScrollTop = Math.min(maxScrollTop, Math.max(0, item.start + anchor.offset))
|
||||
const nextScrollTop = Math.min(maxScrollTop, Math.max(0, item.start + offset))
|
||||
if (Math.abs(el.scrollTop - nextScrollTop) > 1) {
|
||||
el.scrollTop = nextScrollTop
|
||||
}
|
||||
@@ -134,7 +234,11 @@ export function useVirtualizedScrollAnchor<
|
||||
return true
|
||||
}
|
||||
|
||||
if (restoreFromMeasuredItem()) {
|
||||
if (restoreFromDomElement()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!itemElementSelector && restoreFromMeasuredItem()) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -143,11 +247,15 @@ export function useVirtualizedScrollAnchor<
|
||||
// TanStack Virtual has mounted and measured that row.
|
||||
virtualizer.scrollToIndex(index, { align: 'start' })
|
||||
const frameId = window.requestAnimationFrame(() => {
|
||||
restoreFromMeasuredItem()
|
||||
if (!restoreFromDomElement()) {
|
||||
restoreFromMeasuredItem()
|
||||
}
|
||||
})
|
||||
return () => window.cancelAnimationFrame(frameId)
|
||||
}, [
|
||||
anchorRef,
|
||||
getItemElementKey,
|
||||
itemElementSelector,
|
||||
recordScrollAnchor,
|
||||
rowIndexByKey,
|
||||
scrollElementRef,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
const sleepingWorktreeIds = new Set<string>()
|
||||
|
||||
export function markWorktreeSleepIntent(worktreeId: string): void {
|
||||
sleepingWorktreeIds.add(worktreeId)
|
||||
}
|
||||
|
||||
export function clearWorktreeSleepIntent(worktreeId: string): void {
|
||||
sleepingWorktreeIds.delete(worktreeId)
|
||||
}
|
||||
|
||||
export function hasWorktreeSleepIntent(worktreeId: string | null): boolean {
|
||||
return worktreeId !== null && sleepingWorktreeIds.has(worktreeId)
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import { normalizeTerminalLayoutSnapshot } from '@/components/terminal-pane/term
|
||||
import { shutdownBufferCaptures } from '@/components/terminal-pane/shutdown-buffer-captures'
|
||||
import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
|
||||
import { createBrowserUuid } from '@/lib/browser-uuid'
|
||||
import { hasWorktreeSleepIntent } from '@/lib/worktree-sleep-intent'
|
||||
|
||||
function getNextTerminalOrdinal(tabs: TerminalTab[]): number {
|
||||
const usedOrdinals = new Set<number>()
|
||||
@@ -1084,7 +1085,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
// Bump meaningful activity when a PTY exits, but skip if this exit
|
||||
// was triggered by an intentional shutdown (suppressed exits) OR by a
|
||||
// click-driven pane unmount (pendingActivationSpawn).
|
||||
if (worktreeId && !wasActivationSpawn && !(ptyId && get().suppressedPtyExitIds[ptyId])) {
|
||||
if (
|
||||
worktreeId &&
|
||||
!wasActivationSpawn &&
|
||||
!hasWorktreeSleepIntent(worktreeId) &&
|
||||
!(ptyId && get().suppressedPtyExitIds[ptyId])
|
||||
) {
|
||||
get().bumpWorktreeActivity(worktreeId)
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user