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): retry an unwritable project folder, and refuse image import on a relay tab
Claude Code517940300106
diff --git a/src/core/canvas-images.test.ts b/src/core/canvas-images.test.tsindex c1e5edf4c..0ced8e760 100644--- a/src/core/canvas-images.test.ts+++ b/src/core/canvas-images.test.ts@@ -1,10 +1,10 @@-import { describe, expect, it, beforeEach, afterEach } from 'vitest'+import { describe, expect, it, beforeEach, afterEach, vi } 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'+import { UPLOAD_MAX_BYTES, uploadsRoot } from './uploads'const png = Buffer.from('fake-png-bytes').toString('base64')@@ -86,16 +86,81 @@ describe('saveCanvasImage', () => {})it('answers null for bytes it will not store, rather than throwing', async () => {+ // null is the whole contract with the caller: it filters the path out and reports the loss,+ // so a throw here would take the other images in the same drop down with it.expect(await saveCanvasImage({ projectCwd, userDataDir, name: 'a.png', dataBase64: '' })).toBe(null)+ // Refused on the ENCODED length, before any decode — measuring it by allocating it is the+ // exact thing the limit exists to prevent, so the test must not allocate the payload either.expect(await saveCanvasImage({projectCwd,userDataDir,name: 'a.png',- dataBase64: 'x'.repeat(64 * 1024 * 1024 * 2)+ dataBase64: 'x'.repeat(Math.ceil(UPLOAD_MAX_BYTES * 1.4) + 1)})).toBe(null)+ // Nothing was left behind by either refusal.+ await expect(fs.readdir(projectImagesDir(projectCwd))).rejects.toThrow()+ })++ it('falls back to the app folder when the project folder will not take the file', async () => {+ // `.nodeterm` as a FILE reproduces ENOTDIR, which is the same shape as EACCES on a read-only+ // checkout, a root-owned `.nodeterm`, or a read-only mount. Before the retry this lost the+ // image silently — a regression against the pre-durability behavior, where the write went to+ // userData and essentially could not fail.+ await fs.writeFile(join(projectCwd, '.nodeterm'), 'not a directory')+ const path = await saveCanvasImage({+ projectCwd,+ 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('does not resurrect a project folder that has been deleted', async () => {+ await rm(projectCwd, { recursive: true, force: true })+ const path = await saveCanvasImage({+ projectCwd,+ userDataDir,+ name: 'shot.png',+ dataBase64: png+ })+ // Saved app-locally, and — the point — `mkdir -p` did not recreate the folder the user removed.+ expect(path).toBe(join(appImagesDir(userDataDir), 'shot.png'))+ await expect(fs.stat(projectCwd)).rejects.toThrow()+ })++ it('leaves no truncated file behind when the write fails partway', async () => {+ // `wx` creates the file and then writes it, so a disk that fills in between leaves a partial+ // image holding a name — indistinguishable from a whole one to whoever reads it next.+ const buf = Buffer.from('fake-png-bytes')+ const real = fs.writeFile+ // Faithful to the failure mode: the file IS created and partially written, and THEN the write+ // fails. Rejecting without creating anything would leave nothing for the cleanup to remove and+ // the assertion below would pass whether or not the cleanup exists.+ const writeFile = vi+ .spyOn(fs, 'writeFile')+ .mockImplementationOnce(async (target, _data, options) => {+ await real(target, 'partial', options)+ throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' })+ })+ const partial = join(projectImagesDir(projectCwd), 'shot.png')+ const path = await saveCanvasImage({+ projectCwd,+ userDataDir,+ name: 'shot.png',+ dataBase64: buf.toString('base64')+ })+ writeFile.mockRestore()+ // The project write failed, so it landed app-locally, whole...+ expect(path).toBe(join(appImagesDir(userDataDir), 'shot.png'))+ expect(await fs.readFile(path!, 'utf8')).toBe('fake-png-bytes')+ // ...and the half-written project file was removed rather than left holding the name.+ await expect(fs.readFile(partial, 'utf8')).rejects.toThrow()+ await expect(fs.readdir(projectImagesDir(projectCwd))).resolves.toEqual([])})})diff --git a/src/core/canvas-images.ts b/src/core/canvas-images.tsindex e701ad0bd..5963bca9b 100644--- a/src/core/canvas-images.ts+++ b/src/core/canvas-images.ts@@ -37,19 +37,24 @@ export interface CanvasImageTarget {}/**- * `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:+ * `projectCwd` is the project's LOCAL cwd, or undefined. Undefined covers three cases:** • 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.+ * • an SSH project — `<cwd>` is a path on the REMOTE host, while this write happens here, on the+ * machine the terminals run on (as `files.saveUpload` always has). Writing to the host would be+ * wrong anyway: the canvas opens an image node WITHOUT `sshFs`, so the node reads through the+ * local fs and would not be able to read its own file. App-local is the coherent answer;+ * • a project whose folder has been DELETED — see `saveCanvasImage`, which collapses it into this+ * branch rather than letting `mkdir -p` resurrect a directory the user removed.*- * 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`.+ * None of these is an error, so none refuses: the image is saved, it just cannot travel with the+ * project. The caller is told which happened via `inProject`.+ *+ * A RELAY TAB is deliberately NOT in that list — it is refused before it reaches here (see+ * `canvasImportRefusal` in renderer/canvas/canvas-image-import.ts). The reasoning above turns on+ * the node reading through the same fs this wrote to, and for a relay tab that is FALSE: the write+ * is the local preload's while `EditorNode` reads through the session api, i.e. the PEER's core.+ * Saving here would produce a node that asks another machine for a path only this one has.*/export function canvasImageTarget(projectCwd: string | undefined,@@ -60,10 +65,50 @@ export function canvasImageTarget(: { dir: appImagesDir(userDataDir), inProject: false }}+const isDir = async (p: string): Promise<boolean> => {+ try {+ return (await fs.stat(p)).isDirectory()+ } catch {+ return false+ }+}++/**+ * One write attempt into `dir`. Throws whatever the filesystem threw — the caller decides whether+ * that is worth a second directory. Resolves null only when the name collided every allowed time.+ */+async function writeInto(dir: string, safe: string, buf: Buffer): Promise<string | null> {+ await fs.mkdir(dir, { recursive: true })+ 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') continue+ // `wx` CREATED the file and then the write failed partway (a disk that filled between the+ // two). Nothing distinguishes a truncated image from a whole one to the reader, and the+ // name is now taken, so the remains are removed before the error propagates.+ await fs.rm(target, { force: true }).catch(() => undefined)+ throw err+ }+ }+ return null+}++const tryWrite = async (dir: string, safe: string, buf: Buffer): Promise<string | null> => {+ try {+ return await writeInto(dir, safe, buf)+ } catch {+ return null+ }+}+/*** 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.+ * it could not be written anywhere (too large, undecodable, or every candidate directory refused).+ * Never throws — the caller drops what it could not save, exactly like a failed drop, and tells+ * the user (an image that silently never appears is the failure this must not have).** 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@@ -76,28 +121,31 @@ export async function saveCanvasImage(opts: {name: stringdataBase64: string}): Promise<string | null> {+ // 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+ let buf: Buffertry {- // 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+ buf = Buffer.from(dataBase64, 'base64')} catch {return null}+ if (!buf.length || buf.length > UPLOAD_MAX_BYTES) return null+ const safe = safeUploadName(opts.name)++ // A project folder that is GONE takes the app-local branch instead of the project one:+ // `mkdir -p` would otherwise happily RESURRECT `<cwd>/.nodeterm/images` under a directory the+ // user deleted, leaving a lone skeleton of a project behind as a side effect of a paste.+ const cwd = opts.projectCwd && (await isDir(opts.projectCwd)) ? opts.projectCwd : undefined+ const target = canvasImageTarget(cwd, opts.userDataDir)+ const primary = await tryWrite(target.dir, safe, buf)+ if (primary || !target.inProject) return primary++ // The project folder exists but would not take the file: a read-only checkout or mount, a+ // root-owned `.nodeterm`, `.nodeterm` present as a FILE (ENOTDIR), a full disk. Storing it+ // app-locally costs the user only the ability to share it; refusing costs them the image. Note+ // this retry is what keeps the durable-storage decision from being a REGRESSION — before it, the+ // write went to userData, where it essentially could not fail.+ return tryWrite(appImagesDir(opts.userDataDir), safe, buf)}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex fb4276ea4..b46677da0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -38,6 +38,7 @@ import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'import { selectedLocalFilePaths } from './canvas-file-copy'import {canvasImagePasteArmedAfterKey,+ canvasImportRefusal,guardedCanvasImagePlacements,isCanvasImageDropTarget} from './canvas-image-import'@@ -2963,6 +2964,13 @@ export function Canvas() {async (files: File[], center: { x: number; y: number }, projectId: string) => {const images = canvasImageFiles(files)if (!images.length) return+ // A relay tab writes here and reads on the peer, so the node could never render its own+ // file — say so instead of creating it. Same fact, same source as the Cmd+C gate below.+ const refusal = canvasImportRefusal(!!useProjects.getState().getProject(projectId)?.remote)+ if (refusal) {+ setCopyError(refusal)+ return+ }const placements = await guardedCanvasImagePlacements(// 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@@ -2973,6 +2981,16 @@ export function Canvas() {center)placements.forEach(({ filePath, center: placement }) => openFile(filePath, placement))+ // Unsaveable files are dropped silently one layer down, and core already retried in a second+ // directory before giving up — so a shortfall here means the image is genuinely not on disk.+ // Saying nothing would leave the user watching for a node that is never coming. (A project+ // switch mid-save legitimately places nothing; that is the guard's job, not a failure.)+ const lost = images.length - placements.length+ if (lost > 0 && useProjects.getState().activeProjectId === projectId) {+ setCopyError(+ `Could not save ${lost === 1 ? 'the image' : `${lost} images`} — check that this project's folder is writable.`+ )+ }},[openFile])diff --git a/src/renderer/canvas/canvas-image-import.test.ts b/src/renderer/canvas/canvas-image-import.test.tsindex 2b2f84c8e..c5b69c9f3 100644--- a/src/renderer/canvas/canvas-image-import.test.ts+++ b/src/renderer/canvas/canvas-image-import.test.ts@@ -2,10 +2,20 @@import { describe, expect, it } from 'vitest'import {canvasImagePasteArmedAfterKey,+ canvasImportRefusal,guardedCanvasImagePlacements,isCanvasImageDropTarget} from './canvas-image-import'+describe('canvasImportRefusal', () => {+ it('refuses a relay tab, whose write and read land on different machines', () => {+ // The write is the LOCAL preload's, the node reads through the peer's core — so the node could+ // never render its own file. A message beats a broken node.+ expect(canvasImportRefusal(true)).toMatch(/remote tab/i)+ expect(canvasImportRefusal(false)).toBe(null)+ })+})+describe('isCanvasImageDropTarget', () => {it('accepts the real pane and rejects flow-wrap overlays and nodes', () => {const wrap = document.createElement('div')diff --git a/src/renderer/canvas/canvas-image-import.ts b/src/renderer/canvas/canvas-image-import.tsindex 859f25208..115299387 100644--- a/src/renderer/canvas/canvas-image-import.ts+++ b/src/renderer/canvas/canvas-image-import.ts@@ -9,6 +9,26 @@ export function isCanvasImageDropTarget(target: EventTarget | null, wrap: Elemen)}+/**+ * Why a canvas image import cannot proceed, or null when it may. One rule, one message, so the+ * drop path and the paste path cannot disagree about either.+ *+ * A RELAY TAB is refused because the two halves of the feature would land on different machines:+ * the write is `window.nodeTerminal.files.saveCanvasImage` — the LOCAL preload, even in a relay+ * tab — while `EditorNode` reads through the session api, i.e. the PEER's core. The bytes would sit+ * on this disk and the node would ask the peer for that path, producing a node that can never+ * render. Refusing is not a limitation dressed up as a feature: a clear message is strictly better+ * than a broken node, and it is the same fact (`Project.remote`), read the same way, that already+ * gates Cmd+C's file copy. Routing the write to the peer instead is a real feature — it also needs+ * the Finder-drop shortcut bypassed, since a local OS path is just as unreadable over there — and+ * no file write in this app crosses that boundary today.+ */+export function canvasImportRefusal(projectIsRelay: boolean): string | null {+ return projectIsRelay+ ? 'Images can’t be added to a remote tab’s canvas — the file would stay on this machine, where that canvas can’t read it.'+ : null+}+export interface CanvasImagePlacement {filePath: stringcenter: { x: number; y: number }diff --git a/src/renderer/terminal/file-drop.test.ts b/src/renderer/terminal/file-drop.test.tsindex 76159ebfb..d4dd0c083 100644--- a/src/renderer/terminal/file-drop.test.ts+++ b/src/renderer/terminal/file-drop.test.ts@@ -109,15 +109,20 @@ describe('localPathsForFiles', () => {expect(saveUpload).not.toHaveBeenCalled()})- it('reuses an Electron file path without shell escaping it', async () => {+ it('reuses an Electron file path without shell escaping it, and never calls the sink', async () => {+ const saveCanvasImage = vi.fn()vi.stubGlobal('window', {nodeTerminal: {getPathForFile: () => '/tmp/My image.png',- files: { saveUpload: vi.fn() }+ files: { saveUpload: vi.fn(), saveCanvasImage }}})const file = new File(['png'], 'My image.png', { type: 'image/png' })- expect(await localPathsForFiles([file])).toEqual(['/tmp/My image.png'])+ // A Finder drop already IS a file on this disk, so nothing is copied anywhere.+ expect(await localPathsForFiles([file], canvasImageSink('project-a'))).toEqual([+ '/tmp/My image.png'+ ])+ expect(saveCanvasImage).not.toHaveBeenCalled()})})diff --git a/src/renderer/terminal/file-drop.ts b/src/renderer/terminal/file-drop.tsindex cdcac22dc..2953340c6 100644--- a/src/renderer/terminal/file-drop.ts+++ b/src/renderer/terminal/file-drop.ts@@ -175,11 +175,10 @@ async function localFilesWithPaths(.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[],- sink: UploadSink = uploadsSink-): Promise<string[]> {+/** Resolve local/clipboard/browser files to raw local paths for non-terminal consumers. `sink` is+ * required: only the caller knows how long the returned path has to stay true, and defaulting it+ * to the 7-day staging area is exactly the wrong answer for the one caller there is. */+export async function localPathsForFiles(files: File[], sink: UploadSink): Promise<string[]> {return (await localFilesWithPaths(files, sink)).map((pair) => pair.path)}diff --git a/src/server/handlers/fs-handlers.test.ts b/src/server/handlers/fs-handlers.test.tsindex 0c0385bef..56cf6dadf 100644--- a/src/server/handlers/fs-handlers.test.ts+++ b/src/server/handlers/fs-handlers.test.ts@@ -4,13 +4,17 @@ import os from 'os'import path from 'path'import { ServerPlatform } from '../platform-server'import { registerFsHandlers } from '../../core/fs-handlers'+import { appImagesDir, projectImagesDir } from '../../core/canvas-images'import { IPC } from '../../shared/ipc'let dir: string, platform: ServerPlatform, ui: number+/** Project ids the injected `localProjectCwd` knows about, per test. */+let projectCwds: Record<string, string>beforeEach(() => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-fs-'))platform = new ServerPlatform({ userDataDir: dir, appVersion: '0' })- registerFsHandlers(platform)+ projectCwds = {}+ registerFsHandlers(platform, { localProjectCwd: (id) => projectCwds[id] })ui = platform.attach({ sendText: () => {}, sendBinary: () => {} })})afterEach(() => fs.rmSync(dir, { recursive: true, force: true }))@@ -44,6 +48,28 @@ describe('server fs handlers', () => {expect(await call(IPC.fsMkdir, nested)).toBe(true)expect(await call(IPC.fsExists, nested)).toBe(true)})+ // The canvas-image write directory is derived HERE, from this shell's own project registry —+ // the renderer sends a projectId and never names a path. These pin the injection itself: it is+ // one line per shell (src/main/index.ts and src/server/index.ts), and dropping either one sends+ // every image to the app folder with nothing else in the suite noticing.+ it('saveCanvasImage writes into the project cwd the shell resolved', async () => {+ const cwd = path.join(dir, 'proj')+ fs.mkdirSync(cwd)+ projectCwds['p1'] = cwd+ const data = Buffer.from('png').toString('base64')+ expect(await call(IPC.filesSaveCanvasImage, 'p1', 'shot.png', data)).toBe(+ path.join(projectImagesDir(cwd), 'shot.png')+ )+ })++ it('saveCanvasImage falls back to the app folder for a project the shell does not place', async () => {+ // An SSH project, a relay tab, or a cwd-less canvas: saved, never refused.+ const data = Buffer.from('png').toString('base64')+ expect(await call(IPC.filesSaveCanvasImage, 'unknown', 'shot.png', data)).toBe(+ path.join(appImagesDir(dir), 'shot.png')+ )+ })+it('quickOpen lists files under the root', async () => {fs.writeFileSync(path.join(dir, 'q.txt'), 'x')const files = (await call(IPC.filesQuickOpen, dir)) as string[]diff --git a/src/server/handlers/index.test.ts b/src/server/handlers/index.test.tsindex 32f8d3b01..f101a9492 100644--- a/src/server/handlers/index.test.ts+++ b/src/server/handlers/index.test.ts@@ -9,6 +9,7 @@ import { IPC } from '../../shared/ipc'import { DEFAULT_SETTINGS, type GitStatus } from '../../shared/types'import { initPlatform, resetPlatformForTests } from '../../core/platform'import { DownloadTickets } from '../../core/download-tickets'+import { projectImagesDir } from '../../core/canvas-images'let repo: string, platform: ServerPlatform, ui: numberbeforeEach(() => {@@ -64,6 +65,30 @@ describe('registerCoreHandlers (git)', () => {})})+describe('registerCoreHandlers (canvas images)', () => {+ it('forwards localProjectCwd, so an image lands in the project the SHELL resolved', async () => {+ // The dep is one line per shell (src/server/index.ts and src/main/index.ts) and nothing else+ // in the suite notices if it goes missing — every image would just quietly stop travelling+ // with its project. This pins the server's half; the desktop's is the matching line in+ // src/main/index.ts, which has no unit-testable seam (it is inside app.whenReady's bootstrap).+ resetPlatformForTests()+ const p2 = new ServerPlatform({ userDataDir: repo, appVersion: '0' })+ initPlatform(p2)+ registerCoreHandlers(p2, {+ getSettings: () => DEFAULT_SETTINGS,+ localProjectCwd: (id) => (id === 'p2' ? repo : undefined)+ })+ const ui2 = p2.attach({ sendText: () => {}, sendBinary: () => {} })+ const res = await p2.dispatch(ui2, {+ t: 'req',+ id: 1,+ method: IPC.filesSaveCanvasImage,+ args: ['p2', 'shot.png', Buffer.from('png').toString('base64')]+ })+ expect((res as { result: string }).result).toBe(path.join(projectImagesDir(repo), 'shot.png'))+ })+})+describe('registerCoreHandlers (download tickets)', () => {it('mints a redeemable ticket whose URL carries only the token', async () => {const tickets = new DownloadTickets()