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(windows): copy file-backed nodes to the clipboard as files (CF_HDROP)
review7470f232661c
diff --git a/src/main/clipboard-files-win.test.ts b/src/main/clipboard-files-win.test.tsnew file mode 100644index 000000000..50485ed11--- /dev/null+++ b/src/main/clipboard-files-win.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest'+import {+ WINDOWS_FILE_DROP_SCRIPT,+ WINDOWS_FILE_DROP_TIMEOUT_MS,+ windowsPowerShellPath,+ writeWindowsFileDrop,+ type ExecFileLike+} from './clipboard-files-win'++function fakeExec(error: Error | null = null) {+ const stdin = { end: vi.fn(), on: vi.fn() }+ const calls: Array<{ file: string; args: string[]; options: unknown }> = []+ const run: ExecFileLike = (file, args, options, callback) => {+ calls.push({ file, args, options })+ queueMicrotask(() => callback(error))+ return { stdin }+ }+ return { run, stdin, calls }+}++describe('writeWindowsFileDrop', () => {+ it('runs Windows PowerShell 5.1 in STA and sends the paths on stdin, never argv', async () => {+ const { run, stdin, calls } = fakeExec()+ const paths = ['C:\\a"; Remove-Item x; ".png', 'C:\\b $(evil).txt']+ expect(await writeWindowsFileDrop(paths, { execFile: run, env: { SystemRoot: 'D:\\Win' } })).toBe(true)+ expect(calls).toHaveLength(1)+ expect(calls[0].file).toBe('D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe')+ expect(calls[0].args).toEqual(['-NoProfile', '-NonInteractive', '-STA', '-Command', WINDOWS_FILE_DROP_SCRIPT])+ for (const arg of calls[0].args) for (const p of paths) expect(arg).not.toContain(p)+ expect(calls[0].options).toEqual({ timeout: WINDOWS_FILE_DROP_TIMEOUT_MS, windowsHide: true })+ expect(stdin.end).toHaveBeenCalledWith(JSON.stringify(paths))+ })++ it('maps a nonzero exit or a timeout kill to false', async () => {+ expect(await writeWindowsFileDrop(['C:\\a'], { execFile: fakeExec(new Error('exit 1')).run })).toBe(false)+ const killed = Object.assign(new Error('timed out'), { killed: true, signal: 'SIGTERM' })+ expect(await writeWindowsFileDrop(['C:\\a'], { execFile: fakeExec(killed).run })).toBe(false)+ })++ it('fails closed when the process cannot be spawned', async () => {+ const throwing: ExecFileLike = () => {+ throw new Error('ENOENT')+ }+ expect(await writeWindowsFileDrop(['C:\\a'], { execFile: throwing })).toBe(false)+ expect(await writeWindowsFileDrop(['C:\\a'], { execFile: () => ({ stdin: null }) })).toBe(false)+ })++ it('writes a real CF_HDROP through SetFileDropList', () => {+ expect(WINDOWS_FILE_DROP_SCRIPT).toContain('[System.Windows.Forms.Clipboard]::SetFileDropList')+ expect(WINDOWS_FILE_DROP_SCRIPT).toContain('[Console]::In.ReadToEnd()')+ })+})++describe('windowsPowerShellPath', () => {+ it('pins the inbox 5.1 binary and falls back to C:\\Windows', () => {+ expect(windowsPowerShellPath({})).toBe('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe')+ expect(windowsPowerShellPath({ WINDIR: 'E:\\W' })).toBe('E:\\W\\System32\\WindowsPowerShell\\v1.0\\powershell.exe')+ })+})diff --git a/src/main/clipboard-files-win.ts b/src/main/clipboard-files-win.tsnew file mode 100644index 000000000..00e9abc25--- /dev/null+++ b/src/main/clipboard-files-win.ts@@ -0,0 +1,63 @@+import { execFile } from 'child_process'+import { win32 } from 'path'++/**+ * Windows leg of "copy file-backed nodes as files": a real CF_HDROP via+ * `System.Windows.Forms.Clipboard.SetFileDropList`, run in Windows PowerShell 5.1.+ *+ * - The explicit `System32\WindowsPowerShell\v1.0` path pins 5.1 (always present, .NET Framework,+ * WinForms available) — `pwsh` 7's `Set-Clipboard` has no `-Path`, and PATH is not trusted.+ * - `-STA`: the OLE clipboard refuses an MTA thread.+ * - The PATHS NEVER RIDE ARGV OR THE SCRIPT TEXT: they arrive as JSON on stdin, so there is no+ * quoting to get wrong and nothing for a crafted file name to inject into.+ */+export const WINDOWS_FILE_DROP_SCRIPT =+ '$ErrorActionPreference = "Stop"; ' ++ '$p = @([Console]::In.ReadToEnd() | ConvertFrom-Json); ' ++ 'Add-Type -AssemblyName System.Windows.Forms; ' ++ '$c = New-Object System.Collections.Specialized.StringCollection; ' ++ 'foreach ($x in $p) { [void]$c.Add([string]$x) }; ' ++ '[System.Windows.Forms.Clipboard]::SetFileDropList($c)'++/** PowerShell cold start is ~0.5–1.5 s; past this the copy is reported as failed, never hung. */+export const WINDOWS_FILE_DROP_TIMEOUT_MS = 5000++export type ExecFileLike = (+ file: string,+ args: string[],+ options: { timeout: number; windowsHide: boolean },+ callback: (error: Error | null) => void+) => {+ stdin?: { end(data: string): void; on?(event: 'error', listener: () => void): unknown } | null+} | undefined++export function windowsPowerShellPath(env: Record<string, string | undefined> = process.env): string {+ const root = env.SystemRoot || env.WINDIR || 'C:\\Windows'+ return win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')+}++export function writeWindowsFileDrop(+ paths: string[],+ deps: { execFile?: ExecFileLike; env?: Record<string, string | undefined> } = {}+): Promise<boolean> {+ const run = deps.execFile ?? (execFile as unknown as ExecFileLike)+ return new Promise((resolve) => {+ try {+ const child = run(+ windowsPowerShellPath(deps.env),+ ['-NoProfile', '-NonInteractive', '-STA', '-Command', WINDOWS_FILE_DROP_SCRIPT],+ { timeout: WINDOWS_FILE_DROP_TIMEOUT_MS, windowsHide: true },+ (error) => resolve(!error)+ )+ if (!child?.stdin) {+ resolve(false)+ return+ }+ // A spawn failure surfaces in the callback; swallow the paired EPIPE on stdin.+ child.stdin.on?.('error', () => undefined)+ child.stdin.end(JSON.stringify(paths))+ } catch {+ resolve(false)+ }+ })+}diff --git a/src/main/clipboard-files.test.ts b/src/main/clipboard-files.test.tsindex e0b4f05c2..a70a9532c 100644--- a/src/main/clipboard-files.test.ts+++ b/src/main/clipboard-files.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'import {FILE_LIST_PASTEBOARD_TYPE,fileListPropertyList,+ validateClipboardFilePaths,writeFilesToClipboard,type FileClipboardDependencies} from './clipboard-files'@@ -14,9 +15,9 @@ const dependencies = (overrides: Partial<FileClipboardDependencies> = {}): FileC})describe('writeFilesToClipboard', () => {- it('writes unique existing absolute files as a macOS filename pasteboard list', () => {+ it('writes unique existing absolute files as a macOS filename pasteboard list', async () => {const deps = dependencies()- expect(writeFilesToClipboard(['/tmp/a & b.png', '/tmp/a & b.png'], deps)).toBe(true)+ expect(await 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)@@ -24,33 +25,33 @@ describe('writeFilesToClipboard', () => {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('rejects unsupported platforms and any selection containing an invalid file', async () => {+ expect(await writeFilesToClipboard(['/tmp/a'], dependencies({ platform: 'linux' }))).toBe(false)+ expect(await writeFilesToClipboard(['/tmp/a'], dependencies({ isFile: () => false }))).toBe(false)+ expect(await writeFilesToClipboard(['/tmp/a', 'relative'], dependencies())).toBe(false)+ expect(await writeFilesToClipboard('not-an-array', dependencies())).toBe(false)})- it('caps the selection, counting only the files it kept', () => {+ it('caps the selection, counting only the files it kept', async () => {const paths = (n: number): string[] => Array.from({ length: n }, (_, i) => `/tmp/f${i}`)const at = dependencies()// Exactly at the cap is still one copy, not a truncated one.- expect(writeFilesToClipboard(paths(64), at)).toBe(true)+ expect(await writeFilesToClipboard(paths(64), at)).toBe(true)expect(vi.mocked(at.writeBuffer).mock.calls[0][1].toString().match(/<string>/g)).toHaveLength(64)// One over refuses outright — a partial pasteboard is worse than none, because the user// cannot see which files it dropped.- expect(writeFilesToClipboard(paths(65), dependencies())).toBe(false)+ expect(await writeFilesToClipboard(paths(65), dependencies())).toBe(false)// Duplicates are folded before the cap is charged, so 65 entries naming 64 files still fit.const dupes = dependencies()- expect(writeFilesToClipboard([...paths(64), '/tmp/f0'], dupes)).toBe(true)+ expect(await writeFilesToClipboard([...paths(64), '/tmp/f0'], dupes)).toBe(true)expect(vi.mocked(dupes.writeBuffer).mock.calls[0][1].toString().match(/<string>/g)).toHaveLength(64)})- it('fails closed when the OS clipboard write fails', () => {+ it('fails closed when the OS clipboard write fails', async () => {expect(- writeFilesToClipboard(+ await writeFilesToClipboard(['/tmp/a'],dependencies({writeBuffer: () => {@@ -62,8 +63,73 @@ describe('writeFilesToClipboard', () => {})})+describe('writeFilesToClipboard on win32', () => {+ const win = (overrides: Partial<FileClipboardDependencies> = {}): FileClipboardDependencies =>+ dependencies({+ platform: 'win32',+ writeWindowsFileDrop: vi.fn(async () => true),+ ...overrides+ })++ it('hands the validated, de-duplicated drive and UNC paths to the CF_HDROP writer', async () => {+ const deps = win()+ expect(+ await writeFilesToClipboard(['C:\\a b.png', 'C:\\a b.png', '\\\\srv\\share\\c.txt'], deps)+ ).toBe(true)+ expect(deps.writeWindowsFileDrop).toHaveBeenCalledWith(['C:\\a b.png', '\\\\srv\\share\\c.txt'])+ // The darwin plist is never written on Windows.+ expect(deps.writeBuffer).not.toHaveBeenCalled()+ })++ it('refuses relative, missing, over-cap or writer-less selections without writing', async () => {+ for (const [input, overrides] of [+ [['C:\\a', 'relative\\b'], {}],+ [['C:drive-relative'], {}],+ [['C:\\a'], { isFile: () => false }],+ [Array.from({ length: 65 }, (_, i) => `C:\\f${i}`), {}]+ ] as const) {+ const deps = win(overrides)+ expect(await writeFilesToClipboard(input, deps)).toBe(false)+ expect(deps.writeWindowsFileDrop).not.toHaveBeenCalled()+ }+ expect(await writeFilesToClipboard(['C:\\a'], dependencies({ platform: 'win32' }))).toBe(false)+ })++ it('reports the writer failing (or throwing) as a failed copy', async () => {+ expect(await writeFilesToClipboard(['C:\\a'], win({ writeWindowsFileDrop: async () => false }))).toBe(false)+ expect(+ await writeFilesToClipboard(+ ['C:\\a'],+ win({+ writeWindowsFileDrop: async () => {+ throw new Error('boom')+ }+ })+ )+ ).toBe(false)+ })++ it('never hands a win32 writer to darwin or linux', async () => {+ const mac = dependencies({ writeWindowsFileDrop: vi.fn(async () => true) })+ expect(await writeFilesToClipboard(['/tmp/a'], mac)).toBe(true)+ expect(mac.writeWindowsFileDrop).not.toHaveBeenCalled()+ const linux = dependencies({ platform: 'linux', writeWindowsFileDrop: vi.fn(async () => true) })+ expect(await writeFilesToClipboard(['/tmp/a'], linux)).toBe(false)+ expect(linux.writeWindowsFileDrop).not.toHaveBeenCalled()+ })+})++describe('validateClipboardFilePaths', () => {+ it('judges absoluteness in the reading platform\'s dialect', () => {+ expect(validateClipboardFilePaths(['/tmp/a'], 'darwin', () => true)).toEqual(['/tmp/a'])+ expect(validateClipboardFilePaths(['C:\\a'], 'darwin', () => true)).toBeNull()+ expect(validateClipboardFilePaths(['C:\\a'], 'win32', () => true)).toEqual(['C:\\a'])+ expect(validateClipboardFilePaths([], 'darwin', () => true)).toBeNull()+ })+})+describe('fileListPropertyList', () => {- it('escapes every XML-significant path character', () => {+ it('escapes every XML-significant path character', async () => {expect(fileListPropertyList([`/tmp/<a>\"'&`]).toString()).toContain('<a>"'&')diff --git a/src/main/clipboard-files.ts b/src/main/clipboard-files.tsindex bf514d0cf..6fdb9f7c8 100644--- a/src/main/clipboard-files.ts+++ b/src/main/clipboard-files.ts@@ -1,4 +1,4 @@-import { isAbsolute } from 'path'+import { posix, win32 } from 'path'export const FILE_LIST_PASTEBOARD_TYPE = 'NSFilenamesPboardType'const MAX_CLIPBOARD_FILES = 64@@ -7,6 +7,12 @@ export interface FileClipboardDependencies {platform: stringisFile(path: string): booleanwriteBuffer(format: string, buffer: Buffer): void+ /**+ * Windows leg: put a real CF_HDROP on the clipboard. `writeBuffer` cannot do it there —+ * Electron registers its format argument as a CUSTOM format name, and CF_HDROP is a predefined+ * format id, not a registerable name. Absent ⇒ Windows refuses, like every other platform.+ */+ writeWindowsFileDrop?(paths: string[]): Promise<boolean>}const escapeXml = (value: string): string =>@@ -28,34 +34,55 @@ export function fileListPropertyList(paths: string[]): Buffer {}/**- * 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.+ * Validate a renderer-supplied file selection. Inputs cross an IPC trust boundary, so paths are+ * capped, absolute-only (in the dialect of the platform that will read them — `path.win32` on+ * Windows, so drive and UNC paths validate there and only there), de-duplicated and re-checked+ * against the filesystem. All-or-nothing: `null` for any bad entry, so a multi-selection is never+ * silently truncated or partially copied.*/-export function writeFilesToClipboard(+export function validateClipboardFilePaths(input: unknown,- dependencies: FileClipboardDependencies-): boolean {- if (dependencies.platform !== 'darwin' || !Array.isArray(input)) return false+ platform: string,+ isFile: (path: string) => boolean+): string[] | null {+ if (!Array.isArray(input)) return null+ const isAbsolute = platform === 'win32' ? win32.isAbsolute : posix.isAbsoluteconst paths: string[] = []const seen = new Set<string>()for (const value of input) {- if (typeof value !== 'string' || !isAbsolute(value)) return false+ if (typeof value !== 'string' || !isAbsolute(value)) return nullif (seen.has(value)) continue- if (paths.length >= MAX_CLIPBOARD_FILES) return false+ if (paths.length >= MAX_CLIPBOARD_FILES) return nulltry {- if (!dependencies.isFile(value)) return false+ if (!isFile(value)) return null} catch {- return false+ return null}seen.add(value)paths.push(value)}- if (!paths.length) return false+ return paths.length ? paths : null+}++/**+ * Put existing local regular files on the OS clipboard as file references, so Finder / File+ * Explorer pastes the actual files. darwin writes the `NSFilenamesPboardType` plist; win32 hands+ * the validated list to `writeWindowsFileDrop` (CF_HDROP); every other platform refuses.+ */+export async function writeFilesToClipboard(+ input: unknown,+ dependencies: FileClipboardDependencies+): Promise<boolean> {+ const { platform } = dependencies+ if (platform !== 'darwin' && !(platform === 'win32' && dependencies.writeWindowsFileDrop)) {+ return false+ }+ const paths = validateClipboardFilePaths(input, platform, dependencies.isFile)+ if (!paths) return falsetry {+ if (platform === 'win32') return (await dependencies.writeWindowsFileDrop?.(paths)) === truedependencies.writeBuffer(FILE_LIST_PASTEBOARD_TYPE, fileListPropertyList(paths))return true} catch {diff --git a/src/main/index.ts b/src/main/index.tsindex 3372a392a..f84422a0a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -22,6 +22,7 @@ const logBuffer = new LogBuffer()installLogSink(logBuffer)import { nativeMux, setNativeWindowsAgentOptIn, useNativeSsh } from '../core/remote-ssh/native/native-runtime'import { writeFilesToClipboard } from './clipboard-files'+import { writeWindowsFileDrop } from './clipboard-files-win'import { pickProjectIcon } from './project-icon-upload'import { allowGuestNavigation } from './webview-nav'import { appEntryUrlFor, decideMainFrameNavigation, isSafeExternalUrl } from './navigation-guard'@@ -1726,7 +1727,8 @@ app.whenReady().then(async () => {writeFilesToClipboard(paths, {platform: process.platform,isFile: (path) => statSync(path).isFile(),- writeBuffer: (format, buffer) => clipboard.writeBuffer(format, buffer)+ writeBuffer: (format, buffer) => clipboard.writeBuffer(format, buffer),+ writeWindowsFileDrop: (paths) => writeWindowsFileDrop(paths)}))diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 011d2fd9e..ccfd62d60 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -60,7 +60,7 @@ import { FloatingEdge } from './FloatingEdge'import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'import { isBrowserRuntime } from '@renderer/bridge/runtime'import { WheelZoomBurstLimiter, clampWheelZoomSpeed, nextWheelZoom } from './wheel-zoom'-import { selectedLocalFilePaths } from './canvas-file-copy'+import { canCopyFilesToClipboard, selectedLocalFilePaths } from './canvas-file-copy'import {canvasImagePasteArmedAfterKey,canvasImportRefusal,@@ -300,7 +300,7 @@ import {requestTerminalFontZoom,type TerminalFontZoomRequest} from '../terminal/terminal-font-zoom'-import { isMacPlatform } from '@shared/platform-utils'+import { isMacPlatform, isWindowsPlatform } from '@shared/platform-utils'import {dispatchGlobalKeydown,type GlobalKeyEvent,@@ -9757,13 +9757,18 @@ export function Canvas() {//// Gated to where it can actually succeed, because the failure path raises a banner that// stays until dismissed — and before this feature the keystroke was a silent no-op, which- // is what every other machine must keep getting. `writeFilesToClipboard` is darwin-gated- // in main and the browser bridge stub answers false, so on a non-mac renderer (desktop OR- // Server Edition) this branch could only ever produce that banner, wearing macOS-specific- // copy on a Linux box. The board is an opaque overlay over the canvas, so a copy there- // would act on a selection the user cannot see (the canvas-only-shortcut discipline).+ // is what every other machine must keep getting. `writeFilesToClipboard` is darwin/win32-+ // gated in main and the browser bridge stub answers false, so elsewhere (Linux desktop, any+ // Server Edition) this branch could only ever produce that banner. The board is an opaque+ // overlay over the canvas, so a copy there would act on a selection the user cannot see+ // (the canvas-only-shortcut discipline).const projects = useProjects.getState()- if (!isMac || isGlobalKanbanOpen() || isKanbanOpen(projects.activeProjectId)) return false+ if (+ !canCopyFilesToClipboard({ mac: isMac, windows: isWindowsPlatform() }, isBrowserRuntime()) ||+ isGlobalKanbanOpen() ||+ isKanbanOpen(projects.activeProjectId)+ )+ return falseconst paths = selectedLocalFilePaths(nodesRef.current, {projectIsRelay: !!projects.getProject(projects.activeProjectId ?? '')?.remote})@@ -9775,7 +9780,7 @@ export function Canvas() {setCopyError(copied? null- : 'Copy failed — only existing local files can be copied from the macOS desktop app.'+ : 'Copy failed — only existing local files can be copied from the desktop app.')}).catch(() => setCopyError('Copy failed — the system clipboard is unavailable.'))diff --git a/src/renderer/canvas/canvas-file-copy.test.ts b/src/renderer/canvas/canvas-file-copy.test.tsindex 117b8348f..5341ed321 100644--- a/src/renderer/canvas/canvas-file-copy.test.ts+++ b/src/renderer/canvas/canvas-file-copy.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import type { CanvasNode } from '../state/workspace'-import { selectedLocalFilePaths } from './canvas-file-copy'+import { canCopyFilesToClipboard, selectedLocalFilePaths } from './canvas-file-copy'const node = (id: string,@@ -57,3 +57,16 @@ describe('selectedLocalFilePaths', () => {).toEqual([])})})++describe('canCopyFilesToClipboard', () => {+ it('is the macOS and Windows desktop app only', () => {+ expect(canCopyFilesToClipboard({ mac: true, windows: false }, false)).toBe(true)+ expect(canCopyFilesToClipboard({ mac: false, windows: true }, false)).toBe(true)+ expect(canCopyFilesToClipboard({ mac: false, windows: false }, false)).toBe(false)+ })++ it('never claims the keystroke in the Server Edition, whose bridge cannot write files', () => {+ expect(canCopyFilesToClipboard({ mac: true, windows: false }, true)).toBe(false)+ expect(canCopyFilesToClipboard({ mac: false, windows: true }, true)).toBe(false)+ })+})diff --git a/src/renderer/canvas/canvas-file-copy.ts b/src/renderer/canvas/canvas-file-copy.tsindex 42cf2c135..dd8fc1c96 100644--- a/src/renderer/canvas/canvas-file-copy.ts+++ b/src/renderer/canvas/canvas-file-copy.ts@@ -41,3 +41,17 @@ export function selectedLocalFilePaths(}return paths}++/**+ * Where ⌘/Ctrl+C on file-backed nodes can actually put FILES on the clipboard: the DESKTOP app on+ * macOS (pasteboard plist) and Windows (CF_HDROP). Everywhere else — Linux desktop, and the+ * Server Edition on any OS, whose bridge stub answers false — the keystroke stays the silent no-op+ * it always was, because the failure path raises a sticky banner.+ */+export function canCopyFilesToClipboard(+ viewer: { mac: boolean; windows: boolean },+ browserRuntime: boolean+): boolean {+ if (browserRuntime) return false+ return viewer.mac || viewer.windows+}