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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas): fit view into the largest chrome-free rectangle
Dakac46ad799503
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex ecb52965e..a223f94e6 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -25,6 +25,7 @@ import {disposeTerminalOnUnmount,disposeParkedTerminal} from '../nodes/TerminalNode'+import { solveFitPadding } from './fit-view'import { SshReconnector } from '../lib/sshReconnect'import { terminalKey } from '../terminal/terminal-config'import { StickyNode } from '../nodes/StickyNode'@@ -330,6 +331,7 @@ const ropeEdge = (id: string, source: string, target: string, color: string): EdmarkerEnd: { type: MarkerType.ArrowClosed, color, width: 14, height: 14 }})+const minimapNodeColor = (n: Node): string =>(n.data as { color?: string })?.color ?? '#0a84ff'@@ -679,8 +681,31 @@ export function Canvas() {*/const hasPeersRef = useRef(false)const [, bumpHist] = useState(0)- const { setViewport, getViewport, fitView, zoomIn, zoomOut, screenToFlowPosition, setCenter, getZoom } =- useReactFlow()+ const {+ setViewport,+ getViewport,+ fitView,+ zoomIn,+ zoomOut,+ screenToFlowPosition,+ setCenter,+ getZoom,+ getNodes,+ getNodesBounds+ } = useReactFlow()++ // Single "fit everything" path for every fit-view entry point (dock button, the built-in+ // Controls button, the ⌘K palette and the context menu) so they behave identically and there's+ // one place to tune. Solved per click against the CURRENT chrome layout and the CURRENT content+ // shape, so hiding the minimap or fitting a narrow column reclaims that space instead of paying+ // a fixed toll for panels the content never reaches.+ const fitAll = useCallback(() => {+ const wrap = flowWrapRef.current+ const bounds = getNodesBounds(getNodes())+ const padding = wrap ? solveFitPadding(wrap, bounds.width, bounds.height) : null+ // Nothing to fit, or chrome swallowing the viewport: let fitView use its own framing.+ void fitView({ duration: 300, padding: padding ?? 0.1 })+ }, [fitView, getNodes, getNodesBounds])const activeProjectId = useProjects((s) => s.activeProjectId)// The ACTIVE session + its presence — what the canvas-sync publisher and onMutation subscriber@@ -3997,7 +4022,7 @@ export function Canvas() {{ type: 'separator' },// Canvas actions.{ label: 'Select all', icon: <IconSelectAll />, onClick: selectAll },- { label: 'Fit view', icon: <IconFit />, onClick: () => fitView({ padding: 0.2, duration: 300 }) }+ { label: 'Fit view', icon: <IconFit />, onClick: fitAll }]})},@@ -5712,7 +5737,7 @@ export function Canvas() {icon: <IconRemote />,run: () => void connectRemote()},- { id: 'fit', label: 'Fit view', icon: <IconFit />, run: () => fitView({ padding: 0.2, duration: 300 }) },+ { id: 'fit', label: 'Fit view', icon: <IconFit />, run: fitAll },{ id: 'save', label: 'Save', icon: <IconSave />, run: () => void persist() }]const store = useProjects.getState()@@ -6122,7 +6147,7 @@ export function Canvas() {size={2.5}color="#4a4a4a"/>- <Controls showInteractive={false} position="bottom-left">+ <Controls showInteractive={false} position="bottom-left" onFitView={fitAll}><ControlButtonclassName={`canvas-lock-btn${canvasLocked ? ' locked' : ''}`}title={canvasLocked ? 'Unlock view (pan/zoom)' : 'Lock view (pan/zoom) — nodes stay movable'}@@ -6510,7 +6535,7 @@ export function Canvas() {onAddRemote={() => openRemotePicker({ x: window.innerWidth / 2, y: window.innerHeight / 2 })}onConnectRemote={() => void connectRemote()}onSave={persist}- onFitView={() => fitView({ padding: 0.2, duration: 300 })}+ onFitView={fitAll}onZoomIn={() => zoomIn({ duration: 150 })}onZoomOut={() => zoomOut({ duration: 150 })}onDictate={toggleDictation}diff --git a/src/renderer/canvas/fit-view.test.ts b/src/renderer/canvas/fit-view.test.tsnew file mode 100644index 000000000..071289921--- /dev/null+++ b/src/renderer/canvas/fit-view.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from 'vitest'+import { largestFreeRect, rectToPadding, rectsOverlap, type FitRect } from './fit-view'++/**+ * Geometry measured from a real 1264x722 canvas (see docs/superpowers/specs) — the chrome rects+ * are the actual dock / minimap / controls positions, already inflated by the gap.+ */+const VIEWPORT: FitRect = { left: 12, top: 56, right: 1252, bottom: 754 }+const DOCK: FitRect = { left: 407, top: 678, right: 858, bottom: 756 }+const MINIMAP: FitRect = { left: 1035, top: 587, right: 1261, bottom: 763 }+const CONTROLS: FitRect = { left: 3, top: 635, right: 53, bottom: 763 }+const CHROME = [DOCK, MINIMAP, CONTROLS]++const w = (r: FitRect): number => r.right - r.left+const h = (r: FitRect): number => r.bottom - r.top+const zoomOf = (r: FitRect, cw: number, ch: number): number => Math.min(w(r) / cw, h(r) / ch)++describe('largestFreeRect', () => {+ it('never returns a rect that overlaps any chrome', () => {+ for (const [cw, ch] of [+ [2000, 600],+ [300, 2000],+ [1000, 1000],+ [50, 50],+ [5000, 20]+ ]) {+ const r = largestFreeRect(VIEWPORT, CHROME, cw, ch)+ expect(r, `content ${cw}x${ch}`).not.toBeNull()+ for (const c of CHROME) expect(rectsOverlap(r!, c), `content ${cw}x${ch}`).toBe(false)+ }+ })++ it('stays inside the viewport', () => {+ const r = largestFreeRect(VIEWPORT, CHROME, 1000, 1000)!+ expect(r.left).toBeGreaterThanOrEqual(VIEWPORT.left)+ expect(r.top).toBeGreaterThanOrEqual(VIEWPORT.top)+ expect(r.right).toBeLessThanOrEqual(VIEWPORT.right)+ expect(r.bottom).toBeLessThanOrEqual(VIEWPORT.bottom)+ })++ it('does not charge narrow content for the bottom-right minimap', () => {+ // The regression this whole module exists for: a tall narrow column sits well clear of the+ // minimap's x-range, so it must be allowed to run past the minimap's top edge.+ const r = largestFreeRect(VIEWPORT, CHROME, 300, 2000)!+ expect(r.bottom).toBeGreaterThan(MINIMAP.top)+ expect(r.right).toBeLessThanOrEqual(MINIMAP.left)+ })++ it('beats a naive "reserve the deepest bottom intrusion" strategy for narrow content', () => {+ const naiveBottom = Math.min(DOCK.top, MINIMAP.top, CONTROLS.top)+ const naive: FitRect = { ...VIEWPORT, bottom: naiveBottom }+ const solved = largestFreeRect(VIEWPORT, CHROME, 300, 2000)!+ expect(zoomOf(solved, 300, 2000)).toBeGreaterThan(zoomOf(naive, 300, 2000))+ })++ it('uses the full width for wide content, stopping above the bottom chrome', () => {+ const r = largestFreeRect(VIEWPORT, CHROME, 4000, 500)!+ // Wide content genuinely spans the minimap's and controls' x-range, so it must clear them.+ expect(r.bottom).toBeLessThanOrEqual(Math.min(MINIMAP.top, CONTROLS.top))+ expect(w(r)).toBeGreaterThan(1000)+ })++ it('returns the whole viewport when nothing is in the way', () => {+ const r = largestFreeRect(VIEWPORT, [], 1000, 1000)!+ expect(r).toEqual(VIEWPORT)+ })++ it('reclaims space when chrome is hidden (fewer obstacles ⇒ at least as much zoom)', () => {+ const withAll = largestFreeRect(VIEWPORT, CHROME, 1200, 700)!+ const withoutMinimap = largestFreeRect(VIEWPORT, [DOCK, CONTROLS], 1200, 700)!+ expect(zoomOf(withoutMinimap, 1200, 700)).toBeGreaterThanOrEqual(zoomOf(withAll, 1200, 700))+ })++ it('is exhaustive: no sampled free rect beats the chosen one', () => {+ const cw = 900+ const ch = 800+ const best = largestFreeRect(VIEWPORT, CHROME, cw, ch)!+ const bestZoom = zoomOf(best, cw, ch)+ // Brute-force a grid of candidate rects; none may afford more zoom than the solver's. Track+ // the max and assert once — an expect() per candidate would be millions of calls.+ const step = 25+ let brute = 0+ for (let l = VIEWPORT.left; l < VIEWPORT.right; l += step) {+ for (let r2 = l + step; r2 <= VIEWPORT.right; r2 += step) {+ for (let t = VIEWPORT.top; t < VIEWPORT.bottom; t += step) {+ for (let b = t + step; b <= VIEWPORT.bottom; b += step) {+ const cand: FitRect = { left: l, right: r2, top: t, bottom: b }+ if (CHROME.some((c) => rectsOverlap(c, cand))) continue+ const z = zoomOf(cand, cw, ch)+ if (z > brute) brute = z+ }+ }+ }+ }+ expect(brute).toBeLessThanOrEqual(bestZoom + 1e-6)+ })++ it('guards degenerate content', () => {+ expect(largestFreeRect(VIEWPORT, CHROME, 0, 100)).toBeNull()+ expect(largestFreeRect(VIEWPORT, CHROME, 100, 0)).toBeNull()+ })+})++describe('rectToPadding', () => {+ it('converts a chosen rect into per-side px insets', () => {+ const outer: FitRect = { left: 0, top: 0, right: 1000, bottom: 800 }+ expect(rectToPadding(outer, { left: 20, top: 30, right: 900, bottom: 700 })).toEqual({+ left: '20px',+ top: '30px',+ right: '100px',+ bottom: '100px'+ })+ })++ it('never emits negative padding', () => {+ const outer: FitRect = { left: 0, top: 0, right: 100, bottom: 100 }+ expect(rectToPadding(outer, { left: -10, top: -10, right: 110, bottom: 110 })).toEqual({+ left: '0px',+ top: '0px',+ right: '0px',+ bottom: '0px'+ })+ })+})diff --git a/src/renderer/canvas/fit-view.ts b/src/renderer/canvas/fit-view.tsnew file mode 100644index 000000000..92f4467b5--- /dev/null+++ b/src/renderer/canvas/fit-view.ts@@ -0,0 +1,160 @@+/**+ * Fit-view geometry: place the canvas content in the largest chrome-free rectangle.+ *+ * The dock, minimap, controls, sidebars and banners all paint OVER the flow, so a plain `fitView`+ * tucks nodes underneath them. Reserving a fixed margin per edge is too blunt — it taxes content+ * that never reaches the offending panel (narrow content paying for a bottom-RIGHT minimap).+ *+ * Instead every visible overlay becomes an obstacle rect, and we pick the free rectangle that lets+ * the content — at its own aspect ratio — reach the highest zoom. xyflow's directional padding is+ * exactly "fit inside the viewport minus these insets", so the winning rect maps straight onto it.+ *+ * Kept DOM-light and free of React so the geometry can be unit-tested on its own.+ */++/** Chrome that floats over the canvas. New chrome can opt in via `data-canvas-chrome` instead of+ * being added here. */+export const CANVAS_CHROME_SELECTOR = [+ '[data-canvas-chrome]',+ '.dock',+ '.minimap',+ '.react-flow__controls',+ '.usage-indicator',+ '.controls-cluster',+ '.sessions-sidebar',+ '.sessions-icon-cluster',+ '.top-banners',+ '.presence-prompt',+ '.dictation',+ '.update-card'+].join(',')++/** Breathing room kept between the content and both the chrome and the window edge. */+export const FIT_VIEW_GAP = 12++export type FitRect = { left: number; top: number; right: number; bottom: number }++export const rectsOverlap = (a: FitRect, b: FitRect): boolean =>+ a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom++const width = (r: FitRect): number => r.right - r.left+const height = (r: FitRect): number => r.bottom - r.top++/**+ * Largest chrome-free rectangle inside `viewport`, chosen to maximize the zoom a+ * `contentW × contentH` box can reach inside it (ties → bigger area, then closer to centre).+ *+ * Every maximal empty rectangle has each edge either on the viewport border or flush against an+ * obstacle edge, so enumerating obstacle/viewport edge pairs is exhaustive: this returns the true+ * optimum, not an approximation. ~8 overlays → ~18 boundaries per axis, comfortably under a ms.+ *+ * Returns null only if no non-degenerate free rectangle exists.+ */+export function largestFreeRect(+ viewport: FitRect,+ obstacles: FitRect[],+ contentW: number,+ contentH: number+): FitRect | null {+ if (contentW <= 0 || contentH <= 0) return null+ const axis = (lo: number, hi: number, edges: number[]): number[] =>+ [...new Set([lo, hi, ...edges.filter((v) => v > lo && v < hi)])].sort((a, b) => a - b)+ const xs = axis(viewport.left, viewport.right, obstacles.flatMap((o) => [o.left, o.right]))+ const ys = axis(viewport.top, viewport.bottom, obstacles.flatMap((o) => [o.top, o.bottom]))++ const vcx = (viewport.left + viewport.right) / 2+ const vcy = (viewport.top + viewport.bottom) / 2+ let best: FitRect | null = null+ let bestZoom = -1+ let bestArea = -1+ let bestOffCentre = Infinity++ for (let i = 0; i < xs.length - 1; i++) {+ for (let j = i + 1; j < xs.length; j++) {+ for (let k = 0; k < ys.length - 1; k++) {+ for (let l = k + 1; l < ys.length; l++) {+ const r: FitRect = { left: xs[i], right: xs[j], top: ys[k], bottom: ys[l] }+ const w = width(r)+ const h = height(r)+ if (w < 1 || h < 1) continue+ if (obstacles.some((o) => rectsOverlap(o, r))) continue+ // Zoom this rect affords the content. Ties are common once the caller's maxZoom clamps,+ // so fall back to area and then centredness to keep results stable and pleasant.+ const zoom = Math.min(w / contentW, h / contentH)+ const area = w * h+ const offCentre =+ Math.abs((r.left + r.right) / 2 - vcx) + Math.abs((r.top + r.bottom) / 2 - vcy)+ const better =+ zoom > bestZoom + 1e-6 ||+ (zoom > bestZoom - 1e-6 &&+ (area > bestArea + 1e-6 || (area > bestArea - 1e-6 && offCentre < bestOffCentre)))+ if (!better) continue+ best = r+ bestZoom = zoom+ bestArea = area+ bestOffCentre = offCentre+ }+ }+ }+ }+ return best+}++/** Inflate a measured chrome rect by the gap so content keeps its distance. */+export const inflate = (r: FitRect, by: number): FitRect => ({+ left: r.left - by,+ top: r.top - by,+ right: r.right + by,+ bottom: r.bottom + by+})++/** Visible canvas chrome as obstacle rects, inflated by the gap and limited to the viewport. */+export function chromeObstacles(viewport: FitRect, root: ParentNode = document): FitRect[] {+ return [...root.querySelectorAll(CANVAS_CHROME_SELECTOR)]+ .map((el) => el.getBoundingClientRect())+ // Hidden/collapsed chrome measures 0 — it must not reserve any space.+ .filter((r) => r.width > 0 && r.height > 0)+ .map((r) => inflate({ left: r.left, top: r.top, right: r.right, bottom: r.bottom }, FIT_VIEW_GAP))+ .filter((r) => rectsOverlap(r, viewport))+}++/** Padding accepted by xyflow's `fitView` (px strings per side). */+export type FitPadding = {+ top: `${number}px`+ left: `${number}px`+ right: `${number}px`+ bottom: `${number}px`+}++/** Express a chosen free rect as the directional insets `fitView` expects, relative to `outer`. */+export function rectToPadding(outer: FitRect, rect: FitRect): FitPadding {+ return {+ top: `${Math.max(0, Math.round(rect.top - outer.top))}px`,+ left: `${Math.max(0, Math.round(rect.left - outer.left))}px`,+ right: `${Math.max(0, Math.round(outer.right - rect.right))}px`,+ bottom: `${Math.max(0, Math.round(outer.bottom - rect.bottom))}px`+ }+}++/**+ * Solve the fit-view padding for the current chrome layout and content shape.+ * Returns null when there is nothing sensible to solve, so callers can fall back to plain fitView.+ */+export function solveFitPadding(+ wrap: HTMLElement,+ contentW: number,+ contentH: number+): FitPadding | null {+ if (contentW <= 0 || contentH <= 0) return null+ const v = wrap.getBoundingClientRect()+ const outer: FitRect = { left: v.left, top: v.top, right: v.right, bottom: v.bottom }+ const viewport: FitRect = {+ left: outer.left + FIT_VIEW_GAP,+ top: outer.top + FIT_VIEW_GAP,+ right: outer.right - FIT_VIEW_GAP,+ bottom: outer.bottom - FIT_VIEW_GAP+ }+ if (width(viewport) < 1 || height(viewport) < 1) return null+ const rect = largestFreeRect(viewport, chromeObstacles(viewport), contentW, contentH)+ return rect ? rectToPadding(outer, rect) : null+}