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(b5): remote filesystem (explorer + editor over relay)

enesb4b357ce568e
diff --git a/src/main/fs-ops.ts b/src/main/fs-ops.ts
new file mode 100644
index 000000000..b1f402e98
--- /dev/null
+++ b/src/main/fs-ops.ts
@@ -0,0 +1,86 @@
+// Shared filesystem operations (main process).
+//
+// The single source of truth for the app's `fs.*` reads/writes. BOTH the local `fs:*` IPC
+// handlers (`index.ts`, used by the local Explorer/Editor) AND the remote `fs.*` RPC handlers
+// (`remote/host-service.ts`, used by a client's Explorer/Editor over the relay) call these, so
+// the local and remote filesystem behaviour stay byte-for-byte identical (DRY).
+//
+// Each helper is error-tolerant by design: the renderer's `FsApi` contract treats failures as
+// empty/false rather than throwing, so a missing file or unreadable dir degrades gracefully.
+
+import { promises as fs } from 'fs'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import type { DirEntry } from '../shared/types'
+
+const run = promisify(execFile)
+
+/**
+ * List a directory: folders first then files (alphabetical), `.git` hidden, git-ignored entries
+ * flagged so the explorer can dim them. Returns `[]` on any error.
+ */
+export async function listDir(dirPath: string): Promise<DirEntry[]> {
+ try {
+ const dirents = await fs.readdir(dirPath, { withFileTypes: true })
+ const entries: DirEntry[] = dirents
+ .filter((e) => e.name !== '.git')
+ .map((e) => ({ name: e.name, dir: e.isDirectory(), ignored: false }))
+ .sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1))
+
+ // Mark git-ignored entries (so the explorer can dim them).
+ if (entries.length) {
+ const flag = (out: string): void => {
+ const set = new Set(
+ out
+ .split('\n')
+ .map((s) => s.trim().replace(/\/$/, ''))
+ .filter(Boolean)
+ )
+ for (const en of entries) if (set.has(en.name)) en.ignored = true
+ }
+ try {
+ const { stdout } = await run(
+ 'git',
+ ['-C', dirPath, 'check-ignore', '--', ...entries.map((e) => e.name)],
+ { maxBuffer: 4 * 1024 * 1024 }
+ )
+ flag(stdout)
+ } catch (err) {
+ const out = (err as { stdout?: string }).stdout
+ if (out) flag(out)
+ }
+ }
+ return entries
+ } catch {
+ return []
+ }
+}
+
+/** Read a file's UTF-8 text. Returns `''` on any error. */
+export async function readText(filePath: string): Promise<string> {
+ try {
+ return await fs.readFile(filePath, 'utf-8')
+ } catch {
+ return ''
+ }
+}
+
+/** Read a file as base64 (for image/binary previews). Returns `''` on any error. */
+export async function readBinary(filePath: string): Promise<string> {
+ try {
+ const buf = await fs.readFile(filePath)
+ return buf.toString('base64')
+ } catch {
+ return ''
+ }
+}
+
+/** Write UTF-8 text to a file. Resolves `true` on success, `false` on any error. */
+export async function writeText(filePath: string, content: string): Promise<boolean> {
+ try {
+ await fs.writeFile(filePath, content, 'utf-8')
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index cfe35677b..a532af8ad 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,9 +1,7 @@
import { join } from 'path'
-import { promises as fs } from 'fs'
-import { execFile } from 'child_process'
-import { promisify } from 'util'
import { app, BrowserWindow, dialog, ipcMain, Notification, shell } from 'electron'
import { IPC } from '../shared/ipc'
+import * as fsOps from './fs-ops'
import { PtyManager } from './pty-manager'
import { WorkspaceStore } from './workspace-store'
import { SettingsStore } from './settings-store'
@@ -179,69 +177,14 @@ app.whenReady().then(async () => {
if (typeof url === 'string' && /^https?:\/\//.test(url)) void shell.openExternal(url)
})
- ipcMain.handle(IPC.fsList, async (_e, dirPath: string) => {
- try {
- const dirents = await fs.readdir(dirPath, { withFileTypes: true })
- const entries = dirents
- .filter((e) => e.name !== '.git')
- .map((e) => ({ name: e.name, dir: e.isDirectory(), ignored: false }))
- .sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1))
-
- // Mark git-ignored entries (so the explorer can dim them).
- if (entries.length) {
- const run = promisify(execFile)
- const flag = (out: string) => {
- const set = new Set(
- out
- .split('\n')
- .map((s) => s.trim().replace(/\/$/, ''))
- .filter(Boolean)
- )
- for (const en of entries) if (set.has(en.name)) en.ignored = true
- }
- try {
- const { stdout } = await run(
- 'git',
- ['-C', dirPath, 'check-ignore', '--', ...entries.map((e) => e.name)],
- { maxBuffer: 4 * 1024 * 1024 }
- )
- flag(stdout)
- } catch (err) {
- const out = (err as { stdout?: string }).stdout
- if (out) flag(out)
- }
- }
- return entries
- } catch {
- return []
- }
- })
-
- ipcMain.handle(IPC.fsRead, async (_e, filePath: string) => {
- try {
- return await fs.readFile(filePath, 'utf-8')
- } catch {
- return ''
- }
- })
-
- ipcMain.handle(IPC.fsReadBinary, async (_e, filePath: string) => {
- try {
- const buf = await fs.readFile(filePath)
- return buf.toString('base64')
- } catch {
- return ''
- }
- })
-
- ipcMain.handle(IPC.fsWrite, async (_e, filePath: string, content: string) => {
- try {
- await fs.writeFile(filePath, content, 'utf-8')
- return true
- } catch {
- return false
- }
- })
+ // The local Explorer/Editor fs IPC: thin wrappers over the shared fs-ops (the SAME logic the
+ // remote `fs.*` RPC handlers reuse, so local and remote filesystem behaviour stay identical).
+ ipcMain.handle(IPC.fsList, (_e, dirPath: string) => fsOps.listDir(dirPath))
+ ipcMain.handle(IPC.fsRead, (_e, filePath: string) => fsOps.readText(filePath))
+ ipcMain.handle(IPC.fsReadBinary, (_e, filePath: string) => fsOps.readBinary(filePath))
+ ipcMain.handle(IPC.fsWrite, (_e, filePath: string, content: string) =>
+ fsOps.writeText(filePath, content)
+ )
ipcMain.handle(IPC.dialogSelectFolder, async () => {
const result = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] })
diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.ts
index 46bfe9158..1f0ae45cc 100644
--- a/src/main/remote/client-service.ts
+++ b/src/main/remote/client-service.ts
@@ -21,7 +21,7 @@
import { ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
-import type { CanvasMutation, CanvasState, PtyCreateOptions } from '../../shared/types'
+import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'
import { genKeyPair } from './e2ee'
import { OP, type Frame } from './framing'
import { CANVAS_MUTATE_METHOD, CANVAS_STATE_METHOD } from './host-service'
@@ -64,6 +64,14 @@ export interface ClientHandlers {
onFrame(frame: Frame): void
/** Drop all tracked streams (called on disconnect/close); does not RPC the host. */
closeAll(): void
+ /** List a directory on the host's filesystem (over `fs.list` RPC). */
+ fsList(path: string): Promise<DirEntry[]>
+ /** Read a host file's UTF-8 text (over `fs.read` RPC). */
+ fsRead(path: string): Promise<string>
+ /** Read a host file as base64 (over `fs.readBinary` RPC). */
+ fsReadBinary(path: string): Promise<string>
+ /** Write UTF-8 text to a host file (over `fs.write` RPC). */
+ fsWrite(path: string, content: string): Promise<boolean>
}
interface Stream {
@@ -165,6 +173,22 @@ export function createClientHandlers(
},
closeAll() {
streams.clear()
+ },
+ async fsList(path) {
+ const body = asRecord(await socket.rpc('fs.list', { path }))
+ return Array.isArray(body.entries) ? (body.entries as DirEntry[]) : []
+ },
+ async fsRead(path) {
+ const body = asRecord(await socket.rpc('fs.read', { path }))
+ return typeof body.content === 'string' ? body.content : ''
+ },
+ async fsReadBinary(path) {
+ const body = asRecord(await socket.rpc('fs.readBinary', { path }))
+ return typeof body.base64 === 'string' ? body.base64 : ''
+ },
+ async fsWrite(path, content) {
+ const body = asRecord(await socket.rpc('fs.write', { path, content }))
+ return body.ok === true
}
}
}
@@ -334,4 +358,23 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: boole
ipcMain.on(IPC.remoteClientMutate, (_e, connectionId: string, mutation: CanvasMutation) => {
connections.get(String(connectionId))?.canvas.sendMutation(mutation)
})
+
+ // Remote filesystem: the client renderer's `remoteFs(connectionId)` proxies the local `fs:*`
+ // shape onto the host's filesystem over the relay's `fs.*` RPCs. A missing connection degrades
+ // to the same empty/false values the host's fs-ops would return on error.
+ ipcMain.handle(IPC.remoteClientFsList, (_e, connectionId: string, path: string) =>
+ connections.get(String(connectionId))?.handlers.fsList(path) ?? Promise.resolve([])
+ )
+ ipcMain.handle(IPC.remoteClientFsRead, (_e, connectionId: string, path: string) =>
+ connections.get(String(connectionId))?.handlers.fsRead(path) ?? Promise.resolve('')
+ )
+ ipcMain.handle(IPC.remoteClientFsReadBinary, (_e, connectionId: string, path: string) =>
+ connections.get(String(connectionId))?.handlers.fsReadBinary(path) ?? Promise.resolve('')
+ )
+ ipcMain.handle(
+ IPC.remoteClientFsWrite,
+ (_e, connectionId: string, path: string, content: string) =>
+ connections.get(String(connectionId))?.handlers.fsWrite(path, content) ??
+ Promise.resolve(false)
+ )
}
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 9f05bcf45..c6de80cae 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -23,9 +23,10 @@ import { promises as fs } from 'fs'
import path from 'path'
import { app, ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
-import type { CanvasMutation, CanvasState, PtyCreateOptions } from '../../shared/types'
+import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'
import type { AgentId } from '../../shared/agents/config'
import { PtyManager, type DetachedSinks } from '../pty-manager'
+import * as fsOps from '../fs-ops'
import { getStoredEntitlement, isPremium } from '../license'
import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
import { OP, type Frame } from './framing'
@@ -73,6 +74,16 @@ export interface HostHandlers {
closeAll(): void
}
+// The slice of fs-ops the host serves over `fs.*` RPC. Defaults to the real fs-ops; tests inject
+// a fake (or just point it at a temp dir). Mirrors the renderer's `FsApi` contract exactly so a
+// remote Explorer/Editor behaves the same as a local one.
+export interface HostFsOps {
+ listDir(dirPath: string): Promise<DirEntry[]>
+ readText(filePath: string): Promise<string>
+ readBinary(filePath: string): Promise<string>
+ writeText(filePath: string, content: string): Promise<boolean>
+}
+
interface Stream {
sessionId: string
/** Outbound OP.Output sequence counter. */
@@ -99,7 +110,11 @@ function str(value: unknown): string | undefined {
*
* `nextStreamId` lets tests assert deterministic ids; production uses a monotonic counter.
*/
-export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket): HostHandlers {
+export function createHostHandlers(
+ pty: HostPtyManager,
+ socket: HostRelaySocket,
+ fs: HostFsOps = fsOps
+): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
const streams = new Map<number, Stream>()
@@ -232,6 +247,29 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)
})
}
+ // Serve a `fs.*` RPC by calling the shared fs-ops on the host's real filesystem and responding
+ // with the same shape the renderer's `FsApi` expects. fs-ops never throws (errors degrade to
+ // empty/false), so this always responds ok with a result body.
+ function handleFs(req: RpcRequest): void {
+ const p = asRecord(req.params)
+ const filePath = str(p.path) ?? ''
+ const respond = (body: unknown): void => socket.respond(req.id, true, body)
+ switch (req.method) {
+ case 'fs.list':
+ void fs.listDir(filePath).then((entries) => respond({ entries }))
+ break
+ case 'fs.read':
+ void fs.readText(filePath).then((content) => respond({ content }))
+ break
+ case 'fs.readBinary':
+ void fs.readBinary(filePath).then((base64) => respond({ base64 }))
+ break
+ case 'fs.write':
+ void fs.writeText(filePath, str(p.content) ?? '').then((ok) => respond({ ok }))
+ break
+ }
+ }
+
function handleKill(req: RpcRequest): void {
const streamId = num(asRecord(req.params).streamId, -1)
const stream = streams.get(streamId)
@@ -254,6 +292,12 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)
case 'pty.kill':
handleKill(req)
break
+ case 'fs.list':
+ case 'fs.read':
+ case 'fs.readBinary':
+ case 'fs.write':
+ handleFs(req)
+ break
default:
socket.respond(req.id, false, { message: `Unknown method: ${req.method}` })
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 6f976842b..9950d53ef 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -217,7 +217,13 @@ const api: NodeTerminalApi = {
return () => ipcRenderer.removeListener(channel, handler)
},
sendMutation: (connectionId, mutation) =>
- ipcRenderer.send(IPC.remoteClientMutate, connectionId, mutation)
+ ipcRenderer.send(IPC.remoteClientMutate, connectionId, mutation),
+ fsList: (connectionId, path) => ipcRenderer.invoke(IPC.remoteClientFsList, connectionId, path),
+ fsRead: (connectionId, path) => ipcRenderer.invoke(IPC.remoteClientFsRead, connectionId, path),
+ fsReadBinary: (connectionId, path) =>
+ ipcRenderer.invoke(IPC.remoteClientFsReadBinary, connectionId, path),
+ fsWrite: (connectionId, path, content) =>
+ ipcRenderer.invoke(IPC.remoteClientFsWrite, connectionId, path, content)
},
handoff: {
build: (sessionId, agentId, sourceNodeId, cwd) =>
diff --git a/src/renderer/canvas/RemoteSessionView.tsx b/src/renderer/canvas/RemoteSessionView.tsx
index 50deff7ea..045982bda 100644
--- a/src/renderer/canvas/RemoteSessionView.tsx
+++ b/src/renderer/canvas/RemoteSessionView.tsx
@@ -43,10 +43,17 @@ export function RemoteSessionView({ connectionId }: { connectionId: string }): R
)
}
-/** Tag every terminal node as remote-bound so TerminalNode picks RemoteTransport(connectionId). */
+// Node kinds whose `data.remote.connectionId` routes their I/O to the host over the relay:
+// terminals pick RemoteTransport(connectionId); editor/diff use remoteFs(connectionId) so they
+// read/write the HOST's filesystem instead of the local one.
+const REMOTE_BOUND_KINDS = new Set(['terminal', 'editor', 'diff'])
+
+/** Tag remote-capable nodes (terminal/editor/diff) so they address the host over the relay. */
function bindRemote(states: CanvasNodeState[], connectionId: string): CanvasNode[] {
return nodeStatesToFlow(states).map((n) =>
- n.type === 'terminal' ? { ...n, data: { ...n.data, remote: { connectionId } } } : n
+ n.type && REMOTE_BOUND_KINDS.has(n.type)
+ ? { ...n, data: { ...n.data, remote: { connectionId } } }
+ : n
)
}
diff --git a/src/renderer/components/ExplorerPanel.tsx b/src/renderer/components/ExplorerPanel.tsx
index c4f005b60..6e5d38012 100644
--- a/src/renderer/components/ExplorerPanel.tsx
+++ b/src/renderer/components/ExplorerPanel.tsx
@@ -100,7 +100,13 @@ function TreeEntry({
)
}
-/** Project file explorer — a lazy-loaded tree of the active project's folder. */
+/** Project file explorer — a lazy-loaded tree of the active project's folder.
+ *
+ * NOTE (Task 6): this Explorer is LOCAL-only. In a remote session the host's root cwd isn't known
+ * client-side (the local project's `cwd` is the client's), so it can't be pointed at the host
+ * filesystem yet. Once `canvas:state` carries the host cwd (Task 6), this can switch to
+ * `remoteFs(connectionId)` (the per-connection `FsApi`) rooted at that path — the Editor already
+ * proxies over the relay via `data.remote.connectionId`. */
export function ExplorerPanel({ onClose, onOpenFile }: ExplorerPanelProps) {
const project = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId))
const cwd = project?.cwd
diff --git a/src/renderer/nodes/EditorNode.tsx b/src/renderer/nodes/EditorNode.tsx
index 45184c96e..e963bf95b 100644
--- a/src/renderer/nodes/EditorNode.tsx
+++ b/src/renderer/nodes/EditorNode.tsx
@@ -3,6 +3,7 @@ import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'
import { monaco } from '../editor/monaco-setup'
import { renderMarkdown } from '../lib/markdown'
import { useSettings } from '../state/settings'
+import { remoteFs } from '../terminal/remote-fs'
import type { CanvasNode } from '../state/workspace'
// Image extensions get a visual preview instead of the Monaco text editor.
@@ -36,6 +37,10 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {
const [imageDims, setImageDims] = useState('')
const [imageError, setImageError] = useState('')
const filePath = (data.filePath as string) ?? ''
+ // In a remote session the node operates on the HOST's filesystem via the relay; otherwise the
+ // local fs. The `FsApi` shape is identical, so the rest of the component is unchanged.
+ const connectionId = data.remote?.connectionId
+ const fs = connectionId ? remoteFs(connectionId) : window.nodeTerminal.fs
const fileName = filePath.split('/').pop() || 'untitled'
const ext = fileName.includes('.') ? fileName.split('.').pop()!.toLowerCase() : ''
const isImage = ext in IMAGE_MIME
@@ -55,7 +60,7 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {
const editor = editorRef.current
if (!editor) return
const value = editor.getValue()
- window.nodeTerminal.fs.write(filePath, value).then((ok) => {
+ fs.write(filePath, value).then((ok) => {
if (ok) {
savedRef.current = value
setDirty(false)
@@ -72,7 +77,7 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {
if (isImage) {
let disposed = false
// Guard: readBinary may be missing if the preload is stale (dev not restarted).
- const readBinary = window.nodeTerminal.fs.readBinary
+ const readBinary = fs.readBinary
if (typeof readBinary !== 'function') {
setImageError('Image preview needs an app restart.')
return
@@ -97,7 +102,7 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {
let editor: monaco.editor.IStandaloneCodeEditor | null = null
let model: monaco.editor.ITextModel | null = null
- window.nodeTerminal.fs.read(filePath).then((content) => {
+ fs.read(filePath).then((content) => {
if (disposed) return
const s = useSettings.getState().settings
// Unique model per node (fragment), language still inferred from the path extension.
diff --git a/src/renderer/terminal/remote-fs.ts b/src/renderer/terminal/remote-fs.ts
new file mode 100644
index 000000000..7e6175033
--- /dev/null
+++ b/src/renderer/terminal/remote-fs.ts
@@ -0,0 +1,21 @@
+// Remote filesystem API (renderer).
+//
+// `remoteFs(connectionId)` returns an object satisfying the same `FsApi` contract as
+// `window.nodeTerminal.fs`, but scoped to a remote connection: every call proxies onto the HOST's
+// filesystem over the E2EE relay (renderer → `remoteClient.fs*` IPC → client-service `fs.*` RPC →
+// host-service `fs.*` handler → shared fs-ops). Because the shape matches the local `FsApi`
+// exactly, nodes (Editor/Diff/Explorer) can pick `remoteFs(connectionId)` instead of the local fs
+// when they are rendered inside a remote session, with behaviour identical to local.
+
+import type { FsApi } from '@shared/types'
+
+/** Build an `FsApi` bound to a remote connection (proxies to the host's filesystem). */
+export function remoteFs(connectionId: string): FsApi {
+ const client = window.nodeTerminal.remoteClient
+ return {
+ list: (dirPath) => client.fsList(connectionId, dirPath),
+ read: (filePath) => client.fsRead(connectionId, filePath),
+ readBinary: (filePath) => client.fsReadBinary(connectionId, filePath),
+ write: (filePath, content) => client.fsWrite(connectionId, filePath, content)
+ }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 161ff418d..99bbb1c1b 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -94,6 +94,11 @@ export const IPC = {
// Client canvas mirror: main pushes the host's full canvas snapshot to the client renderer;
// the client renderer sends its local mutations back for main to RPC to the host.
remoteClientMutate: 'remote:client:mutate',
+ // Remote filesystem: the client proxies the local `fs:*` shape onto the host over the relay.
+ remoteClientFsList: 'remote:client:fs-list',
+ remoteClientFsRead: 'remote:client:fs-read',
+ remoteClientFsReadBinary: 'remote:client:fs-read-binary',
+ remoteClientFsWrite: 'remote:client:fs-write',
// Host canvas snapshot pushed main->renderer for a connection (connectionId appended).
remoteClientCanvasState: (connectionId: string) => `remote:client:canvas-state:${connectionId}`,
// Per-session events broadcast main->renderer (connectionId + streamId appended).
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 7a6fdfb4d..7dbb155e6 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -610,6 +610,14 @@ export interface RemoteClientApi {
* `canvas:mutate` RPC; the host applies it and the next `canvas:state` reconciles.
*/
sendMutation(connectionId: string, mutation: CanvasMutation): void
+ /** List a directory on the host's filesystem (the `FsApi.list` shape over the relay). */
+ fsList(connectionId: string, path: string): Promise<DirEntry[]>
+ /** Read a host file's UTF-8 text (the `FsApi.read` shape over the relay). */
+ fsRead(connectionId: string, path: string): Promise<string>
+ /** Read a host file as base64 (the `FsApi.readBinary` shape over the relay). */
+ fsReadBinary(connectionId: string, path: string): Promise<string>
+ /** Write UTF-8 text to a host file (the `FsApi.write` shape over the relay). */
+ fsWrite(connectionId: string, path: string, content: string): Promise<boolean>
}
export interface NodeTerminalApi {
diff --git a/test/remote/remote-fs.test.ts b/test/remote/remote-fs.test.ts
new file mode 100644
index 000000000..e778f80d0
--- /dev/null
+++ b/test/remote/remote-fs.test.ts
@@ -0,0 +1,116 @@
+// Remote filesystem round-trip (Task 5).
+//
+// Wires the pure CLIENT handlers' `fs.*` RPC senders straight into the pure HOST handlers' `fs.*`
+// RPC handlers via a fake relay pair (no sockets, no Electron). The host handlers run the REAL
+// shared fs-ops against a real temp dir, so this proves the full client→host→fs round-trip:
+// client.fsWrite(tmp, 'hi') → host writes the real file
+// client.fsRead(tmp) → host reads it back → 'hi'
+// client.fsList(tmpdir) → host lists it → includes the file
+// client.fsReadBinary(tmp) → host reads base64 → decodes to 'hi'
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import {
+ createHostHandlers,
+ type HostPtyManager,
+ type HostRelaySocket
+} from '../../src/main/remote/host-service'
+import {
+ createClientHandlers,
+ type ClientRelaySocket,
+ type ClientSessionSinks
+} from '../../src/main/remote/client-service'
+
+// The fs RPCs never touch the PTY; a no-op pty-manager satisfies the host's required shape.
+function noopPty(): HostPtyManager {
+ return {
+ createDetached: () => 'pty-1',
+ attachDetached: () => 'pty-1',
+ captureSnapshot: async () => '',
+ write: () => {},
+ resize: () => {},
+ setFlow: () => {},
+ kill: () => {}
+ }
+}
+
+const noopSinks: ClientSessionSinks = { onData: () => {}, onExit: () => {} }
+
+// A fake relay pair: the client's `rpc(method, params)` is routed straight into the host handlers'
+// `onRpc` (resolved lazily so the host can be built after the pair), and the host's
+// `respond(id, ok, body)` resolves the matching client promise. This is the synchronous in-memory
+// equivalent of the relay carrying the request/response.
+function fakePair(getHost: () => ReturnType<typeof createHostHandlers>) {
+ let counter = 0
+ const pending = new Map<string, (body: unknown) => void>()
+
+ const hostSocket: HostRelaySocket = {
+ respond: (id, _ok, body) => pending.get(id)?.(body),
+ sendFrame: () => true
+ }
+
+ const clientSocket: ClientRelaySocket = {
+ rpc: (method, params) =>
+ new Promise((resolve) => {
+ const id = `rpc-${++counter}`
+ pending.set(id, resolve)
+ getHost().onRpc({ id, method, params })
+ }),
+ sendFrame: () => true
+ }
+
+ return { hostSocket, clientSocket }
+}
+
+describe('remote filesystem round-trip (client fs RPC → host fs-ops → real temp dir)', () => {
+ let dir = ''
+
+ beforeAll(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nodeterm-remote-fs-'))
+ })
+
+ afterAll(async () => {
+ await fs.rm(dir, { recursive: true, force: true })
+ })
+
+ it('writes, reads, lists and reads-binary a host file over the relay', async () => {
+ // Build the host handlers first so the fake pair can route the client's RPCs into them; then
+ // wire the host's `respond` back through the same pair.
+ let host!: ReturnType<typeof createHostHandlers>
+ const pair = fakePair(() => host)
+ host = createHostHandlers(noopPty(), pair.hostSocket)
+ const client = createClientHandlers(pair.clientSocket, noopSinks)
+
+ const file = path.join(dir, 'note.txt')
+
+ // write
+ expect(await client.fsWrite(file, 'hi')).toBe(true)
+ expect(await fs.readFile(file, 'utf-8')).toBe('hi')
+
+ // read
+ expect(await client.fsRead(file)).toBe('hi')
+
+ // list includes the new file
+ const entries = await client.fsList(dir)
+ expect(entries.map((e) => e.name)).toContain('note.txt')
+ expect(entries.find((e) => e.name === 'note.txt')?.dir).toBe(false)
+
+ // readBinary round-trips through base64
+ const b64 = await client.fsReadBinary(file)
+ expect(Buffer.from(b64, 'base64').toString('utf-8')).toBe('hi')
+ })
+
+ it('degrades to empty/false on host fs errors (read/list/write of a bad path)', async () => {
+ let host!: ReturnType<typeof createHostHandlers>
+ const pair = fakePair(() => host)
+ host = createHostHandlers(noopPty(), pair.hostSocket)
+ const client = createClientHandlers(pair.clientSocket, noopSinks)
+
+ expect(await client.fsRead(path.join(dir, 'does-not-exist.txt'))).toBe('')
+ expect(await client.fsList(path.join(dir, 'no-such-dir'))).toEqual([])
+ expect(await client.fsWrite(path.join(dir, 'no', 'such', 'parent.txt'), 'x')).toBe(false)
+ })
+})