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
feat(canvas): trackpad wheel routing, image paste/drop, and file copy to the OS pasteboard
Claude Code6e66946e9555
diff --git a/src/main/clipboard-files.test.ts b/src/main/clipboard-files.test.tsnew file mode 100644index 000000000..a81aa10c5--- /dev/null+++ b/src/main/clipboard-files.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from 'vitest'+import {+ FILE_LIST_PASTEBOARD_TYPE,+ fileListPropertyList,+ writeFilesToClipboard,+ type FileClipboardDependencies+} from './clipboard-files'++const dependencies = (overrides: Partial<FileClipboardDependencies> = {}): FileClipboardDependencies => ({+ platform: 'darwin',+ isFile: () => true,+ writeBuffer: vi.fn(),+ ...overrides+})++describe('writeFilesToClipboard', () => {+ it('writes unique existing absolute files as a macOS filename pasteboard list', () => {+ const deps = dependencies()+ expect(writeFilesToClipboard(['/tmp/a & b.png', '/tmp/a & b.png'], deps)).toBe(true)+ expect(deps.writeBuffer).toHaveBeenCalledOnce()+ const [format, buffer] = vi.mocked(deps.writeBuffer).mock.calls[0]+ expect(format).toBe(FILE_LIST_PASTEBOARD_TYPE)+ expect(buffer.toString()).toContain('<string>/tmp/a & b.png</string>')+ expect(buffer.toString().match(/<string>/g)).toHaveLength(1)+ })++ it('rejects unsupported platforms and any selection containing an invalid file', () => {+ expect(writeFilesToClipboard(['/tmp/a'], dependencies({ platform: 'linux' }))).toBe(false)+ expect(writeFilesToClipboard(['/tmp/a'], dependencies({ isFile: () => false }))).toBe(false)+ expect(writeFilesToClipboard(['/tmp/a', 'relative'], dependencies())).toBe(false)+ expect(writeFilesToClipboard('not-an-array', dependencies())).toBe(false)+ })++ it('fails closed when the OS clipboard write fails', () => {+ expect(+ writeFilesToClipboard(+ ['/tmp/a'],+ dependencies({+ writeBuffer: () => {+ throw new Error('clipboard unavailable')+ }+ })+ )+ ).toBe(false)+ })+})++describe('fileListPropertyList', () => {+ it('escapes every XML-significant path character', () => {+ expect(fileListPropertyList([`/tmp/<a>\"'&`]).toString()).toContain(+ '<a>"'&'+ )+ })+})diff --git a/src/main/clipboard-files.ts b/src/main/clipboard-files.tsnew file mode 100644index 000000000..bf514d0cf--- /dev/null+++ b/src/main/clipboard-files.ts@@ -0,0 +1,64 @@+import { isAbsolute } from 'path'++export const FILE_LIST_PASTEBOARD_TYPE = 'NSFilenamesPboardType'+const MAX_CLIPBOARD_FILES = 64++export interface FileClipboardDependencies {+ platform: string+ isFile(path: string): boolean+ writeBuffer(format: string, buffer: Buffer): void+}++const escapeXml = (value: string): string =>+ value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''')++export function fileListPropertyList(paths: string[]): Buffer {+ const entries = paths.map((path) => ` <string>${escapeXml(path)}</string>`).join('\n')+ return Buffer.from(+ `<?xml version="1.0" encoding="UTF-8"?>\n` ++ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n` ++ `<plist version="1.0">\n <array>\n${entries}\n </array>\n</plist>\n`,+ 'utf8'+ )+}++/**+ * Put existing local regular files on the macOS clipboard as Finder-compatible file references.+ * Inputs cross an IPC trust boundary, so paths are capped, absolute-only, de-duplicated and+ * re-checked in main. The operation is all-or-nothing so a multi-selection is never silently+ * truncated or partially copied.+ */+export function writeFilesToClipboard(+ input: unknown,+ dependencies: FileClipboardDependencies+): boolean {+ if (dependencies.platform !== 'darwin' || !Array.isArray(input)) return false++ const paths: string[] = []+ const seen = new Set<string>()+ for (const value of input) {+ if (typeof value !== 'string' || !isAbsolute(value)) return false+ if (seen.has(value)) continue+ if (paths.length >= MAX_CLIPBOARD_FILES) return false+ try {+ if (!dependencies.isFile(value)) return false+ } catch {+ return false+ }+ seen.add(value)+ paths.push(value)+ }+ if (!paths.length) return false++ try {+ dependencies.writeBuffer(FILE_LIST_PASTEBOARD_TYPE, fileListPropertyList(paths))+ return true+ } catch {+ return false+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 741bbeff1..9a5ee521d 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2,10 +2,12 @@ import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'import { readFile } from 'fs/promises'+import { statSync } from 'fs'import { homedir, hostname } from 'os'import { randomUUID } from 'crypto'import { app, BrowserWindow, clipboard, dialog, ipcMain, Notification, powerMonitor, safeStorage, shell, systemPreferences } from 'electron'import { IPC } from '../shared/ipc'+import { writeFilesToClipboard } from './clipboard-files'import { registerFsHandlers } from '../core/fs-handlers'import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'import type { RemoteLogExec } from '../core/board-log'@@ -645,6 +647,13 @@ app.whenReady().then(async () => {ipcMain.on(IPC.clipboardWrite, (_e, text: string) => {if (typeof text === 'string') clipboard.writeText(text)})+ ipcMain.handle(IPC.clipboardWriteFiles, (_e, paths: unknown) =>+ writeFilesToClipboard(paths, {+ platform: process.platform,+ isFile: (path) => statSync(path).isFile(),+ writeBuffer: (format, buffer) => clipboard.writeBuffer(format, buffer)+ })+ )// Dock badge: number of Claude nodes with unread output (macOS only). '' clears it.ipcMain.on(IPC.appSetBadge, (_e, count: number) => {diff --git a/src/preload/index.ts b/src/preload/index.tsindex ff4aaebb2..61faf5e78 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -287,7 +287,8 @@ const api: NodeTerminalApi = {},clipboard: {// Route to the MAIN process: renderer-side `clipboard` access is deprecated in Electron.- writeText: (text: string) => ipcRenderer.send(IPC.clipboardWrite, text)+ writeText: (text: string) => ipcRenderer.send(IPC.clipboardWrite, text),+ writeFiles: (paths: string[]) => ipcRenderer.invoke(IPC.clipboardWriteFiles, paths)},shell: {reveal: (path: string) => ipcRenderer.send(IPC.shellReveal, path),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 4a154149a..6cd9d82a0 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -165,7 +165,9 @@ export function buildStubApi(): Omit<return}copyViaExecCommand(text)- }+ },+ // A browser cannot place host-local file references on the viewer's OS clipboard.+ writeFiles: async (): Promise<boolean> => false},shell: {// no filesystem-reveal in a browser; intentionally inert (see docs/SERVER.md)diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 0b95c6815..915c12ed2 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -34,6 +34,13 @@ import {wakeHibernatedNode} from '../nodes/TerminalNode'import { solveFitPadding } from './fit-view'+import { MacWheelGestureRouter } from './wheel-gesture'+import { selectedLocalFilePaths } from './canvas-file-copy'+import {+ canvasImagePasteArmedAfterKey,+ guardedCanvasImagePlacements,+ isCanvasImageDropTarget+} from './canvas-image-import'import {SharedGlyphLayer,flushOpaqueNodeIds,@@ -204,6 +211,13 @@ import {import { normWorktreePath, type BoundGroup } from '@shared/worktree-reconcile'import { boundGroups, scmScopes, defaultScmScope, selectedScmGroupId } from '@shared/scm-scope'import { hintLabel } from '@shared/platform-utils'+import {+ canvasImageFiles,+ clipboardImages,+ localPathsForFiles,+ pasteHasText,+ pastedFiles+} from '../terminal/file-drop'import { useWorktrees } from '../state/worktrees'import { activeSessionApi } from '../session/session'import {@@ -676,6 +690,10 @@ export function Canvas() {// `nodeterm:toast` when neither the Clipboard API nor execCommand can copy — typically a// non-secure context (plain http over a LAN). It must be seen, not swallowed.const [copyError, setCopyError] = useState<string | null>(null)+ // Cmd+V only drops an image on the canvas when the LAST pointer press was on the pane itself —+ // otherwise a paste aimed at a panel or a dialog would spawn a node behind it. See+ // canvas-image-import.ts for the arming rules.+ const canvasImagePasteArmedRef = useRef(false)// Result of a worktree operation (merge / remove). These used to be `window.alert`s — a modal// that blocks the whole app to say "Merged feat into main." Shown as a strip in the existing// top-banner column instead; an 'info' one fades itself out, an 'error' stays until dismissed.@@ -2533,20 +2551,28 @@ export function Canvas() {// zoom to the cursor. React Flow's own zoomOnPinch / zoomActivationKeyCode are disabled so// this is the single source of zoom (no double-zoom on the open canvas).//- // With settings.wheelZoom on, a PLAIN wheel zooms too (mouse-first workflow; scroll-to-pan- // is disabled on <ReactFlow> in that mode) — except inside a `nowheel` node body (focused- // xterm scrollback, Monaco, markdown/chat panes), which keeps its own scrolling. The hover- // guard overlay is NOT nowheel, so an unfocused terminal still zooms under the cursor.+ // With settings.wheelZoom on, a PLAIN mouse wheel zooms too (mouse-first workflow) — except+ // inside a `nowheel` node body (focused xterm scrollback, Monaco, markdown/chat panes), which+ // keeps its own scrolling. The hover guard overlay is NOT nowheel, so an unfocused terminal+ // still zooms under the cursor. On macOS a two-finger TRACKPAD scroll keeps panning even with+ // wheelZoom on: Chromium reports both devices as an unmodified pixel-wheel, so+ // MacWheelGestureRouter tells them apart (and stays sticky for the length of one physical+ // gesture) and hands trackpad packets back to React Flow's own panOnScroll.const wheelZoom = settings.wheelZoomuseEffect(() => {const wrap = flowWrapRef.currentif (!wrap) return+ const wheelRouting = new MacWheelGestureRouter()const onWheel = (e: WheelEvent) => {if (canvasLocked) returnif (!e.ctrlKey && !e.metaKey) {+ const overNativeScrollable = !!(e.target as HTMLElement | null)?.closest('.nowheel')+ // A macOS trackpad's two-finger scroll pans the canvas outside native scroll surfaces;+ // inside them (terminal, Monaco, markdown) it scrolls that surface as before.+ if (wheelRouting.destination(e, isMac, overNativeScrollable) === 'flow-pan') return+ if (overNativeScrollable) return// pinch (ctrl+wheel) / Cmd/Ctrl+scroll always zoom; plain wheel only when opted inif (!wheelZoom) return- if ((e.target as HTMLElement | null)?.closest('.nowheel')) return}e.preventDefault()e.stopPropagation()@@ -2920,6 +2946,97 @@ export function Canvas() {[setNodes, markDirty, viewCenter])+ // Reuse the same path resolver as terminal file paste/drop, then feed the existing Open-file+ // node path. Desktop Finder drops retain their real path; clipboard/browser blobs are saved in+ // NodeTerm's managed upload directory first. Multiple images fan out diagonally from the cursor.+ const placeCanvasImages = useCallback(+ async (files: File[], center: { x: number; y: number }, projectId: string) => {+ const images = canvasImageFiles(files)+ if (!images.length) return+ const placements = await guardedCanvasImagePlacements(+ () => localPathsForFiles(images),+ projectId,+ () => useProjects.getState().activeProjectId,+ center+ )+ placements.forEach(({ filePath, center: placement }) => openFile(filePath, placement))+ },+ [openFile]+ )++ // Drop or paste an image onto empty canvas → an image preview node. Registered on `window`+ // (not the wrapper) because a paste has no drop target, and gated by isCanvasImageDropTarget so+ // panels, dialogs and node bodies keep their own drop/paste behavior.+ useEffect(() => {+ const wrap = flowWrapRef.current+ if (!wrap) return+ const editableTarget = (target: EventTarget | null): boolean => {+ const element = target instanceof Element ? target : null+ return !!element?.closest(+ 'input, textarea, select, button, [contenteditable], [role="dialog"], .monaco-editor, .xterm, .react-flow__node'+ )+ }+ const onPointerDown = (event: PointerEvent) => {+ canvasImagePasteArmedRef.current = isCanvasImageDropTarget(event.target, wrap)+ }+ const onKeyDown = (event: KeyboardEvent) => {+ canvasImagePasteArmedRef.current = canvasImagePasteArmedAfterKey(+ canvasImagePasteArmedRef.current,+ event+ )+ }+ const onDragOver = (event: DragEvent) => {+ if (!isCanvasImageDropTarget(event.target, wrap)) return+ if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return+ event.preventDefault()+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy'+ }+ const onDrop = (event: DragEvent) => {+ if (!isCanvasImageDropTarget(event.target, wrap)) return+ const images = canvasImageFiles(Array.from(event.dataTransfer?.files ?? []))+ if (!images.length) return+ event.preventDefault()+ event.stopPropagation()+ const center = screenToFlowPosition({ x: event.clientX, y: event.clientY })+ const projectId = useProjects.getState().activeProjectId+ if (projectId) void placeCanvasImages(images, center, projectId)+ }+ const onPaste = (event: ClipboardEvent) => {+ if (!canvasImagePasteArmedRef.current || !hasProjects || welcomeOpen || kanbanOpen) return+ if (document.querySelector('[role="dialog"], .usage-popover')) return+ if (editableTarget(event.target)) return+ const projectId = useProjects.getState().activeProjectId+ if (!projectId) return+ const center = viewCenter()+ if (!center) return+ const files = canvasImageFiles(pastedFiles(event.clipboardData))+ if (files.length) {+ event.preventDefault()+ event.stopPropagation()+ void placeCanvasImages(files, center, projectId)+ return+ }+ // A screenshot can arrive with an empty clipboardData when Chromium filters the paste+ // target. Ordinary text must remain untouched; only the image-only case uses async read().+ if (pasteHasText(event.clipboardData)) return+ void clipboardImages().then((images) => {+ if (images.length) void placeCanvasImages(images, center, projectId)+ })+ }+ window.addEventListener('pointerdown', onPointerDown, true)+ window.addEventListener('keydown', onKeyDown, true)+ window.addEventListener('dragover', onDragOver)+ window.addEventListener('drop', onDrop)+ window.addEventListener('paste', onPaste)+ return () => {+ window.removeEventListener('pointerdown', onPointerDown, true)+ window.removeEventListener('keydown', onKeyDown, true)+ window.removeEventListener('dragover', onDragOver)+ window.removeEventListener('drop', onDrop)+ window.removeEventListener('paste', onPaste)+ }+ }, [hasProjects, kanbanOpen, placeCanvasImages, screenToFlowPosition, viewCenter, welcomeOpen])+// Load the quick-open file index when the palette opens.useEffect(() => {if (!paletteOpen) return@@ -4693,11 +4810,36 @@ export function Canvas() {switchProject(targetId)}} else if ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === 'c') {- // Copy the current page selection (e.g. markdown view) to the clipboard.+ // Native text selection wins (markdown, editor and terminal keep their normal copy path).const tag = (document.activeElement?.tagName || '').toLowerCase()- if (tag === 'input' || tag === 'textarea') return+ if (+ tag === 'input' ||+ tag === 'textarea' ||+ document.activeElement?.getAttribute('contenteditable') === 'true' ||+ document.activeElement?.closest('.monaco-editor, .xterm')+ )+ returnconst sel = window.getSelection?.()?.toString()- if (sel) window.nodeTerminal.clipboard.writeText(sel)+ if (sel) {+ window.nodeTerminal.clipboard.writeText(sel)+ return+ }+ // Nothing selected as text: copy the selected file-backed nodes as FILE REFERENCES, so+ // Finder (or any file-aware app) pastes the actual files. Desktop/macOS only — the browser+ // stub answers false and the banner says why.+ const paths = selectedLocalFilePaths(nodesRef.current)+ if (!paths.length) return+ e.preventDefault()+ void window.nodeTerminal.clipboard+ .writeFiles(paths)+ .then((copied) => {+ setCopyError(+ copied+ ? null+ : 'Copy failed — only existing local files can be copied from the macOS desktop app.'+ )+ })+ .catch(() => setCopyError('Copy failed — the system clipboard is unavailable.'))}}window.addEventListener('keydown', onKey)@@ -8243,7 +8385,7 @@ export function Canvas() {? [0, 1]: [1]}- panOnScroll={canvasLocked ? false : !wheelZoom}+ panOnScroll={canvasLocked ? false : isMac || !wheelZoom}zoomOnScroll={false}zoomOnPinch={false}// Off: a pane double-click is the overview-zoom gesture (see PANE_OVERVIEW_ZOOM) and adiff --git a/src/renderer/canvas/canvas-file-copy.test.ts b/src/renderer/canvas/canvas-file-copy.test.tsnew file mode 100644index 000000000..85fb01df5--- /dev/null+++ b/src/renderer/canvas/canvas-file-copy.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'+import type { CanvasNode } from '../state/workspace'+import { selectedLocalFilePaths } from './canvas-file-copy'++const node = (+ id: string,+ type: CanvasNode['type'],+ filePath: string,+ data: Record<string, unknown> = {}+): CanvasNode =>+ ({+ id,+ type,+ selected: true,+ position: { x: 0, y: 0 },+ data: { title: id, color: '#fff', group: null, filePath, ...data }+ }) as CanvasNode++describe('selectedLocalFilePaths', () => {+ it('returns selected local file-backed nodes once and in canvas order', () => {+ expect(+ selectedLocalFilePaths([+ node('image', 'editor', '/tmp/image.png'),+ node('video', 'video', '/tmp/video.mp4'),+ node('html', 'web', '/tmp/page.html'),+ node('duplicate', 'editor', '/tmp/image.png')+ ])+ ).toEqual(['/tmp/image.png', '/tmp/video.mp4', '/tmp/page.html'])+ })++ it('excludes unselected, remote, missing and non-file node kinds', () => {+ const unselected = node('unselected', 'editor', '/tmp/a')+ unselected.selected = false+ expect(+ selectedLocalFilePaths([+ unselected,+ node('remote', 'editor', '/tmp/b', { sshFs: true }),+ node('missing', 'video', '/tmp/c', { fileMissing: true }),+ node('diff', 'diff', '/tmp/d'),+ node('url', 'web', '')+ ])+ ).toEqual([])+ })+})diff --git a/src/renderer/canvas/canvas-file-copy.ts b/src/renderer/canvas/canvas-file-copy.tsnew file mode 100644index 000000000..1440d325a--- /dev/null+++ b/src/renderer/canvas/canvas-file-copy.ts@@ -0,0 +1,26 @@+import type { CanvasNode } from '../state/workspace'++const LOCAL_FILE_NODE_TYPES = new Set(['editor', 'video', 'web'])++/** Paths represented by the selected local file-backed nodes, in canvas order and without dupes. */+export function selectedLocalFilePaths(nodes: CanvasNode[]): string[] {+ const seen = new Set<string>()+ const paths: string[] = []+ for (const node of nodes) {+ const path = node.data.filePath+ if (+ !node.selected ||+ !LOCAL_FILE_NODE_TYPES.has(node.type) ||+ typeof path !== 'string' ||+ !path ||+ node.data.sshFs ||+ node.data.fileMissing ||+ seen.has(path)+ ) {+ continue+ }+ seen.add(path)+ paths.push(path)+ }+ return paths+}diff --git a/src/renderer/canvas/canvas-image-import.test.ts b/src/renderer/canvas/canvas-image-import.test.tsnew file mode 100644index 000000000..2b2f84c8e--- /dev/null+++ b/src/renderer/canvas/canvas-image-import.test.ts@@ -0,0 +1,79 @@+// @vitest-environment jsdom+import { describe, expect, it } from 'vitest'+import {+ canvasImagePasteArmedAfterKey,+ guardedCanvasImagePlacements,+ isCanvasImageDropTarget+} from './canvas-image-import'++describe('isCanvasImageDropTarget', () => {+ it('accepts the real pane and rejects flow-wrap overlays and nodes', () => {+ const wrap = document.createElement('div')+ wrap.innerHTML = `+ <div class="react-flow__pane"><div class="react-flow__node"><span>node</span></div></div>+ <div class="welcome"><button>open</button></div>+ <div class="usage-indicator"><div class="usage-popover">usage</div></div>+ `+ const pane = wrap.querySelector('.react-flow__pane')!+ expect(isCanvasImageDropTarget(pane, wrap)).toBe(true)+ expect(isCanvasImageDropTarget(wrap.querySelector('.react-flow__node span'), wrap)).toBe(false)+ expect(isCanvasImageDropTarget(wrap.querySelector('.welcome'), wrap)).toBe(false)+ expect(isCanvasImageDropTarget(wrap.querySelector('.usage-popover'), wrap)).toBe(false)+ })++ it('rejects dialogs and sidebars outside the canvas wrapper', () => {+ const root = document.createElement('div')+ root.innerHTML = `+ <div class="flow-wrap"><div class="react-flow__pane"></div></div>+ <div role="dialog">settings</div>+ <aside class="sessions-sidebar">sessions</aside>+ `+ const wrap = root.querySelector('.flow-wrap')!+ expect(isCanvasImageDropTarget(root.querySelector('[role="dialog"]'), wrap)).toBe(false)+ expect(isCanvasImageDropTarget(root.querySelector('.sessions-sidebar'), wrap)).toBe(false)+ })+})++describe('guardedCanvasImagePlacements', () => {+ it('places every resolved path while the originating project remains active', async () => {+ await expect(+ guardedCanvasImagePlacements(+ async () => ['/tmp/a.png', '/tmp/b.png'],+ 'project-a',+ () => 'project-a',+ { x: 10, y: 20 }+ )+ ).resolves.toEqual([+ { filePath: '/tmp/a.png', center: { x: 10, y: 20 } },+ { filePath: '/tmp/b.png', center: { x: 46, y: 56 } }+ ])+ })++ it('abandons an async result after a project switch', async () => {+ let release!: (paths: string[]) => void+ const pending = new Promise<string[]>((resolve) => (release = resolve))+ let active = 'project-a'+ const placements = guardedCanvasImagePlacements(+ () => pending,+ 'project-a',+ () => active,+ { x: 10, y: 20 }+ )+ active = 'project-b'+ release(['/tmp/a.png'])+ await expect(placements).resolves.toEqual([])+ })+})++describe('canvasImagePasteArmedAfterKey', () => {+ it('preserves a real Cmd+V sequence but revokes arming for a keyboard-opened overlay', () => {+ const meta = { key: 'Meta', metaKey: true, ctrlKey: false }+ const paste = { key: 'v', metaKey: true, ctrlKey: false }+ const openSettings = { key: ',', metaKey: true, ctrlKey: false }++ expect(canvasImagePasteArmedAfterKey(true, meta)).toBe(true)+ expect(canvasImagePasteArmedAfterKey(true, paste)).toBe(true)+ expect(canvasImagePasteArmedAfterKey(true, openSettings)).toBe(false)+ expect(canvasImagePasteArmedAfterKey(false, paste)).toBe(false)+ })+})diff --git a/src/renderer/canvas/canvas-image-import.ts b/src/renderer/canvas/canvas-image-import.tsnew file mode 100644index 000000000..859f25208--- /dev/null+++ b/src/renderer/canvas/canvas-image-import.ts@@ -0,0 +1,45 @@+/** True only for the actual React Flow pane, never flow-wrap overlays such as Welcome/Usage. */+export function isCanvasImageDropTarget(target: EventTarget | null, wrap: Element): boolean {+ const element = target instanceof Element ? target : null+ return !!(+ element &&+ wrap.contains(element) &&+ element.closest('.react-flow__pane') &&+ !element.closest('.react-flow__node, .react-flow__controls, .react-flow__minimap')+ )+}++export interface CanvasImagePlacement {+ filePath: string+ center: { x: number; y: number }+}++/**+ * Keyboard-opened UI must revoke a prior canvas click. Modifier keydown events are part of the+ * normal Cmd+V sequence, so only they and the actual paste chord preserve the armed state.+ */+export function canvasImagePasteArmedAfterKey(+ armed: boolean,+ event: { key: string; metaKey: boolean; ctrlKey: boolean }+): boolean {+ if (!armed) return false+ if (event.key === 'Meta' || event.key === 'Control' || event.key === 'Alt' || event.key === 'Shift') {+ return true+ }+ return (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'v'+}++/** Resolve image files asynchronously, but abandon them if their originating project changed. */+export async function guardedCanvasImagePlacements(+ resolvePaths: () => Promise<string[]>,+ originatingProjectId: string,+ activeProjectId: () => string,+ center: { x: number; y: number }+): Promise<CanvasImagePlacement[]> {+ const paths = await resolvePaths()+ if (activeProjectId() !== originatingProjectId) return []+ return paths.map((filePath, index) => ({+ filePath,+ center: { x: center.x + index * 36, y: center.y + index * 36 }+ }))+}diff --git a/src/renderer/canvas/wheel-gesture.test.ts b/src/renderer/canvas/wheel-gesture.test.tsnew file mode 100644index 000000000..8c12a52a1--- /dev/null+++ b/src/renderer/canvas/wheel-gesture.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest'+import { MacWheelGestureRouter } from './wheel-gesture'++const gesture = (+ deltaY: number,+ o: Partial<{+ deltaX: number+ deltaMode: number+ ctrlKey: boolean+ metaKey: boolean+ wheelDeltaY: number+ }> = {}+) => ({+ deltaY,+ deltaX: o.deltaX ?? 0,+ deltaMode: o.deltaMode ?? 0,+ ctrlKey: o.ctrlKey ?? false,+ metaKey: o.metaKey ?? false,+ wheelDeltaY: o.wheelDeltaY+})++describe('MacWheelGestureRouter', () => {+ it('keeps a notched macOS mouse wheel on the user-configured zoom path', () => {+ const router = new MacWheelGestureRouter()+ expect(router.shouldPan(gesture(100, { wheelDeltaY: -120 }), true, 1000)).toBe(false)+ expect(router.shouldPan(gesture(-100, { wheelDeltaY: 120 }), true, 1100)).toBe(false)+ })++ it('routes smooth two-finger trackpad scroll and its momentum to panning', () => {+ const router = new MacWheelGestureRouter()+ expect(router.shouldPan(gesture(6.25), true, 1000)).toBe(true)+ expect(router.shouldPan(gesture(75), true, 1080)).toBe(true)+ expect(router.shouldPan(gesture(75), true, 1700)).toBe(false)+ })++ it('does not reclassify a quantized packet in an active trackpad gesture as mouse zoom', () => {+ const router = new MacWheelGestureRouter()+ expect(router.shouldPan(gesture(4.5), true, 1000)).toBe(true)+ expect(router.shouldPan(gesture(100, { wheelDeltaY: -120 }), true, 1150)).toBe(true)+ expect(router.shouldPan(gesture(70), true, 1500)).toBe(true)+ })++ it('keeps trackpad scrolling native over terminal and other native scroll surfaces', () => {+ const router = new MacWheelGestureRouter()+ expect(router.destination(gesture(6.25), true, true, 1000)).toBe('native')+ expect(router.destination(gesture(6.25), true, false, 1400)).toBe('flow-pan')+ expect(router.destination(gesture(100, { wheelDeltaY: -120 }), true, true, 1800)).toBe('native')+ })++ it('does not pan over a non-terminal native scroller, and still knows the gesture is a trackpad', () => {+ const router = new MacWheelGestureRouter()+ // A trackpad gesture that begins over Monaco / a markdown pane scrolls THAT surface...+ expect(router.destination(gesture(6.25), true, true, 1000)).toBe('native')+ // ...but the packet still classified the device, so continuing the same gesture off the+ // scroller pans the canvas instead of falling back to the mouse-notch (zoom) path.+ expect(router.destination(gesture(75), true, false, 1100)).toBe('flow-pan')+ })++ it('keeps pinch, Cmd-wheel, line-mode wheel and other platforms off the override', () => {+ const router = new MacWheelGestureRouter()+ expect(router.shouldPan(gesture(5, { ctrlKey: true }), true, 1000)).toBe(false)+ expect(router.shouldPan(gesture(5, { metaKey: true }), true, 1000)).toBe(false)+ expect(router.shouldPan(gesture(3, { deltaMode: 1 }), true, 1000)).toBe(false)+ expect(router.shouldPan(gesture(5), false, 1000)).toBe(false)+ })+})diff --git a/src/renderer/canvas/wheel-gesture.ts b/src/renderer/canvas/wheel-gesture.tsnew file mode 100644index 000000000..31addf18d--- /dev/null+++ b/src/renderer/canvas/wheel-gesture.ts@@ -0,0 +1,51 @@+type WheelGesture = Pick<WheelEvent, 'ctrlKey' | 'metaKey' | 'deltaMode' | 'deltaX' | 'deltaY'> & {+ wheelDeltaY?: number+}++export type MacWheelDestination = 'flow-pan' | 'native'++const TRACKPAD_SEQUENCE_MS = 500+const MOUSE_WHEEL_NOTCH = 120+const LARGE_PIXEL_DELTA = 40++/** Pixel mode alone is not a device identity: Chromium uses it for trackpads and many mice. */+export class MacWheelGestureRouter {+ private trackpadUntil = 0++ shouldPan(event: WheelGesture, mac: boolean, now = performance.now()): boolean {+ if (!mac || event.ctrlKey || event.metaKey || event.deltaMode !== 0) return false+ // Device identity is sticky for one physical gesture. Chromium can quantize a later+ // trackpad/momentum event to wheelDeltaY=120; treating that single packet as a mouse notch+ // hands it to wheelZoom and creates the observed one-frame zoom inside an otherwise pure pan.+ if (now <= this.trackpadUntil) {+ this.trackpadUntil = now + TRACKPAD_SEQUENCE_MS+ return true+ }+ const legacyDelta = Math.abs(event.wheelDeltaY ?? 0)+ const mouseNotch = legacyDelta >= MOUSE_WHEEL_NOTCH && legacyDelta % MOUSE_WHEEL_NOTCH === 0+ if (mouseNotch) {+ this.trackpadUntil = 0+ return false+ }+ const smooth =+ event.deltaX !== 0 ||+ !Number.isInteger(event.deltaX) ||+ !Number.isInteger(event.deltaY) ||+ Math.abs(event.deltaY) < LARGE_PIXEL_DELTA+ if (smooth) {+ this.trackpadUntil = now + TRACKPAD_SEQUENCE_MS+ return true+ }+ return false+ }++ destination(+ event: WheelGesture,+ mac: boolean,+ overNativeScrollable: boolean,+ now = performance.now()+ ): MacWheelDestination {+ if (!this.shouldPan(event, mac, now)) return 'native'+ return overNativeScrollable ? 'native' : 'flow-pan'+ }+}diff --git a/src/renderer/terminal/file-drop.test.ts b/src/renderer/terminal/file-drop.test.tsindex 008353410..cbdb1e33c 100644--- a/src/renderer/terminal/file-drop.test.ts+++ b/src/renderer/terminal/file-drop.test.ts@@ -1,7 +1,9 @@import { describe, it, expect, afterEach, vi } from 'vitest'import {+ canvasImageFiles,clipboardImages,escapeDroppedPath,+ localPathsForFiles,pasteHasText,pastedFiles,uploadNameFor@@ -61,6 +63,30 @@ describe('pastedFiles', () => {})})+describe('canvasImageFiles', () => {+ it('keeps MIME images and known image extensions only', () => {+ const png = new File(['png'], 'shot.png', { type: 'image/png' })+ const avif = new File(['avif'], 'photo.AVIF')+ const text = new File(['hello'], 'notes.txt', { type: 'text/plain' })+ expect(canvasImageFiles([png, avif, text])).toEqual([png, avif])+ })+})++describe('localPathsForFiles', () => {+ afterEach(() => vi.unstubAllGlobals())++ it('reuses an Electron file path without shell escaping it', async () => {+ vi.stubGlobal('window', {+ nodeTerminal: {+ getPathForFile: () => '/tmp/My image.png',+ files: { saveUpload: vi.fn() }+ }+ })+ const file = new File(['png'], 'My image.png', { type: 'image/png' })+ expect(await localPathsForFiles([file])).toEqual(['/tmp/My image.png'])+ })+})+describe('pasteHasText', () => {it('separates an ordinary text paste from one that carried nothing at all', () => {expect(pasteHasText(clipboard({ text: 'hello' }))).toBe(true)diff --git a/src/renderer/terminal/file-drop.ts b/src/renderer/terminal/file-drop.tsindex af7c7b81e..5d6db3b0b 100644--- a/src/renderer/terminal/file-drop.ts+++ b/src/renderer/terminal/file-drop.ts@@ -22,6 +22,37 @@ const EXT_BY_TYPE: Record<string, string> = {'text/plain': 'txt'}+const CANVAS_IMAGE_EXTENSIONS = new Set([+ 'png',+ 'jpg',+ 'jpeg',+ 'gif',+ 'webp',+ 'bmp',+ 'ico',+ 'svg',+ 'avif'+])+const CANVAS_IMAGE_MIME = new Set([+ 'image/png',+ 'image/jpeg',+ 'image/gif',+ 'image/webp',+ 'image/bmp',+ 'image/x-icon',+ 'image/svg+xml',+ 'image/avif'+])++/** Only image files become canvas preview nodes; other dropped files keep the existing no-op. */+export function canvasImageFiles(files: File[]): File[] {+ return files.filter((file) => {+ if (CANVAS_IMAGE_MIME.has(file.type.toLowerCase())) return true+ const ext = file.name.split('.').pop()?.toLowerCase() ?? ''+ return CANVAS_IMAGE_EXTENSIONS.has(ext)+ })+}+/** The name to store a file under. Clipboard bytes usually have none, so one is generated from* the MIME type + a timestamp — recognizable in a prompt and unique enough to read back. */export function uploadNameFor(file: { name: string; type: string }): string {@@ -116,6 +147,18 @@ async function localPathFor(file: File): Promise<string | null> {return window.nodeTerminal.files.saveUpload(uploadNameFor(file), data).catch(() => null)}+async function localFilesWithPaths(files: File[]): Promise<Array<{ file: File; path: string }>> {+ const local = await Promise.all(files.map((f) => localPathFor(f).catch(() => null)))+ return files+ .map((file, i) => ({ file, path: local[i] }))+ .filter((pair): pair is { file: File; path: string } => !!pair.path)+}++/** Resolve local/clipboard/browser files to raw local paths for non-terminal consumers. */+export async function localPathsForFiles(files: File[]): Promise<string[]> {+ return (await localFilesWithPaths(files)).map((pair) => pair.path)+}+/*** Resolve dropped/pasted files to terminal-pasteable paths. For an SSH-project terminal a local* path is useless on the host, so each file is uploaded over the project's ControlMaster and its@@ -126,10 +169,7 @@ export async function droppedPaths(files: File[],opts: { sshRemoteTmux: boolean; projectId: string }): Promise<string[]> {- const local = await Promise.all(files.map((f) => localPathFor(f).catch(() => null)))- const pairs = files- .map((f, i) => ({ file: f, path: local[i] }))- .filter((p): p is { file: File; path: string } => !!p.path)+ const pairs = await localFilesWithPaths(files)if (!opts.sshRemoteTmux) return pairs.map((p) => escapeDroppedPath(p.path))const uploaded = await Promise.all(pairs.map((p) =>diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex c15d1ada0..a9c7c1ad3 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -47,6 +47,8 @@ export const IPC = {/** Write text to the system clipboard from the MAIN process. Renderer-side `clipboard` access is* deprecated in Electron; the renderer sends this instead (fire-and-forget). */clipboardWrite: 'clipboard:write',+ /** Copy local files as file references (not bytes/text) to the macOS system clipboard. */+ clipboardWriteFiles: 'clipboard:write-files',appNotify: 'app:notify',appOpenNotificationSettings: 'app:open-notification-settings',appFocusNode: 'app:focus-node',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 1af23fcf2..e221dceea 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -672,6 +672,8 @@ export interface DialogApi {export interface ClipboardApi {writeText(text: string): void+ /** Copy local files so Finder and other file-aware macOS apps can paste them. */+ writeFiles(paths: string[]): Promise<boolean>}export interface ShellApi {@@ -861,8 +863,9 @@ export interface Settings {* tmux's buffer, and it never reached the browser.*/terminalMiddleClickPaste: boolean- /** Plain mouse wheel zooms the canvas (no Cmd/Ctrl needed). Trades away scroll-to-pan,- * so it's opt-in — best for mouse users; trackpads keep two-finger pan when off. */+ /** Plain mouse wheel zooms the canvas (no Cmd/Ctrl needed). On macOS a two-finger trackpad+ * scroll keeps panning independently (see canvas/wheel-gesture.ts), so mouse and trackpad+ * coexist; elsewhere this still trades away scroll-to-pan, so it stays opt-in. */wheelZoom: boolean/** What a left-drag on EMPTY canvas does. 'select' (default) rubber-band selects, like* Figma's move tool — pan stays on middle-drag / two-finger scroll. 'pan' drags the map