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(peer): electronPlatform.dispatch/cast — a peer's RPC reaches the core's handlers

enesc9efc4cdccbf
diff --git a/src/core/fs-handlers.ts b/src/core/fs-handlers.ts
new file mode 100644
index 000000000..fa1c133fb
--- /dev/null
+++ b/src/core/fs-handlers.ts
@@ -0,0 +1,22 @@
+import type { CorePlatform } from './platform'
+import * as fsOps from './fs-ops'
+import { IPC } from '../shared/ipc'
+
+/** The fs.* + files.quickOpen RPC surface, registered ONCE for every shell (Electron main, the
+ * Server Edition, and — through the Electron platform's handler table — a relay peer). The logic
+ * is already pure in core/fs-ops.ts; this is only the registration.
+ *
+ * It lives here, and not in either shell, so the two can never drift: the desktop used to register
+ * these on raw `ipcMain`, which made them unreachable for a peer (a peer has no webContents).
+ * Threat model unchanged: whoever can reach these already has a terminal on this machine. */
+export function registerFsHandlers(platform: CorePlatform): void {
+ platform.handle(IPC.fsList, (dirPath: string) => fsOps.listDir(dirPath))
+ platform.handle(IPC.fsRead, (filePath: string) => fsOps.readText(filePath))
+ platform.handle(IPC.fsReadBinary, (filePath: string) => fsOps.readBinary(filePath))
+ platform.handle(IPC.fsWrite, (filePath: string, content: string) =>
+ fsOps.writeText(filePath, content)
+ )
+ platform.handle(IPC.fsMkdir, (dirPath: string) => fsOps.makeDir(dirPath))
+ platform.handle(IPC.fsExists, (p: string) => fsOps.pathExists(p))
+ platform.handle(IPC.filesQuickOpen, (cwd: string) => fsOps.listQuickOpenFiles(cwd))
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index dc0608a84..c6308405a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -4,7 +4,7 @@ import { homedir } from 'os'
import { randomUUID } from 'crypto'
import { app, BrowserWindow, dialog, ipcMain, Notification, shell } from 'electron'
import { IPC } from '../shared/ipc'
-import * as fsOps from '../core/fs-ops'
+import { registerFsHandlers } from '../core/fs-handlers'
import { PtyManager } from '../core/pty-manager'
import { WorkspaceStore } from '../core/workspace-store'
import { WorkspaceWatcher } from '../core/workspace-watcher'
@@ -87,7 +87,10 @@ if (NT_MULTI && process.env.NT_USER_DATA) app.setPath('userData', process.env.NT
// First thing in bootstrap: install the Electron CorePlatform so anything in src/core
// (wired in later tasks) can resolve platform() at boot. Placed after the NT_MULTI
// userData override so userDataDir reads the final path; nothing consumes it yet.
-initPlatform(electronPlatform())
+// Held: a relay peer's inbound RPC is answered from THIS instance's handler table (corePlatform
+// .dispatch / .cast — see platform-electron.ts). `platform()` only exposes the CorePlatform half.
+const corePlatform = electronPlatform()
+initPlatform(corePlatform)
// Only hand the OS a URL with a vetted scheme. Blocks file://, smb://, and custom
// protocol-handler schemes that could be smuggled in via remote announcement feeds or
@@ -374,7 +377,14 @@ app.whenReady().then(async () => {
// node — resolves from cache instead of racing the probe into a conservative "no auto".
void claudeCliCaps()
- ipcMain.handle(IPC.commitGenerate, (_e, cwd: string) =>
+ // REACHABILITY (4c): a handler registered through `corePlatform` serves BOTH the local window
+ // (it is still `ipcMain.handle`, bit-for-bit) AND a relay peer (answered from the platform's
+ // handler table — a peer has no webContents, so a raw `ipcMain.handle` is invisible to it).
+ // Everything core-bound — it acts on THIS machine's state, which is exactly what a remote tab
+ // is looking at — goes on the platform. The raw `ipcMain` registrations that remain further down
+ // are deliberate: each one must act on the USER's machine (dialogs, shell, notifications,
+ // updater) or is part of the host's own trust/relay control plane (pairing, remote:*, accounts).
+ corePlatform.handle(IPC.commitGenerate, (cwd: string) =>
generateCommitMessage(cwd, settingsStore.get())
)
@@ -395,7 +405,7 @@ app.whenReady().then(async () => {
const localNamingCwd = (keys: string[], cwd: string): string =>
keys.some((k) => ptyManager.sshRemoteForNode(k)) ? '' : cwd
- ipcMain.handle(IPC.ptyGenerateName, async (_e, persistKey: string, cwd: string) =>
+ corePlatform.handle(IPC.ptyGenerateName, async (persistKey: string, cwd: string) =>
generateTerminalName(
await ptyManager.captureSession(persistKey),
localNamingCwd([persistKey], cwd),
@@ -403,16 +413,16 @@ app.whenReady().then(async () => {
)
)
- ipcMain.handle(IPC.ptyGenerateGroupName, async (_e, memberKeys: string[], cwd: string) => {
+ corePlatform.handle(IPC.ptyGenerateGroupName, async (memberKeys: string[], cwd: string) => {
const contents = await Promise.all(memberKeys.map((k) => ptyManager.captureSession(k)))
return generateGroupName(contents, localNamingCwd(memberKeys, cwd), settingsStore.get())
})
- ipcMain.handle(IPC.ptyCapture, (_e, persistKey: string, full?: boolean) =>
+ corePlatform.handle(IPC.ptyCapture, (persistKey: string, full?: boolean) =>
ptyManager.captureSession(persistKey, full)
)
- ipcMain.handle(IPC.ptyReadSessionName, (_e, sessionId: string, accountId?: string) =>
+ corePlatform.handle(IPC.ptyReadSessionName, (sessionId: string, accountId?: string) =>
readSessionName(sessionId ?? '', accountId)
)
@@ -480,8 +490,9 @@ app.whenReady().then(async () => {
ipcMain.handle(IPC.announcementsFetch, async () => (await fetchCheck()).messages)
ipcMain.handle(IPC.appUpdatePolicy, async () => (await fetchCheck()).update)
- // Writable base dir for app-managed files (e.g. default git worktree location).
- ipcMain.handle(IPC.appUserDataDir, () => app.getPath('userData'))
+ // Writable base dir for app-managed files (e.g. default git worktree location). On the platform:
+ // a remote tab derives the default worktree path from it, and the worktree lives on THIS host.
+ corePlatform.handle(IPC.appUserDataDir, () => app.getPath('userData'))
// Phone pairing (nodeterm iOS "scan a QR" flow): a one-shot LAN listener that installs the
// phone's Ed25519 key into ~/.ssh/authorized_keys. The completion result is forwarded to the
@@ -517,17 +528,10 @@ app.whenReady().then(async () => {
if (isSafeExternalUrl(url)) void shell.openExternal(url)
})
- // 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.fsMkdir, (_e, dirPath: string) => fsOps.makeDir(dirPath))
- ipcMain.handle(IPC.fsExists, (_e, p: string) => fsOps.pathExists(p))
- ipcMain.handle(IPC.filesQuickOpen, (_e, cwd: string) => fsOps.listQuickOpenFiles(cwd))
+ // 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)
// SSH-project Explorer/Editor fs: the remote analog of the fs:* handlers above, scoped to a
// project's ControlMaster. One SshFs bound to the SSH-project manager's own ssh runner (the SAME
@@ -695,10 +699,9 @@ app.whenReady().then(async () => {
// the remote read fetches the tail over ssh, then reuses the SAME pure parsers as local, so
// the returned shape is byte-identical to the local reader.
const REMOTE_TRANSCRIPT_CAP = 5 * 1024 * 1024
- ipcMain.handle(
+ corePlatform.handle(
IPC.claudeReadTranscript,
async (
- _e,
sessionId: string | undefined,
cwd: string | undefined,
accountId: string | undefined
@@ -713,10 +716,9 @@ app.whenReady().then(async () => {
}
)
- ipcMain.handle(
+ corePlatform.handle(
IPC.chatReadTranscript,
async (
- _e,
sessionId: string | undefined,
cwd: string | undefined,
accountId: string | undefined
@@ -732,24 +734,20 @@ app.whenReady().then(async () => {
)
initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])
- ipcMain.handle(IPC.transcriptSearch, (_e, query: string) => searchTranscripts(query))
+ corePlatform.handle(IPC.transcriptSearch, (query: string) => searchTranscripts(query))
// Populate the context meter without a live hook event: the renderer calls this on mount
// (the continuing session may be idle after a restart). Track under the sessionId (the key
// the meter looks up); cwd is only a path fallback. contextTail.track reads immediately and
// the 1s interval keeps it fresh while tracked.
- ipcMain.on(
- IPC.contextEnsure,
- async (_e, sessionId?: string, cwd?: string, accountId?: string) => {
- if (!sessionId || !SESSION_ID_RE.test(sessionId)) return
- let p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId, accountId))
- if (!p && cwd) p = await transcriptPathForCwd(cwd)
- if (p) contextTail.track(sessionId, p)
- }
- )
- ipcMain.handle(
+ corePlatform.on(IPC.contextEnsure, async (sessionId?: string, cwd?: string, accountId?: string) => {
+ if (!sessionId || !SESSION_ID_RE.test(sessionId)) return
+ let p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId, accountId))
+ if (!p && cwd) p = await transcriptPathForCwd(cwd)
+ if (p) contextTail.track(sessionId, p)
+ })
+ corePlatform.handle(
IPC.handoffBuild,
(
- _e,
sessionId: string,
agentId: string,
sourceNodeId: string,
@@ -757,14 +755,17 @@ app.whenReady().then(async () => {
accountId: string | undefined
) => buildHandoff({ sessionId, agentId, sourceNodeId, cwd, accountId })
)
- // Chat nodes: one long-lived Claude Agent SDK query per node, bridged over chat:* IPC.
- ipcMain.handle(IPC.chatEnsure, (_e, nodeId: string, opts) => chatDriver.ensure(nodeId, opts))
- ipcMain.on(IPC.chatSend, (_e, nodeId: string, text: string, images) => chatDriver.send(nodeId, text, images))
- ipcMain.on(IPC.chatInterrupt, (_e, nodeId: string) => chatDriver.interrupt(nodeId))
- ipcMain.on(IPC.chatPermissionReply, (_e, nodeId: string, requestId: string, decision) =>
+ // Chat nodes: one long-lived Claude Agent SDK query per node, bridged over chat:* IPC. On the
+ // platform: the driver runs on THIS host, and a remote tab's chat node drives the same one.
+ corePlatform.handle(IPC.chatEnsure, (nodeId: string, opts) => chatDriver.ensure(nodeId, opts))
+ corePlatform.on(IPC.chatSend, (nodeId: string, text: string, images) =>
+ chatDriver.send(nodeId, text, images))
+ corePlatform.on(IPC.chatInterrupt, (nodeId: string) => chatDriver.interrupt(nodeId))
+ corePlatform.on(IPC.chatPermissionReply, (nodeId: string, requestId: string, decision) =>
chatDriver.permissionReply(nodeId, requestId, decision))
- ipcMain.on(IPC.chatRemoveQueued, (_e, nodeId: string, queueId: string) => chatDriver.removeQueued(nodeId, queueId))
- ipcMain.on(IPC.chatDispose, (_e, nodeId: string) => chatDriver.dispose(nodeId))
+ corePlatform.on(IPC.chatRemoveQueued, (nodeId: string, queueId: string) =>
+ chatDriver.removeQueued(nodeId, queueId))
+ corePlatform.on(IPC.chatDispose, (nodeId: string) => chatDriver.dispose(nodeId))
installManagedAgentHooks()
// Managed accounts each carry their own settings.json AND skills/ (Claude Code resolves both
@@ -935,8 +936,11 @@ app.whenReady().then(async () => {
nodeSubagents.delete(nodeId)
}
}
- ipcMain.on(IPC.ptyDestroy, (_e, nodeId: string) => releaseNodeTails(nodeId))
- ipcMain.on(IPC.ptyRecycle, (_e, nodeId: string) => releaseNodeTails(nodeId))
+ // A SECOND listener on these channels (PtyManager registers its own): both fire, in registration
+ // order, on ipcMain AND in the platform's listener table — so a peer closing a node releases the
+ // host's tails too, instead of leaking them.
+ corePlatform.on(IPC.ptyDestroy, (nodeId: string) => releaseNodeTails(nodeId))
+ corePlatform.on(IPC.ptyRecycle, (nodeId: string) => releaseNodeTails(nodeId))
// Agent canvas control: the spawned agent's `nodeterm` CLI POSTs a verb to the hook server,
// which we forward to the renderer and await a reply. A pending-request map (keyed by a random
// requestId) bridges the two async hops; both the reply and the 120s timeout clear the entry.
diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.ts
index 74e21206f..65ec1d360 100644
--- a/src/main/platform-electron.test.ts
+++ b/src/main/platform-electron.test.ts
@@ -43,6 +43,7 @@ import {
type UiSink
} from './peer-registry'
import { decodePtyData } from '../shared/rpc'
+import { allocateRelayClientId } from '../core/presence/hub'
/** A relay peer id, as allocateRelayClientId() would mint it (≥ 1_000_000 — never a webContents id). */
const PEER = 1_000_000
@@ -202,3 +203,94 @@ describe('electronPlatform + relay peers', () => {
expect(h.sent).toEqual([{ channel: 'x', args: [1] }]) // exactly sendToMain, nothing else
})
})
+
+/**
+ * The INBOUND half (4c): a peer has no webContents, so its RPC request can never travel through
+ * ipcMain. It is answered from the platform's own recorded handler table — the SAME registrations
+ * the local window gets, so the two surfaces can never drift.
+ */
+describe('electronPlatform.dispatch / cast (the peer inbound path)', () => {
+ it('dispatch answers a peer request from the recorded handler table, with the peer as sender', async () => {
+ const p = electronPlatform()
+ p.handle('fs:list', (dir: string) => [{ name: 'a.txt', dir: false, path: `${dir}/a.txt` }])
+ p.handleWithSender('presence:hello', (senderId: number, id: unknown) => ({ senderId, id }))
+
+ const peer = allocateRelayClientId()
+ await expect(
+ p.dispatch(peer, { t: 'req', id: 7, method: 'fs:list', args: ['/w'] })
+ ).resolves.toEqual({
+ t: 'res',
+ id: 7,
+ ok: true,
+ result: [{ name: 'a.txt', dir: false, path: '/w/a.txt' }]
+ })
+ await expect(
+ p.dispatch(peer, { t: 'req', id: 8, method: 'presence:hello', args: [{ name: 'A' }] })
+ ).resolves.toEqual({ t: 'res', id: 8, ok: true, result: { senderId: peer, id: { name: 'A' } } })
+ })
+
+ it('an unknown method answers E_NO_HANDLER (never hangs the peer)', async () => {
+ const p = electronPlatform()
+ const res = await p.dispatch(PEER, { t: 'req', id: 1, method: 'nope', args: [] })
+ expect(res).toMatchObject({ ok: false, error: { code: 'E_NO_HANDLER' } })
+ })
+
+ it('a throwing handler answers an error frame, not a rejection', async () => {
+ const p = electronPlatform()
+ p.handle('boom', () => {
+ throw new Error('nope')
+ })
+ const res = await p.dispatch(PEER, { t: 'req', id: 2, method: 'boom', args: [] })
+ expect(res).toMatchObject({ ok: false, error: { code: 'E_HANDLER', message: 'nope' } })
+ })
+
+ it('a handler returning undefined answers null (JSON has no undefined)', async () => {
+ const p = electronPlatform()
+ p.handle('void', () => undefined)
+ await expect(p.dispatch(PEER, { t: 'req', id: 3, method: 'void', args: [] })).resolves.toEqual({
+ t: 'res',
+ id: 3,
+ ok: true,
+ result: null
+ })
+ })
+
+ it('cast fires every listener in registration order, with the peer as sender', () => {
+ const p = electronPlatform()
+ const seen: string[] = []
+ p.on('pty:write', (sid: unknown) => seen.push(`on:${sid}`))
+ p.onWithSender('pty:write', (senderId: number, sid: unknown) => seen.push(`ws:${senderId}:${sid}`))
+ p.cast(1_000_001, 'pty:write', ['s1', 'x'])
+ expect(seen).toEqual(['on:s1', 'ws:1000001:s1'])
+ })
+
+ it('one throwing cast listener does not swallow the peer keystroke for the rest', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const p = electronPlatform()
+ const seen: string[] = []
+ p.on('pty:write', () => {
+ throw new Error('attribution blew up')
+ })
+ p.onWithSender('pty:write', (_s: number, sid: unknown) => seen.push(`ws:${sid}`))
+ expect(() => p.cast(PEER, 'pty:write', ['s1', 'x'])).not.toThrow()
+ expect(seen).toEqual(['ws:s1'])
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+
+ it('cast on a channel nobody listens to is a silent no-op', () => {
+ const p = electronPlatform()
+ expect(() => p.cast(PEER, 'nobody:home', [])).not.toThrow()
+ })
+
+ it('recording the table does not change what the LOCAL window gets (still ipcMain)', async () => {
+ const p = electronPlatform()
+ p.handle('c1', (a: number) => a + 1)
+ p.on('c2', () => {})
+ p.handleWithSender('c3', (senderId: number, a: string) => `${senderId}:${a}`)
+ // Same ipcMain registrations, same event-stripping, same sender id as before this feature.
+ expect(await h.handlers['c1']({ sender: { id: 1 } }, 41)).toBe(42)
+ expect(await h.handlers['c3']({ sender: { id: 7 } }, 'x')).toBe('7:x')
+ expect(Object.keys(h.handlers).sort()).toEqual(['c1', 'c2', 'c3'])
+ })
+})
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index bc6eea4f4..222ab6ee5 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -2,6 +2,24 @@ import { app, ipcMain, shell, webContents } from 'electron'
import type { CorePlatform } from '../core/platform'
import { mainWindowClientIds, sendToMain } from './main-window'
import { peerRegistry } from './peer-registry'
+import { E_NO_HANDLER, type RpcErr, type RpcOk, type RpcRequest } from '../shared/rpc'
+
+type Handler = { fn: (...args: any[]) => unknown; withSender: boolean }
+type Listener = { fn: (...args: any[]) => void; withSender: boolean }
+
+/**
+ * The Electron platform, with the two extra members a relay PEER needs (they are deliberately NOT
+ * on CorePlatform: the core never dispatches, only the shell that owns the socket does — exactly as
+ * attach/detach/dispatch are extras on ServerPlatform).
+ */
+export interface ElectronPlatform extends CorePlatform {
+ /** Answer one peer RPC request from the recorded handler table. The peer's clientId is the
+ * sender, so handleWithSender attributes it correctly. Never rejects: a missing handler is
+ * E_NO_HANDLER and a throwing handler is E_HANDLER, so the peer's `await` always settles. */
+ dispatch(clientId: number, req: RpcRequest): Promise<RpcOk | RpcErr>
+ /** Fire one peer cast at every listener on that channel, in registration order. */
+ cast(clientId: number, method: string, args: unknown[]): void
+}
/**
* The Electron shell's CorePlatform. Getters keep app.getPath lazy (safe pre-ready).
@@ -16,7 +34,30 @@ import { peerRegistry } from './peer-registry'
* SOLO COST: zero. With no peer registered the registry holds an empty Map — `has` is a miss, `ids`
* is empty — and the webContents path below is the code it replaced, byte for byte.
*/
-export function electronPlatform(): CorePlatform {
+export function electronPlatform(): ElectronPlatform {
+ // THE INVARIANT (4c): a channel is REACHABLE BY A REMOTE PEER if, and only if, it is registered
+ // through platform().handle/on. A raw `ipcMain.handle` is invisible to a peer — a peer has no
+ // webContents, so its request never travels through ipcMain at all; it is answered from THIS
+ // table by dispatch() below. When you add an IPC handler, that is the choice you are making:
+ // - core-bound / acts on THIS machine's state (fs, git, pty, workspace, transcripts) → platform
+ // - acts on the USER's own machine or is host-security-sensitive (dialogs, shell, notifications,
+ // updater, pairing/relay control plane) → raw ipcMain, on purpose. See src/main/index.ts.
+ // handle/handleWithSender are ONE handler per channel (last wins, like ipcMain.handle);
+ // on/onWithSender are an ordered set of listeners. Mirrors ServerPlatform exactly — a divergence
+ // here would be a behavior difference between the two remote surfaces.
+ //
+ // SOLO COST: one Map.set per boot-time registration. With no peer connected nothing ever reads it.
+ const handlers = new Map<string, Handler>()
+ const listeners = new Map<string, Set<Listener>>()
+ const addListener = (channel: string, listener: Listener): void => {
+ let set = listeners.get(channel)
+ if (!set) {
+ set = new Set()
+ listeners.set(channel, set)
+ }
+ set.add(listener)
+ }
+
return {
get userDataDir() {
return app.getPath('userData')
@@ -27,10 +68,60 @@ export function electronPlatform(): CorePlatform {
get isPackaged() {
return app.isPackaged
},
- handle: (ch, fn) => ipcMain.handle(ch, (_e, ...args) => fn(...args)),
- on: (ch, fn) => ipcMain.on(ch, (_e, ...args) => fn(...args)),
- handleWithSender: (ch, fn) => ipcMain.handle(ch, (e, ...args) => fn(e.sender.id, ...args)),
- onWithSender: (ch, fn) => ipcMain.on(ch, (e, ...args) => fn(e.sender.id, ...args)),
+ // The ipcMain half of each registration is UNCHANGED — the local window's call is bit-identical
+ // to what it was before the table existed (same event-stripping, same sender id).
+ handle: (ch, fn) => {
+ handlers.set(ch, { fn, withSender: false })
+ ipcMain.handle(ch, (_e, ...args) => fn(...args))
+ },
+ on: (ch, fn) => {
+ addListener(ch, { fn, withSender: false })
+ ipcMain.on(ch, (_e, ...args) => fn(...args))
+ },
+ handleWithSender: (ch, fn) => {
+ handlers.set(ch, { fn, withSender: true })
+ ipcMain.handle(ch, (e, ...args) => fn(e.sender.id, ...args))
+ },
+ onWithSender: (ch, fn) => {
+ addListener(ch, { fn, withSender: true })
+ ipcMain.on(ch, (e, ...args) => fn(e.sender.id, ...args))
+ },
+ async dispatch(clientId, req) {
+ const h = handlers.get(req.method)
+ if (!h) {
+ return {
+ t: 'res', id: req.id, ok: false,
+ error: { code: E_NO_HANDLER, message: `no handler for ${req.method}` }
+ }
+ }
+ try {
+ const result = h.withSender ? await h.fn(clientId, ...req.args) : await h.fn(...req.args)
+ return { t: 'res', id: req.id, ok: true, result: result ?? null }
+ } catch (err) {
+ return {
+ t: 'res', id: req.id, ok: false,
+ error: { code: 'E_HANDLER', message: err instanceof Error ? err.message : String(err) }
+ }
+ }
+ },
+ cast(clientId, method, args) {
+ const set = listeners.get(method)
+ if (!set) return
+ for (const l of set) {
+ // A cast has no reply channel (unlike dispatch, which returns E_HANDLER), so isolate each
+ // listener: one throw must not skip the rest — a broken attribution listener would
+ // otherwise swallow the peer's keystrokes. Log it, keep going. (Mirrors ServerPlatform.)
+ try {
+ if (l.withSender) l.fn(clientId, ...args)
+ else l.fn(...args)
+ } catch (err) {
+ console.warn(
+ `[peer] cast listener for ${method} threw`,
+ err instanceof Error ? err.message : String(err)
+ )
+ }
+ }
+ },
sendTo: (id, ch, ...args) => {
// A peer id resolves to a UiSink (RPC-framed; pty:data goes out as a binary frame, with the
// registry's WS backpressure). Everything else is a webContents, dispatched natively.
diff --git a/src/server/handlers/fs.test.ts b/src/server/handlers/fs-handlers.test.ts
similarity index 97%
rename from src/server/handlers/fs.test.ts
rename to src/server/handlers/fs-handlers.test.ts
index 4309db656..0c0385bef 100644
--- a/src/server/handlers/fs.test.ts
+++ b/src/server/handlers/fs-handlers.test.ts
@@ -3,7 +3,7 @@ import fs from 'fs'
import os from 'os'
import path from 'path'
import { ServerPlatform } from '../platform-server'
-import { registerFsHandlers } from './fs'
+import { registerFsHandlers } from '../../core/fs-handlers'
import { IPC } from '../../shared/ipc'
let dir: string, platform: ServerPlatform, ui: number
diff --git a/src/server/handlers/fs.ts b/src/server/handlers/fs.ts
deleted file mode 100644
index f26000322..000000000
--- a/src/server/handlers/fs.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { ServerPlatform } from '../platform-server'
-import * as fsOps from '../../core/fs-ops'
-import { IPC } from '../../shared/ipc'
-
-/** Register the fs.* + files.quickOpen RPC surface. The desktop registers these inline in
- * src/main/index.ts; the logic is already pure in src/core/fs-ops.ts, so the server just
- * wraps it. Threat model: an authenticated user already has a shell, so server-local file
- * read/write adds no new exposure. */
-export function registerFsHandlers(platform: ServerPlatform): void {
- platform.handle(IPC.fsList, (dirPath: string) => fsOps.listDir(dirPath))
- platform.handle(IPC.fsRead, (filePath: string) => fsOps.readText(filePath))
- platform.handle(IPC.fsReadBinary, (filePath: string) => fsOps.readBinary(filePath))
- platform.handle(IPC.fsWrite, (filePath: string, content: string) => fsOps.writeText(filePath, content))
- platform.handle(IPC.fsMkdir, (dirPath: string) => fsOps.makeDir(dirPath))
- platform.handle(IPC.fsExists, (p: string) => fsOps.pathExists(p))
- platform.handle(IPC.filesQuickOpen, (cwd: string) => fsOps.listQuickOpenFiles(cwd))
-}
diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.ts
index a40b8ac1e..f8bb99307 100644
--- a/src/server/handlers/index.ts
+++ b/src/server/handlers/index.ts
@@ -2,7 +2,7 @@ import type { Settings } from '../../shared/types'
import type { ServerPlatform } from '../platform-server'
import { GitService } from '../../core/git-service'
import { generateCommitMessage } from '../../core/commit-message'
-import { registerFsHandlers } from './fs'
+import { registerFsHandlers } from '../../core/fs-handlers'
import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'
import { IPC } from '../../shared/ipc'