Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat: auto-scroll the tab strip and sessions sidebar while dragging (#1188)

ezwep667de95e2ad4
diff --git a/src/renderer/components/SessionsSidebar.dragScroll.test.tsx b/src/renderer/components/SessionsSidebar.dragScroll.test.tsx
new file mode 100644
index 000000000..5f6aab062
--- /dev/null
+++ b/src/renderer/components/SessionsSidebar.dragScroll.test.tsx
@@ -0,0 +1,109 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { NodeTerminalApi, Project } from '@shared/types'
+import { SessionsSidebar, type SessionsSidebarProps } from './SessionsSidebar'
+import { useProjects } from '../state/projects'
+import { createSession, setActiveSession, SessionProvider, resetSessionsForTest } from '../session/session'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const noop = (): void => {}
+const props: SessionsSidebarProps = {
+ open: true, pinned: true, liveActiveNodes: null, onTogglePin: noop, onClose: noop,
+ onFocusNode: noop, onCloseSession: noop, onRenameSession: noop, onAiNameSession: noop,
+ onRowContextMenu: noop, onProjectContextMenu: noop, onSwitchProject: noop, onAddToProject: noop,
+ onMoveToGroup: noop, onAiNameGroup: noop, onReorder: noop, onReorderGroup: noop,
+ onReorderProject: noop, onReopenProject: noop, onDeleteProject: noop,
+ onReopenClosedSession: noop, onDiscardClosedSession: noop, onOpenClosedTranscript: noop
+}
+const project = (id: string): Project =>
+ ({ id, cwd: `/repo/${id}`, name: id, color: '#fff', nodes: [], viewport: { x: 0, y: 0, zoom: 1 } }) as Project
+
+let root: Root
+let host: HTMLDivElement
+let frames: FrameRequestCallback[]
+let clock = 0
+const flush = (): void => {
+ const due = frames
+ frames = []
+ due.forEach((f) => f((clock += 1000 / 60)))
+}
+const dragEvent = async (el: EventTarget, type: string, clientY = 0): Promise<void> => {
+ const e = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(e, {
+ dataTransfer: { value: { effectAllowed: '', setData: noop } },
+ clientX: { value: 100 },
+ clientY: { value: clientY }
+ })
+ await act(async () => {
+ el.dispatchEvent(e)
+ })
+}
+
+beforeEach(() => {
+ resetSessionsForTest()
+ frames = []
+ vi.stubGlobal('requestAnimationFrame', (f: FrameRequestCallback) => frames.push(f))
+ vi.stubGlobal('cancelAnimationFrame', () => {
+ frames = []
+ })
+ window.nodeTerminal = { sshFs: {} } as NodeTerminalApi
+ useProjects.setState({ projects: [project('a'), project('b'), project('c')], activeProjectId: 'a' })
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ resetSessionsForTest()
+ vi.unstubAllGlobals()
+})
+
+it('scrolls the sidebar body while a project is dragged below it, and stops when the drag ends', async () => {
+ const api = { git: { status: vi.fn(async () => ({ hasRepo: false })) }, fs: {} } as unknown as NodeTerminalApi
+ const session = createSession('local', api, 'local')
+ setActiveSession(session.id)
+ await act(async () => {
+ root.render(
+ <SessionProvider session={session}>
+ <SessionsSidebar {...props} />
+ </SessionProvider>
+ )
+ })
+ const body = host.querySelector<HTMLElement>('.sessions-sidebar__body')!
+ body.getBoundingClientRect = () =>
+ ({ left: 0, right: 300, top: 100, bottom: 500, width: 300, height: 400 }) as DOMRect
+ const head = host.querySelector('.ss-group__head')!
+ await dragEvent(head, 'dragstart')
+ await dragEvent(document.body, 'dragover', 900)
+ flush()
+ flush()
+ expect(body.scrollTop).toBeGreaterThan(0)
+ const afterDrag = body.scrollTop
+ await dragEvent(head, 'dragend')
+ flush()
+ expect(body.scrollTop).toBe(afterDrag)
+})
+
+it('stops scrolling when the sidebar closes mid-drag', async () => {
+ const api = { git: { status: vi.fn(async () => ({ hasRepo: false })) }, fs: {} } as unknown as NodeTerminalApi
+ const session = createSession('local', api, 'local')
+ setActiveSession(session.id)
+ const render = (open: boolean): Promise<void> =>
+ act(async () => {
+ root.render(
+ <SessionProvider session={session}>
+ <SessionsSidebar {...props} open={open} />
+ </SessionProvider>
+ )
+ })
+ await render(true)
+ const head = host.querySelector('.ss-group__head')!
+ await dragEvent(head, 'dragstart')
+ expect(frames.length).toBeGreaterThan(0)
+ await render(false)
+ expect(frames).toHaveLength(0)
+})
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index 58ae44654..d3e1c93b4 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
buildSessionList,
buildStatusList,
@@ -30,6 +30,7 @@ import { useSettings } from '../state/settings'
import { useAgentStatus } from '../state/agentStatus'
import { useSessionNaming } from '../state/sessionNaming'
import { ProjectBranch } from './ProjectBranch'
+import { useDragAutoScroll } from '../lib/dragAutoScroll'
const HISTORY_COLLAPSE_KEY = 'history'
@@ -164,6 +165,11 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
// before ('' = end of the list). Distinct from the session drag above — one at a time.
const [dragProj, setDragProj] = useState<string | null>(null)
const [dropProj, setDropProj] = useState<string | null>(null)
+ // The body scrolls itself while a project or session is dragged near (or past) its top/bottom.
+ const bodyRef = useRef<HTMLDivElement>(null)
+ // Gated on `open` too: closing the sidebar mid-drag removes the body without unmounting this
+ // component, and the detached drag source's dragend may never reach the window.
+ useDragAutoScroll(bodyRef, 'y', open && (dragProj !== null || drag !== null))
// Inline group rename: the group node id being edited + its draft title.
const [editGroup, setEditGroup] = useState<{ id: string; draft: string } | null>(null)
@@ -590,6 +596,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
<div
className="sessions-sidebar__body"
+ ref={bodyRef}
// The body's empty space is the project drag's "drop at the end" zone (headers
// stopPropagation their own drops).
onDragOver={(e) => {
diff --git a/src/renderer/components/TabBar.test.tsx b/src/renderer/components/TabBar.test.tsx
index ac00c7c01..a0a1adb6d 100644
--- a/src/renderer/components/TabBar.test.tsx
+++ b/src/renderer/components/TabBar.test.tsx
@@ -277,6 +277,38 @@ describe('TabBar drag-reorder', () => {
expect(host.querySelector('.tab__dropline')).not.toBeNull()
})
+ it('scrolls the strip while a tab is dragged past its edge, and stops when the drag ends', async () => {
+ let frames: FrameRequestCallback[] = []
+ let clock = 0
+ vi.stubGlobal('requestAnimationFrame', (f: FrameRequestCallback) => frames.push(f))
+ vi.stubGlobal('cancelAnimationFrame', () => {
+ frames = []
+ })
+ const flush = (): void => {
+ const due = frames
+ frames = []
+ due.forEach((f) => f((clock += 1000 / 60)))
+ }
+ const strip = host.querySelector<HTMLElement>('.tabbar__tabs')!
+ strip.getBoundingClientRect = () =>
+ ({ left: 200, right: 600, top: 0, bottom: 40, width: 400, height: 40 }) as DOMRect
+ strip.scrollLeft = 500
+ const [, , third] = tabs()
+ await drag(third, 'dragstart')
+ // Far left of the strip and below it — over the brand / canvas, not the strip itself.
+ const over = new Event('dragover', { bubbles: true, cancelable: true })
+ Object.defineProperties(over, { clientX: { value: 20 }, clientY: { value: 300 } })
+ document.body.dispatchEvent(over)
+ flush()
+ flush()
+ expect(strip.scrollLeft).toBeLessThan(500)
+ const afterDrag = strip.scrollLeft
+ await drag(third, 'dragend')
+ flush()
+ expect(strip.scrollLeft).toBe(afterDrag)
+ vi.unstubAllGlobals()
+ })
+
it('drops at the end when released on the strip itself', async () => {
const [first] = tabs()
await drag(first, 'dragstart')
diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsx
index ebdcc422b..c49d3b03c 100644
--- a/src/renderer/components/TabBar.tsx
+++ b/src/renderer/components/TabBar.tsx
@@ -17,6 +17,7 @@ import { runPendingUpdate, usePendingUpdate } from '../state/pendingUpdate'
import { ProjectGlyph } from './ProjectGlyph'
import { useTooltip } from './Tooltip'
import { projectTabTooltip } from '../lib/projectTabTooltip'
+import { useDragAutoScroll } from '../lib/dragAutoScroll'
import {
ALL_PERMISSION_MODES,
PERMISSION_MODE_LABELS,
@@ -232,6 +233,9 @@ export function TabBar({
// The strip scrolls without a visible scrollbar (see .tabbar__tabs), so keep it navigable:
// a plain mouse wheel scrolls it horizontally, and the active tab is brought into view.
const tabsRef = useRef<HTMLDivElement>(null)
+ // While a tab is dragged the strip scrolls itself near (or past) its left/right edge, so a tab
+ // can travel from the far end to the front in one drag.
+ useDragAutoScroll(tabsRef, 'x', dragId !== null)
const pendingUpdate = usePendingUpdate((s) => s.pending)
useEffect(() => {
tabsRef.current
diff --git a/src/renderer/lib/dragAutoScroll.test.ts b/src/renderer/lib/dragAutoScroll.test.ts
new file mode 100644
index 000000000..da2dbe667
--- /dev/null
+++ b/src/renderer/lib/dragAutoScroll.test.ts
@@ -0,0 +1,149 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ EDGE_BELT_PX,
+ MAX_SCROLL_STEP_PX,
+ edgeScrollStep,
+ startDragAutoScroll
+} from './dragAutoScroll'
+
+describe('edgeScrollStep', () => {
+ // A 400px scroller spanning 100..500 on its axis.
+ const step = (pos: number): number => edgeScrollStep(pos, 100, 500)
+
+ it('does not scroll while the pointer is in the middle', () => {
+ expect(step(300)).toBe(0)
+ expect(step(100 + EDGE_BELT_PX + 1)).toBe(0)
+ expect(step(500 - EDGE_BELT_PX - 1)).toBe(0)
+ })
+
+ it('scrolls back near the start edge and forward near the end edge', () => {
+ expect(step(100 + EDGE_BELT_PX / 2)).toBeLessThan(0)
+ expect(step(500 - EDGE_BELT_PX / 2)).toBeGreaterThan(0)
+ })
+
+ it('keeps scrolling — faster — when the pointer overshoots past the edge', () => {
+ // The point of the feature: you should not have to aim at a thin strip.
+ const atEdge = Math.abs(step(100))
+ const past = Math.abs(step(40))
+ const farPast = Math.abs(step(-400))
+ expect(atEdge).toBeGreaterThan(0)
+ expect(past).toBeGreaterThan(atEdge)
+ expect(farPast).toBe(MAX_SCROLL_STEP_PX)
+ expect(step(5000)).toBe(MAX_SCROLL_STEP_PX)
+ })
+
+ it('narrows the belt on a scroller too small to have a quiet middle otherwise', () => {
+ // 60px scroller: two full belts would cover it entirely.
+ expect(edgeScrollStep(130, 100, 160)).toBe(0)
+ })
+})
+
+describe('startDragAutoScroll', () => {
+ let el: HTMLDivElement
+ let frames: FrameRequestCallback[]
+ let clock = 0
+
+ const flush = (n = 1): void => {
+ for (let i = 0; i < n; i++) {
+ const due = frames
+ frames = []
+ due.forEach((f) => f((clock += 1000 / 60)))
+ }
+ }
+ const dragOver = (clientX: number, clientY: number): void => {
+ const e = new Event('dragover', { bubbles: true, cancelable: true })
+ Object.defineProperties(e, { clientX: { value: clientX }, clientY: { value: clientY } })
+ document.body.dispatchEvent(e)
+ }
+
+ beforeEach(() => {
+ frames = []
+ vi.stubGlobal('requestAnimationFrame', (f: FrameRequestCallback) => frames.push(f))
+ vi.stubGlobal('cancelAnimationFrame', () => {
+ frames = []
+ })
+ el = document.createElement('div')
+ document.body.appendChild(el)
+ el.getBoundingClientRect = () =>
+ ({ left: 200, right: 600, top: 100, bottom: 500, width: 400, height: 400 }) as DOMRect
+ })
+
+ afterEach(() => {
+ el.remove()
+ vi.unstubAllGlobals()
+ })
+
+ it('scrolls a horizontal strip left while the pointer is far left of it, even over another element', () => {
+ el.scrollLeft = 1000
+ const stop = startDragAutoScroll(el, 'x')
+ dragOver(10, 800) // over the brand, below the strip: only the x axis counts
+ flush(3)
+ expect(el.scrollLeft).toBe(1000 - 3 * MAX_SCROLL_STEP_PX)
+ stop()
+ })
+
+ it('scrolls a vertical list down while the pointer is below it', () => {
+ const stop = startDragAutoScroll(el, 'y')
+ dragOver(400, 900)
+ flush(2)
+ expect(el.scrollTop).toBe(2 * MAX_SCROLL_STEP_PX)
+ stop()
+ })
+
+ it('scrolls at the same speed on a 120 Hz display as on a 60 Hz one', () => {
+ el.scrollLeft = 1000
+ const stop = startDragAutoScroll(el, 'x')
+ dragOver(10, 10)
+ // Two 120 Hz frames cover one 60 Hz frame's time: together they move one 60 Hz step.
+ flush(1) // first frame counts as one 60 Hz frame
+ const afterFirst = el.scrollLeft
+ const run = frames
+ frames = []
+ run.forEach((f) => f((clock += 1000 / 120)))
+ const run2 = frames
+ frames = []
+ run2.forEach((f) => f((clock += 1000 / 120)))
+ expect(afterFirst - el.scrollLeft).toBe(MAX_SCROLL_STEP_PX)
+ stop()
+ })
+
+ it('does nothing until the first dragover reports a position', () => {
+ el.scrollLeft = 50
+ const stop = startDragAutoScroll(el, 'x')
+ flush(3)
+ expect(el.scrollLeft).toBe(50)
+ stop()
+ })
+
+ it('ignores a (0, 0) dragover, which Chromium can send at the window boundary', () => {
+ el.scrollLeft = 1000
+ const stop = startDragAutoScroll(el, 'x')
+ dragOver(5000, 300) // overshooting to the right
+ dragOver(0, 0)
+ flush(1)
+ expect(el.scrollLeft).toBe(1000 + MAX_SCROLL_STEP_PX)
+ stop()
+ })
+
+ it('stops by itself once the container is removed from the DOM', () => {
+ const stop = startDragAutoScroll(el, 'x')
+ dragOver(10, 10)
+ el.remove()
+ flush(1)
+ expect(frames).toHaveLength(0)
+ stop()
+ })
+
+ it('stops scrolling and listening once stopped', () => {
+ el.scrollLeft = 1000
+ const stop = startDragAutoScroll(el, 'x')
+ dragOver(10, 10)
+ flush(1)
+ stop()
+ flush(3)
+ dragOver(10, 10)
+ flush(3)
+ expect(el.scrollLeft).toBe(1000 - MAX_SCROLL_STEP_PX)
+ })
+})
diff --git a/src/renderer/lib/dragAutoScroll.ts b/src/renderer/lib/dragAutoScroll.ts
new file mode 100644
index 000000000..b2f6a7142
--- /dev/null
+++ b/src/renderer/lib/dragAutoScroll.ts
@@ -0,0 +1,113 @@
+import { useEffect, type RefObject } from 'react'
+
+// Auto-scroll a scroll container while an HTML5 drag is in flight. Two lists reorder by drag and
+// both scroll: the project tab strip (horizontally, without a visible scrollbar) and the sessions
+// sidebar (vertically). During a native drag the wheel does not reach the page, so with 20–30
+// projects a tab could only travel as far as the strip showed: drop, scroll, drag again.
+//
+// Chromium has a built-in drag autoscroll, but it only reacts inside a thin band along the
+// container's own edge — you have to aim at it. Here the edge band is generous AND everything
+// past the edge counts: dragging over the brand, the +, the canvas or out of the window keeps the
+// list scrolling, faster the further you overshoot. Only the scroll axis is read, so a drag that
+// drifts down onto the canvas while far to the left still scrolls the tab strip left.
+
+export type DragScrollAxis = 'x' | 'y'
+
+/** Width of the band inside each edge where scrolling starts. */
+export const EDGE_BELT_PX = 40
+/** Extra distance past the edge over which the speed ramps up to its maximum. */
+export const OVERSHOOT_RAMP_PX = 120
+export const MIN_SCROLL_STEP_PX = 2
+/** Per 60 Hz frame (~1400 px/s), a 30-tab strip end to end in ~3 s. The loop scales it by the
+ * real frame time, so a 120 Hz display scrolls at the same speed, not twice as fast. */
+export const MAX_SCROLL_STEP_PX = 24
+const FRAME_MS = 1000 / 60
+/** A frame time longer than this (a stalled tab, a debugger pause) counts as this, not as a jump. */
+const MAX_FRAME_MS = 50
+
+function stepFor(depth: number, belt: number): number {
+ const t = Math.min(1, depth / (belt + OVERSHOOT_RAMP_PX))
+ return Math.round(MIN_SCROLL_STEP_PX + (MAX_SCROLL_STEP_PX - MIN_SCROLL_STEP_PX) * t)
+}
+
+/**
+ * Signed scroll step (px per frame) for a pointer at `pos` against a scroller spanning
+ * `[start, end]` on one axis: negative = towards the start, 0 = leave it alone. A pointer before
+ * the start or after the end still scrolls, at a speed that grows with the overshoot.
+ */
+export function edgeScrollStep(pos: number, start: number, end: number): number {
+ // A scroller narrower than two full belts keeps a quiet middle half.
+ const belt = Math.min(EDGE_BELT_PX, Math.max(0, end - start) / 4)
+ const intoStart = start + belt - pos
+ if (intoStart > 0) return -stepFor(intoStart, belt)
+ const intoEnd = pos - (end - belt)
+ if (intoEnd > 0) return stepFor(intoEnd, belt)
+ return 0
+}
+
+/**
+ * Scroll `el` along `axis` from the pointer position every `dragover` reports, anywhere in the
+ * window, until the returned stop function runs (or the drag ends). The last position is kept
+ * while no dragover arrives — a pointer that left the window past the edge keeps scrolling.
+ */
+export function startDragAutoScroll(el: HTMLElement, axis: DragScrollAxis): () => void {
+ let pos: number | null = null
+ let frame = 0
+ let lastTime: number | null = null
+ let stopped = false
+
+ const onDragOver = (e: DragEvent): void => {
+ // Chromium can report (0, 0) for a drag event at the window boundary; taken at face value it
+ // would flip a drag that overshot the right/bottom edge into scrolling the other way.
+ if (e.clientX === 0 && e.clientY === 0) return
+ pos = axis === 'x' ? e.clientX : e.clientY
+ }
+ const tick = (time: number): void => {
+ if (stopped) return
+ const elapsed = lastTime === null ? FRAME_MS : Math.min(MAX_FRAME_MS, Math.max(0, time - lastTime))
+ lastTime = time
+ // The container left the DOM mid-drag (its panel closed): nothing left to scroll.
+ if (!el.isConnected) {
+ stop()
+ return
+ }
+ if (pos !== null) {
+ const r = el.getBoundingClientRect()
+ const perFrame = axis === 'x' ? edgeScrollStep(pos, r.left, r.right) : edgeScrollStep(pos, r.top, r.bottom)
+ const step = Math.round((perFrame * elapsed) / FRAME_MS)
+ if (step !== 0) {
+ if (axis === 'x') el.scrollLeft += step
+ else el.scrollTop += step
+ }
+ }
+ frame = requestAnimationFrame(tick)
+ }
+ const stop = (): void => {
+ if (stopped) return
+ stopped = true
+ cancelAnimationFrame(frame)
+ window.removeEventListener('dragover', onDragOver, true)
+ window.removeEventListener('drop', stop, true)
+ window.removeEventListener('dragend', stop, true)
+ }
+
+ // Capture phase: the per-item handlers stopPropagation, and those positions count too.
+ window.addEventListener('dragover', onDragOver, true)
+ window.addEventListener('drop', stop, true)
+ window.addEventListener('dragend', stop, true)
+ frame = requestAnimationFrame(tick)
+ return stop
+}
+
+/** Runs {@link startDragAutoScroll} on `ref`'s element for as long as `active` is true. */
+export function useDragAutoScroll(
+ ref: RefObject<HTMLElement | null>,
+ axis: DragScrollAxis,
+ active: boolean
+): void {
+ useEffect(() => {
+ const el = ref.current
+ if (!active || !el) return
+ return startDragAutoScroll(el, axis)
+ }, [ref, axis, active])
+}