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(canvas): add a trackpad-pan escape hatch, and store canvas images with the project

Claude Codedda3d9556a6e
diff --git a/src/core/canvas-images.test.ts b/src/core/canvas-images.test.ts
new file mode 100644
index 000000000..c1e5edf4c
--- /dev/null
+++ b/src/core/canvas-images.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it, beforeEach, afterEach } from 'vitest'
+import { promises as fs } from 'fs'
+import { mkdtemp, rm } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { appImagesDir, canvasImageTarget, projectImagesDir, saveCanvasImage } from './canvas-images'
+import { uploadsRoot } from './uploads'
+
+const png = Buffer.from('fake-png-bytes').toString('base64')
+
+let root: string
+let userDataDir: string
+let projectCwd: string
+
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'nt-canvas-images-'))
+ userDataDir = join(root, 'userData')
+ projectCwd = join(root, 'project')
+ await fs.mkdir(projectCwd, { recursive: true })
+})
+afterEach(() => rm(root, { recursive: true, force: true }))
+
+describe('canvasImageTarget', () => {
+ it('uses the project folder when it has a local cwd, and a durable app folder when it does not', () => {
+ expect(canvasImageTarget(projectCwd, userDataDir)).toEqual({
+ dir: projectImagesDir(projectCwd),
+ inProject: true
+ })
+ // No local cwd: an SSH project (its cwd is on the host), a relay tab, or an inline canvas.
+ expect(canvasImageTarget(undefined, userDataDir)).toEqual({
+ dir: appImagesDir(userDataDir),
+ inProject: false
+ })
+ })
+
+ it('never lands inside the swept uploads staging area', () => {
+ // The whole reason this module exists: a canvas image node is persisted, so its file must not
+ // sit where UPLOAD_TTL_MS deletes it after a week.
+ const sweptRoot = uploadsRoot(userDataDir)
+ expect(canvasImageTarget(projectCwd, userDataDir).dir.startsWith(sweptRoot)).toBe(false)
+ expect(canvasImageTarget(undefined, userDataDir).dir.startsWith(sweptRoot)).toBe(false)
+ })
+})
+
+describe('saveCanvasImage', () => {
+ it('writes into the project’s git-shared .nodeterm/images/', async () => {
+ const path = await saveCanvasImage({
+ projectCwd,
+ userDataDir,
+ name: 'shot.png',
+ dataBase64: png
+ })
+ expect(path).toBe(join(projectCwd, '.nodeterm', 'images', 'shot.png'))
+ expect(await fs.readFile(path!, 'utf8')).toBe('fake-png-bytes')
+ })
+
+ it('falls back to the app folder for a project with no local cwd, instead of refusing', async () => {
+ const path = await saveCanvasImage({ userDataDir, name: 'shot.png', dataBase64: png })
+ expect(path).toBe(join(appImagesDir(userDataDir), 'shot.png'))
+ expect(await fs.readFile(path!, 'utf8')).toBe('fake-png-bytes')
+ })
+
+ it('never clobbers an existing image, and keeps the extension on the renamed one', async () => {
+ const first = await saveCanvasImage({ projectCwd, userDataDir, name: 'shot.png', dataBase64: png })
+ const second = await saveCanvasImage({
+ projectCwd,
+ userDataDir,
+ name: 'shot.png',
+ dataBase64: Buffer.from('second').toString('base64')
+ })
+ expect(first).toBe(join(projectCwd, '.nodeterm', 'images', 'shot.png'))
+ expect(second).toBe(join(projectCwd, '.nodeterm', 'images', 'shot (2).png'))
+ expect(await fs.readFile(first!, 'utf8')).toBe('fake-png-bytes')
+ expect(await fs.readFile(second!, 'utf8')).toBe('second')
+ })
+
+ it('cannot be steered out of the images directory by the pasted name', async () => {
+ const path = await saveCanvasImage({
+ projectCwd,
+ userDataDir,
+ name: '../../.bashrc',
+ dataBase64: png
+ })
+ expect(path).toBe(join(projectCwd, '.nodeterm', 'images', '.bashrc'))
+ await expect(fs.readFile(join(root, '.bashrc'), 'utf8')).rejects.toThrow()
+ })
+
+ it('answers null for bytes it will not store, rather than throwing', async () => {
+ expect(await saveCanvasImage({ projectCwd, userDataDir, name: 'a.png', dataBase64: '' })).toBe(
+ null
+ )
+ expect(
+ await saveCanvasImage({
+ projectCwd,
+ userDataDir,
+ name: 'a.png',
+ dataBase64: 'x'.repeat(64 * 1024 * 1024 * 2)
+ })
+ ).toBe(null)
+ })
+})
diff --git a/src/core/canvas-images.ts b/src/core/canvas-images.ts
new file mode 100644
index 000000000..e701ad0bd
--- /dev/null
+++ b/src/core/canvas-images.ts
@@ -0,0 +1,103 @@
+// Where an image pasted or dropped ONTO THE CANVAS is written.
+//
+// This is deliberately NOT `core/uploads.ts`. That directory is a staging area for a paste into a
+// terminal — the path is consumed within seconds and swept after `UPLOAD_TTL_MS` (7 days), which
+// is right for a path that was pasted into a prompt and wrong for a canvas image node: the node is
+// persisted in `project.json`, so after a week the canvas kept a node pointing at a file the
+// sweeper had deleted. Whatever holds the file has to be at least as durable as the thing that
+// remembers it.
+//
+// So a project with a local cwd gets `<cwd>/.nodeterm/images/`, beside the `project.json` that
+// names the node. That folder is already the git-shared one (project.json, board-log.jsonl), so
+// the image travels to everyone who clones the repo — which is the point: a canvas that arrives
+// with broken image nodes is a canvas that did not arrive.
+//
+// Everything else falls back to `<userData>/canvas-images/` — durable (no sweeper walks it) but
+// local to this machine. See `canvasImageTarget` for exactly which cases, and why.
+
+import { promises as fs } from 'fs'
+import { join } from 'path'
+import { candidateName } from './download-name'
+import { UPLOAD_MAX_BYTES, safeUploadName } from './uploads'
+
+/** Beside project.json, in the git-shared folder — so the image travels with the canvas. */
+export const projectImagesDir = (projectCwd: string): string =>
+ join(projectCwd, '.nodeterm', 'images')
+
+/** The fallback for a project with no local cwd. Outside `uploads/`, so no sweeper touches it. */
+export const appImagesDir = (userDataDir: string): string => join(userDataDir, 'canvas-images')
+
+/** Give up rather than spin: 200 files literally named `shot.png` is not a collision any more. */
+const MAX_COLLISION_ATTEMPTS = 200
+
+export interface CanvasImageTarget {
+ dir: string
+ /** True when the file landed in the project (and will therefore travel with it). */
+ inProject: boolean
+}
+
+/**
+ * `projectCwd` is the project's LOCAL cwd, or undefined. Undefined covers three cases, and the
+ * answer is the same for all of them because in each one there is no local directory that both
+ * this machine can write and the image node can later read:
+ *
+ * • a cwd-less / inline canvas — there is no project folder at all;
+ * • an SSH project — `<cwd>` is a path on the REMOTE host, and `files.saveUpload` has always
+ * written on the machine the terminals run on, i.e. here. The image node itself reads locally
+ * (the canvas opens it without `sshFs`), so writing the bytes to the host would produce a node
+ * that cannot read its own file;
+ * • a relay tab — not in this machine's workspace index at all.
+ *
+ * None of these is an error, so none of them refuses: the image is still saved, just somewhere
+ * that only this machine can see. The caller is told which happened via `inProject`.
+ */
+export function canvasImageTarget(
+ projectCwd: string | undefined,
+ userDataDir: string
+): CanvasImageTarget {
+ return projectCwd
+ ? { dir: projectImagesDir(projectCwd), inProject: true }
+ : { dir: appImagesDir(userDataDir), inProject: false }
+}
+
+/**
+ * Write base64 `data` into the project's image folder and resolve its ABSOLUTE path, or null when
+ * it could not be written (too large, undecodable, unwritable, or a name that collided 200 times).
+ * Never throws — the caller drops what it could not save, exactly like a failed drop.
+ *
+ * The name is basenamed by `safeUploadName` before it is joined, so a pasted `../../.bashrc`
+ * cannot escape the directory, and the write is an EXCLUSIVE create (`wx`) walked through
+ * `candidateName` — so a second `shot.png` becomes `shot (2).png` instead of overwriting the
+ * first, and there is no stat-then-write window for two pastes to both win.
+ */
+export async function saveCanvasImage(opts: {
+ projectCwd?: string
+ userDataDir: string
+ name: string
+ dataBase64: string
+}): Promise<string | null> {
+ try {
+ // Guard the ENCODED length first: decoding a hostile 2 GB string to measure it is the
+ // allocation this limit exists to prevent (same rule as core/uploads.ts).
+ const { dataBase64 } = opts
+ if (typeof dataBase64 !== 'string' || dataBase64.length > UPLOAD_MAX_BYTES * 1.4) return null
+ const buf = Buffer.from(dataBase64, 'base64')
+ if (!buf.length || buf.length > UPLOAD_MAX_BYTES) return null
+
+ const { dir } = canvasImageTarget(opts.projectCwd, opts.userDataDir)
+ await fs.mkdir(dir, { recursive: true })
+ const safe = safeUploadName(opts.name)
+ for (let attempt = 1; attempt <= MAX_COLLISION_ATTEMPTS; attempt++) {
+ const target = join(dir, candidateName(safe, attempt))
+ try {
+ await fs.writeFile(target, buf, { flag: 'wx' })
+ return target
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') throw err
+ }
+ }
+ return null
+ } catch {
+ return null
+ }
+}
diff --git a/src/core/fs-handlers.ts b/src/core/fs-handlers.ts
index a61b50bae..514a9c58a 100644
--- a/src/core/fs-handlers.ts
+++ b/src/core/fs-handlers.ts
@@ -1,6 +1,7 @@
import type { CorePlatform } from './platform'
import * as fsOps from './fs-ops'
import { saveUpload } from './uploads'
+import { saveCanvasImage } from './canvas-images'
import { IPC } from '../shared/ipc'
import type { DownloadTicket } from '../shared/types'
@@ -22,6 +23,15 @@ export function registerFsHandlers(
* rather than as "not offered here".
*/
issueDownloadTicket?: (path: string) => Promise<DownloadTicket | null>
+ /**
+ * The project's LOCAL cwd, or undefined for an SSH project / relay tab / cwd-less canvas.
+ * Injected rather than taken from the caller because the renderer sends only a `projectId`:
+ * the write path is always derived here, from this shell's own workspace index, so a canvas
+ * image can never be aimed at a directory the renderer names. (Same discipline as
+ * `registerBoardLogHandlers` — see core/board-log-handlers.ts.) Absent ⇒ every project takes
+ * the durable app-local fallback, which is a coherent degrade, not a failure.
+ */
+ localProjectCwd?: (projectId: string) => string | undefined
} = {}
): void {
platform.handle(IPC.fsList, (dirPath: string) => fsOps.listDir(dirPath))
@@ -38,6 +48,18 @@ export function registerFsHandlers(
platform.handle(IPC.filesSaveUpload, (name: string, dataBase64: string) =>
saveUpload(platform.userDataDir, name, dataBase64)
)
+ // A canvas image node is persisted, so its bytes go somewhere equally durable — the project's
+ // own `.nodeterm/images/` when it has one. See core/canvas-images.ts for the fallbacks.
+ platform.handle(
+ IPC.filesSaveCanvasImage,
+ (projectId: string, name: string, dataBase64: string) =>
+ saveCanvasImage({
+ projectCwd: deps.localProjectCwd?.(projectId),
+ userDataDir: platform.userDataDir,
+ name,
+ dataBase64
+ })
+ )
platform.handle(IPC.filesDownloadTicket, (p: string) =>
deps.issueDownloadTicket ? deps.issueDownloadTicket(p) : Promise.resolve(null)
)
diff --git a/src/main/index.ts b/src/main/index.ts
index 9a5ee521d..5f41257fb 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -784,7 +784,12 @@ app.whenReady().then(async () => {
// The Explorer/Editor fs surface: ONE registrar (core/fs-handlers.ts) shared by this shell and
// the Server Edition, over the same pure core/fs-ops — so local, browser and peer filesystem
// behaviour cannot drift. Registered on the platform, so a remote tab's Explorer/editor works.
- registerFsHandlers(corePlatform)
+ // `localProjectCwd` is how a canvas image finds the project's own `.nodeterm/images/`. It
+ // answers undefined for an SSH project (its cwd is on the host, and the image node reads
+ // locally) and for a relay tab (not in this index at all) — both take the app-local fallback.
+ registerFsHandlers(corePlatform, {
+ localProjectCwd: (projectId: string) => workspaceStore.localCwdForProject(projectId)
+ })
const githubSecret = new ElectronGitHubSecretStore(app.getPath('userData'), safeStorage)
const github = registerGitHubIntegration({
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 61faf5e78..22fabf38d 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -326,7 +326,9 @@ const api: NodeTerminalApi = {
// already on this machine" (local project).
downloadTicket: (p: string) => ipcRenderer.invoke(IPC.filesDownloadTicket, p),
saveUpload: (name: string, dataBase64: string) =>
- ipcRenderer.invoke(IPC.filesSaveUpload, name, dataBase64)
+ ipcRenderer.invoke(IPC.filesSaveUpload, name, dataBase64),
+ saveCanvasImage: (projectId: string, name: string, dataBase64: string) =>
+ ipcRenderer.invoke(IPC.filesSaveCanvasImage, projectId, name, dataBase64)
},
updates: {
onAvailable: (listener) => {
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index ac270a552..1e619ce25 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -456,7 +456,13 @@ export function buildFilesApi(
// Also real, and the direction that matters here: the browser holds the bytes, the terminal
// runs on the server, so a pasted image only becomes nameable once the server has written it.
saveUpload: (name, dataBase64) =>
- client.request(IPC.filesSaveUpload, name, dataBase64) as Promise<string | null>
+ client.request(IPC.filesSaveUpload, name, dataBase64) as Promise<string | null>,
+ // Real too, and for the same reason: the browser holds the bytes and the project folder is on
+ // the server, so only the server can put a canvas image where the canvas will find it again.
+ saveCanvasImage: (projectId, name, dataBase64) =>
+ client.request(IPC.filesSaveCanvasImage, projectId, name, dataBase64) as Promise<
+ string | null
+ >
}
const context: ContextApi = {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a354701e4..fb4276ea4 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -34,7 +34,7 @@ import {
wakeHibernatedNode
} from '../nodes/TerminalNode'
import { solveFitPadding } from './fit-view'
-import { MacWheelGestureRouter } from './wheel-gesture'
+import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'
import { selectedLocalFilePaths } from './canvas-file-copy'
import {
canvasImagePasteArmedAfterKey,
@@ -213,6 +213,7 @@ import { boundGroups, scmScopes, defaultScmScope, selectedScmGroupId } from '@sh
import { hintLabel } from '@shared/platform-utils'
import {
canvasImageFiles,
+ canvasImageSink,
clipboardImages,
localPathsForFiles,
pasteHasText,
@@ -2559,6 +2560,9 @@ export function Canvas() {
// 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.wheelZoom
+ // The escape hatch, resolved ONCE: the router and React Flow's panOnScroll below must agree, or
+ // a gesture neither of them pans is a gesture that does nothing.
+ const trackpadRouting = trackpadRoutingEnabled(isMac, settings.trackpadPan)
useEffect(() => {
const wrap = flowWrapRef.current
if (!wrap) return
@@ -2574,7 +2578,8 @@ export function Canvas() {
const overNativeScrollable = (): boolean => (scroller ??= !!target?.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 (wheelRouting.destination(e, trackpadRouting, overNativeScrollable) === 'flow-pan')
+ return
// pinch (ctrl+wheel) / Cmd/Ctrl+scroll always zoom; plain wheel only when opted in
if (!wheelZoom) return
if (overNativeScrollable()) return
@@ -2594,7 +2599,7 @@ export function Canvas() {
}
wrap.addEventListener('wheel', onWheel, { capture: true, passive: false })
return () => wrap.removeEventListener('wheel', onWheel, { capture: true })
- }, [getViewport, setViewport, wheelZoom, canvasLocked])
+ }, [getViewport, setViewport, wheelZoom, trackpadRouting, canvasLocked])
// Double-clicking EMPTY canvas pulls back to the overview zoom — the inverse of the node
// double-click, which frames one node. A fixed zoom, not "the camera the last focus came from":
@@ -2959,7 +2964,10 @@ export function Canvas() {
const images = canvasImageFiles(files)
if (!images.length) return
const placements = await guardedCanvasImagePlacements(
- () => localPathsForFiles(images),
+ // Into the PROJECT's own `.nodeterm/images/`, not the 7-day uploads staging area: the node
+ // that names this file is persisted in project.json, so the file has to outlive a week and
+ // travel to whoever clones the repo.
+ () => localPathsForFiles(images, canvasImageSink(projectId)),
projectId,
() => useProjects.getState().activeProjectId,
center
@@ -8401,7 +8409,7 @@ export function Canvas() {
? [0, 1]
: [1]
}
- panOnScroll={canvasLocked ? false : isMac || !wheelZoom}
+ panOnScroll={canvasLocked ? false : trackpadRouting || !wheelZoom}
zoomOnScroll={false}
zoomOnPinch={false}
// Off: a pane double-click is the overview-zoom gesture (see PANE_OVERVIEW_ZOOM) and a
diff --git a/src/renderer/canvas/wheel-gesture.test.ts b/src/renderer/canvas/wheel-gesture.test.ts
index 90a831179..48fad63e3 100644
--- a/src/renderer/canvas/wheel-gesture.test.ts
+++ b/src/renderer/canvas/wheel-gesture.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { MacWheelGestureRouter } from './wheel-gesture'
+import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'
const gesture = (
deltaY: number,
@@ -59,6 +59,24 @@ describe('MacWheelGestureRouter', () => {
expect(router.destination(gesture(75), true, no, 1100)).toBe('flow-pan')
})
+ it('hands every gesture back to the zoom path once the escape hatch is engaged', () => {
+ // trackpadPan off: `mac` is false for the router whatever machine this is, so nothing is
+ // ever routed to flow-pan and settings.wheelZoom alone decides — the pre-router behavior.
+ expect(trackpadRoutingEnabled(true, true)).toBe(true)
+ expect(trackpadRoutingEnabled(true, false)).toBe(false)
+ expect(trackpadRoutingEnabled(false, true)).toBe(false)
+
+ const hatch = trackpadRoutingEnabled(true, false)
+ const router = new MacWheelGestureRouter()
+ // A precise-pixel MOUSE (Magic Mouse, MX Master) emits exactly what a trackpad emits, so it
+ // classifies as one — this is the user's only way back to wheel zoom, and it must hold for a
+ // whole gesture, not just its first packet.
+ expect(router.destination(gesture(6.25), hatch, no, 1000)).toBe('native')
+ expect(router.destination(gesture(4.5), hatch, no, 1050)).toBe('native')
+ expect(router.destination(gesture(75), hatch, yes, 1100)).toBe('native')
+ expect(router.shouldPan(gesture(6.25), hatch, 1150)).toBe(false)
+ })
+
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)
diff --git a/src/renderer/canvas/wheel-gesture.ts b/src/renderer/canvas/wheel-gesture.ts
index 6f37fdd0c..3228653c4 100644
--- a/src/renderer/canvas/wheel-gesture.ts
+++ b/src/renderer/canvas/wheel-gesture.ts
@@ -4,6 +4,20 @@ type WheelGesture = Pick<WheelEvent, 'ctrlKey' | 'metaKey' | 'deltaMode' | 'delt
export type MacWheelDestination = 'flow-pan' | 'native'
+/**
+ * Whether the trackpad override is live at all — the `mac` argument every method below takes.
+ *
+ * Two reasons it must be one named expression rather than an `isMac &&` at each call site: the
+ * router and React Flow's own `panOnScroll` have to agree exactly (disagreeing means a gesture
+ * that neither of them pans), and `trackpadPan` is the user's ESCAPE HATCH. Turning it off
+ * restores the pre-router behavior on macOS — `wheelZoom` alone decides, and a plain wheel zooms.
+ * That is the recourse for a precise-pixel MOUSE (Magic Mouse, MX Master), whose deltas are
+ * indistinguishable from a trackpad's here: it classifies as a trackpad and would otherwise have
+ * no way back to wheel zoom.
+ */
+export const trackpadRoutingEnabled = (mac: boolean, trackpadPan: boolean): boolean =>
+ mac && trackpadPan
+
const TRACKPAD_SEQUENCE_MS = 500
const MOUSE_WHEEL_NOTCH = 120
const LARGE_PIXEL_DELTA = 40
diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsx
index 20fb761bd..a4a920f45 100644
--- a/src/renderer/components/settings/sections/BehaviorSection.tsx
+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx
@@ -25,6 +25,10 @@ const ROWS = {
keywords: ['sidebar', 'sessions', 'collapse', 'expand', 'project', 'switch']
},
wheelZoom: { title: 'Scroll wheel zooms', keywords: ['zoom', 'wheel', 'scroll', 'mouse', 'pan'] },
+ trackpadPan: {
+ title: 'Trackpad scroll pans',
+ keywords: ['trackpad', 'pan', 'scroll', 'zoom', 'magic', 'mouse', 'two-finger', 'macos']
+ },
dragMode: {
title: 'Canvas left-drag',
keywords: ['pan', 'drag', 'select', 'canvas', 'mouse', 'grab', 'figma', 'miro']
@@ -159,6 +163,21 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.
}
/>
</SearchableRow>
+ <SearchableRow {...ROWS.trackpadPan}>
+ <FieldRow
+ label="Trackpad scroll pans"
+ description={hintLabel(
+ 'macOS: a two-finger trackpad scroll pans the canvas even with wheel zoom on. Turn off if a precise-pixel mouse (Magic Mouse, MX) pans when you meant to zoom.'
+ )}
+ control={
+ <Switch
+ checked={settings.trackpadPan}
+ onChange={(v) => update({ trackpadPan: v })}
+ ariaLabel="Trackpad scroll pans"
+ />
+ }
+ />
+ </SearchableRow>
<SearchableRow {...ROWS.dragMode}>
<FieldRow
label="Canvas left-drag"
diff --git a/src/renderer/terminal/file-drop.test.ts b/src/renderer/terminal/file-drop.test.ts
index cbdb1e33c..76159ebfb 100644
--- a/src/renderer/terminal/file-drop.test.ts
+++ b/src/renderer/terminal/file-drop.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, afterEach, vi } from 'vitest'
import {
canvasImageFiles,
+ canvasImageSink,
clipboardImages,
escapeDroppedPath,
localPathsForFiles,
@@ -75,6 +76,39 @@ describe('canvasImageFiles', () => {
describe('localPathsForFiles', () => {
afterEach(() => vi.unstubAllGlobals())
+ it('routes pathless canvas bytes to the project image store, not the uploads staging area', async () => {
+ const saveUpload = vi.fn()
+ const saveCanvasImage = vi.fn().mockResolvedValue('/proj/.nodeterm/images/pasted.png')
+ // The suite runs on the node environment, which has no FileReader; only the base64 handoff
+ // matters here, so the read is the smallest stand-in that produces one.
+ vi.stubGlobal(
+ 'FileReader',
+ class {
+ onload: (() => void) | null = null
+ onerror: (() => void) | null = null
+ result: string | null = null
+ readAsDataURL(): void {
+ this.result = 'data:image/png;base64,cG5n'
+ this.onload?.()
+ }
+ }
+ )
+ vi.stubGlobal('window', {
+ nodeTerminal: {
+ // A clipboard screenshot: no OS path, so the sink is the only thing that decides where it
+ // lands — and a canvas node outlives the 7-day uploads sweep.
+ getPathForFile: () => null,
+ files: { saveUpload, saveCanvasImage }
+ }
+ })
+ const file = new File(['png'], 'pasted.png', { type: 'image/png' })
+ expect(await localPathsForFiles([file], canvasImageSink('project-a'))).toEqual([
+ '/proj/.nodeterm/images/pasted.png'
+ ])
+ expect(saveCanvasImage).toHaveBeenCalledWith('project-a', 'pasted.png', expect.any(String))
+ expect(saveUpload).not.toHaveBeenCalled()
+ })
+
it('reuses an Electron file path without shell escaping it', async () => {
vi.stubGlobal('window', {
nodeTerminal: {
diff --git a/src/renderer/terminal/file-drop.ts b/src/renderer/terminal/file-drop.ts
index 5d6db3b0b..cdcac22dc 100644
--- a/src/renderer/terminal/file-drop.ts
+++ b/src/renderer/terminal/file-drop.ts
@@ -139,24 +139,48 @@ const readAsBase64 = (file: File): Promise<string | null> =>
* anywhere, and a browser client's file lives on a different machine entirely — so the bytes are
* written into the managed uploads dir over there and THAT path is what the terminal gets.
*/
-async function localPathFor(file: File): Promise<string | null> {
+/**
+ * Where bytes with no usable path get written. The default is the managed uploads staging area,
+ * which is right for a terminal paste — the path is consumed within seconds. A CANVAS image is
+ * remembered in project.json instead, so it passes a sink that writes somewhere equally durable
+ * (`canvasImageSink`); the choice belongs to the caller because only it knows how long the path
+ * has to stay true.
+ */
+export type UploadSink = (name: string, dataBase64: string) => Promise<string | null>
+
+const uploadsSink: UploadSink = (name, data) => window.nodeTerminal.files.saveUpload(name, data)
+
+/** Store into the project's own `.nodeterm/images/` — see core/canvas-images.ts for the fallbacks
+ * (SSH project / relay tab / cwd-less canvas all land in a durable app-local folder instead). */
+export const canvasImageSink =
+ (projectId: string): UploadSink =>
+ (name, data) =>
+ window.nodeTerminal.files.saveCanvasImage(projectId, name, data)
+
+async function localPathFor(file: File, sink: UploadSink): Promise<string | null> {
const direct = window.nodeTerminal.getPathForFile(file)
if (direct) return direct
const data = await readAsBase64(file)
if (!data) return null
- return window.nodeTerminal.files.saveUpload(uploadNameFor(file), data).catch(() => null)
+ return sink(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)))
+async function localFilesWithPaths(
+ files: File[],
+ sink: UploadSink
+): Promise<Array<{ file: File; path: string }>> {
+ const local = await Promise.all(files.map((f) => localPathFor(f, sink).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)
+export async function localPathsForFiles(
+ files: File[],
+ sink: UploadSink = uploadsSink
+): Promise<string[]> {
+ return (await localFilesWithPaths(files, sink)).map((pair) => pair.path)
}
/**
@@ -169,7 +193,7 @@ export async function droppedPaths(
files: File[],
opts: { sshRemoteTmux: boolean; projectId: string }
): Promise<string[]> {
- const pairs = await localFilesWithPaths(files)
+ const pairs = await localFilesWithPaths(files, uploadsSink)
if (!opts.sshRemoteTmux) return pairs.map((p) => escapeDroppedPath(p.path))
const uploaded = await Promise.all(
pairs.map((p) =>
diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.ts
index 4e30b94ba..911cd103c 100644
--- a/src/server/handlers/index.ts
+++ b/src/server/handlers/index.ts
@@ -20,7 +20,12 @@ import { IPC } from '../../shared/ipc'
* routing on desktop, which the server edition does not have (terminals are local). */
export function registerCoreHandlers(
platform: ServerPlatform,
- deps: { getSettings: () => Settings; downloadTickets?: DownloadTickets }
+ deps: {
+ getSettings: () => Settings
+ downloadTickets?: DownloadTickets
+ /** See fs-handlers' dep of the same name — the canvas-image write directory. */
+ localProjectCwd?: (projectId: string) => string | undefined
+ }
): { gitService: GitService } {
// Explorer downloads: mint a one-shot ticket over this (authenticated) channel; the transfer
// itself is a plain HTTP GET the browser performs (src/server/download.ts). Statting here keeps
@@ -38,7 +43,8 @@ export function registerCoreHandlers(
const token = downloadTickets.issue(p, dir)
return { url: `${DOWNLOAD_PATH}?t=${encodeURIComponent(token)}`, name: downloadName(p, dir) }
}
- : undefined
+ : undefined,
+ localProjectCwd: deps.localProjectCwd
})
const gitService = new GitService()
diff --git a/src/server/index.ts b/src/server/index.ts
index b83705e52..e07c17e5a 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -223,7 +223,8 @@ export async function startServer(
const downloadTickets = new DownloadTickets()
const { gitService } = registerCoreHandlers(platform, {
getSettings: () => settingsStore.get(),
- downloadTickets
+ downloadTickets,
+ localProjectCwd: (projectId: string) => workspaceStore.localCwdForProject(projectId)
})
const github = registerGitHubIntegration({
platform,
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index a9c7c1ad3..28cad05eb 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -218,6 +218,8 @@ export const IPC = {
filesDownloadTicket: 'files:download-ticket',
/** Persist pasted/dropped bytes that have no path here, and answer their absolute path. */
filesSaveUpload: 'files:save-upload',
+ /** Write a canvas image into the project's own `.nodeterm/images/` (see core/canvas-images.ts). */
+ filesSaveCanvasImage: 'files:save-canvas-image',
settingsLoad: 'settings:load',
settingsSave: 'settings:save',
sshList: 'ssh:list',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e221dceea..e11b56dad 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -724,6 +724,15 @@ export interface FilesApi {
* (too large, unwritable); callers drop that file the way a failed drop does.
*/
saveUpload(name: string, dataBase64: string): Promise<string | null>
+ /**
+ * Persist raw bytes (base64) as a CANVAS image and resolve its ABSOLUTE path. Unlike
+ * `saveUpload` the file is durable: a canvas image node is persisted in `project.json`, so its
+ * file cannot live in a staging area that is swept after a week. The directory is derived from
+ * `projectId` on the receiving side — the caller never names a path — and is the project's own
+ * git-shared `.nodeterm/images/` when it has a local cwd, else a durable app-local folder.
+ * Resolves null when it could not be written; callers drop that file like a failed drop.
+ */
+ saveCanvasImage(projectId: string, name: string, dataBase64: string): Promise<string | null>
}
export interface MediaApi {
@@ -867,6 +876,10 @@ export interface Settings {
* 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
+ /** macOS only: a two-finger trackpad scroll pans the canvas, independently of `wheelZoom`
+ * (see canvas/wheel-gesture.ts). Off restores the pre-router behavior — `wheelZoom` alone
+ * decides — which is also the recourse for a precise-pixel MOUSE that reads as a trackpad. */
+ trackpadPan: 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
* directly (grab cursor), for mouse users who pan constantly; box-select then moves to
@@ -1055,6 +1068,7 @@ export const DEFAULT_SETTINGS: Settings = {
doubleClickFocus: true,
terminalMiddleClickPaste: false,
wheelZoom: false,
+ trackpadPan: true,
canvasDragMode: 'select',
browserMemorySaver: true,
accent: '#0a84ff',