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(remote): jailed core bridge — typed git verbs + node registration over the relay

enesedaf0475e97c
diff --git a/src/core/project-node-append.test.ts b/src/core/project-node-append.test.ts
new file mode 100644
index 000000000..9742a49f8
--- /dev/null
+++ b/src/core/project-node-append.test.ts
@@ -0,0 +1,102 @@
+import { describe, it, expect } from 'vitest'
+import { appendProjectNode } from './project-node-append'
+
+const NOW = new Date('2026-07-16T10:00:00.000Z')
+
+const baseFile = (nodes: unknown[] = [], extra: Record<string, unknown> = {}): string =>
+ JSON.stringify({
+ version: 1,
+ rev: 7,
+ savedAt: 'then',
+ id: 'p1',
+ name: 'proj',
+ color: '#ffd60a',
+ viewport: { x: 1, y: 2, zoom: 0.5 },
+ nodes,
+ ...extra
+ })
+
+const sibling = {
+ id: 'term-aaa-1',
+ kind: 'terminal',
+ position: { x: 40, y: 100 },
+ size: { width: 900, height: 500 },
+ title: 't',
+ color: '#fff',
+ group: null,
+ cwd: './sub',
+ ssh: { host: 'h', user: 'u' },
+ sshRemoteTmux: true
+}
+
+describe('appendProjectNode', () => {
+ it('appends a terminal node with host-derived defaults, bumps rev, refreshes savedAt', () => {
+ const out = appendProjectNode(baseFile([sibling]), { id: 'term-bbb-2', title: 'Mobile · 10:00' }, NOW)
+ expect(out).not.toBeNull()
+ const f = JSON.parse(out!)
+ expect(f.rev).toBe(8)
+ expect(f.savedAt).toBe('2026-07-16T10:00:00.000Z')
+ const n = f.nodes[1]
+ expect(n).toMatchObject({
+ id: 'term-bbb-2',
+ kind: 'terminal',
+ title: 'Mobile · 10:00',
+ titleAuto: true,
+ group: null,
+ collapsed: false,
+ cwd: './sub', // sibling's portable cwd
+ ssh: { host: 'h', user: 'u' }, // connection spec copied verbatim
+ sshRemoteTmux: true
+ })
+ // Placed below the lowest node, aligned to its x.
+ expect(n.position).toEqual({ x: 40, y: 100 + 500 + 40 })
+ })
+
+ it('empty canvas: defaults position/cwd, no ssh block invented', () => {
+ const f = JSON.parse(appendProjectNode(baseFile([]), { id: 'term-c-1' }, NOW)!)
+ const n = f.nodes[0]
+ expect(n.position).toEqual({ x: 100, y: 100 })
+ expect(n.cwd).toBe('.')
+ expect(n.ssh).toBeUndefined()
+ expect(n.sshRemoteTmux).toBeUndefined()
+ })
+
+ it('carries agentId only when given', () => {
+ const withAgent = JSON.parse(appendProjectNode(baseFile([]), { id: 'term-c-1', agentId: 'claude' }, NOW)!)
+ expect(withAgent.nodes[0].agentId).toBe('claude')
+ const plain = JSON.parse(appendProjectNode(baseFile([]), { id: 'term-c-2' }, NOW)!)
+ expect(plain.nodes[0].agentId).toBeUndefined()
+ })
+
+ it('round-trips fields it does not understand (future schema, bridges, dino score…)', () => {
+ const raw = baseFile([sibling], { bridges: [{ id: 'b1' }], dinoHighScore: 42, futureField: { deep: true } })
+ const f = JSON.parse(appendProjectNode(raw, { id: 'term-bbb-2' }, NOW)!)
+ expect(f.bridges).toEqual([{ id: 'b1' }])
+ expect(f.dinoHighScore).toBe(42)
+ expect(f.futureField).toEqual({ deep: true })
+ })
+
+ it('refuses: bad JSON / wrong shape / wrong version — never invents a file', () => {
+ expect(appendProjectNode('{ not json', { id: 'term-c-1' }, NOW)).toBeNull()
+ expect(appendProjectNode('{"version":99,"rev":1,"nodes":[]}', { id: 'term-c-1' }, NOW)).toBeNull()
+ expect(appendProjectNode('{"version":1}', { id: 'term-c-1' }, NOW)).toBeNull()
+ })
+
+ it('refuses a duplicate node id (a retry must not churn rev)', () => {
+ expect(appendProjectNode(baseFile([sibling]), { id: 'term-aaa-1' }, NOW)).toBeNull()
+ })
+
+ it('refuses an id that is not a safe term-<ts36>-<n> shape (it becomes a tmux session name)', () => {
+ for (const bad of ['x', 'term-a b-1', "term-a'b-1", 'term--1', 'sticky-abc-1', 'term-abc-']) {
+ expect(appendProjectNode(baseFile([]), { id: bad }, NOW)).toBeNull()
+ }
+ })
+
+ it('sanitizes title/agentId: non-strings dropped, title capped', () => {
+ const f = JSON.parse(
+ appendProjectNode(baseFile([]), { id: 'term-c-1', title: 'x'.repeat(500), agentId: 123 as never }, NOW)!
+ )
+ expect(f.nodes[0].title.length).toBeLessThanOrEqual(120)
+ expect(f.nodes[0].agentId).toBeUndefined()
+ })
+})
diff --git a/src/core/project-node-append.ts b/src/core/project-node-append.ts
new file mode 100644
index 000000000..f856fec84
--- /dev/null
+++ b/src/core/project-node-append.ts
@@ -0,0 +1,86 @@
+// Pure append of a PHONE-REGISTERED terminal node into a project.json's raw text — the host side
+// of the relay `projects.registerNode` verb (the phone's twin of this logic lives in
+// nodeterm-ios ProjectNodeRegistrar and writes over direct SSH; both converge on one node shape).
+//
+// Works on the RAW parsed object, not the typed mirrors, so every field this version does not
+// know (bridges, dino scores, future schema) round-trips untouched — the file is rewritten whole.
+// Returns null whenever nothing must be written: unparsable/wrong-shape text (a file we couldn't
+// parse must never be invented or overwritten), a duplicate id (a retry must not churn rev), or
+// an unsafe id (it becomes a tmux session name).
+
+/** What the phone is allowed to choose; everything else is host-derived. */
+export interface RemoteNodeInput {
+ id: string
+ title?: string
+ agentId?: string
+}
+
+/** The desktop id shape (`term-<base36 ms>-<n>`). Anything else is refused — the id is
+ * interpolated into tmux session names, so the alphabet stays strictly boring. */
+const SAFE_NODE_ID = /^term-[a-z0-9]+-\d{1,6}$/
+
+const TITLE_MAX = 120
+
+export function appendProjectNode(raw: string, input: RemoteNodeInput, now: Date): string | null {
+ if (!SAFE_NODE_ID.test(input.id)) return null
+ let root: Record<string, unknown>
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
+ root = parsed as Record<string, unknown>
+ } catch {
+ return null
+ }
+ if (root.version !== 1 || typeof root.rev !== 'number' || !Array.isArray(root.nodes)) return null
+ const nodes = root.nodes as Array<Record<string, unknown>>
+ if (nodes.some((n) => n?.id === input.id)) return null
+
+ const isTerminal = (n: Record<string, unknown>): boolean =>
+ ((n.kind as string | undefined) ?? 'terminal') === 'terminal'
+ const sibling = nodes.find(isTerminal)
+
+ // Place the new node just below the lowest existing node (canvas y grows downward), aligned to
+ // its x; an empty canvas starts at 100/100.
+ let x = 100
+ let y = 100
+ let lowest: { node: Record<string, unknown>; y: number } | null = null
+ for (const n of nodes) {
+ const ny = (n.position as { y?: unknown } | undefined)?.y
+ if (typeof ny !== 'number') continue
+ if (!lowest || ny > lowest.y) lowest = { node: n, y: ny }
+ }
+ if (lowest) {
+ const lx = (lowest.node.position as { x?: unknown }).x
+ x = typeof lx === 'number' ? lx : 100
+ const lh = (lowest.node.size as { height?: unknown } | undefined)?.height
+ y = lowest.y + (typeof lh === 'number' ? lh : 560) + 40
+ }
+
+ const node: Record<string, unknown> = {
+ id: input.id,
+ kind: 'terminal',
+ position: { x, y },
+ size: { width: 900, height: 560 },
+ title: typeof input.title === 'string' ? input.title.slice(0, TITLE_MAX) : 'Mobile session',
+ titleAuto: true,
+ color: '#7aa2f7',
+ group: null,
+ tags: [],
+ collapsed: false,
+ // Sibling nodes carry the project's portable cwd (usually "./…").
+ cwd: typeof sibling?.cwd === 'string' ? sibling.cwd : '.'
+ }
+ if (typeof input.agentId === 'string') node.agentId = input.agentId
+ // Desktop remote nodes carry the connection spec PER NODE — a sibling terminal in the same
+ // project has the right values; copy verbatim. No sibling with ssh → a plain local node.
+ const sshDonor = nodes.find((n) => isTerminal(n) && n.ssh !== undefined)
+ if (sshDonor) {
+ node.ssh = sshDonor.ssh
+ node.sshRemoteTmux = true
+ }
+
+ root.nodes = [...nodes, node]
+ root.rev = (root.rev as number) + 1
+ root.savedAt = now.toISOString()
+ return JSON.stringify(root, null, 2)
+}
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 3831fa5bc..d52e7f050 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -377,6 +377,39 @@ describe('projects.list relay blob (iOS wire contract)', () => {
})
})
+describe('appendRemoteNode (phone-registered sessions over the relay)', () => {
+ it('appends into a local ref project file as an OUTSIDE edit (watcher must see it)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const ok = await store.appendRemoteNode('p1', { id: 'term-zz1-1', title: 'Mobile' })
+ expect(ok).toBe(true)
+ const file = path.join(projRoot, '.nodeterm/project.json')
+ const raw = await fs.readFile(file, 'utf-8')
+ const f = JSON.parse(raw)
+ expect(f.rev).toBe(2)
+ expect(f.nodes.map((n: { id: string }) => n.id)).toContain('term-zz1-1')
+ // NOT a self-write: the workspace watcher must treat this as an outside edit and broadcast
+ // it, so the renderer adopts the node onto the live canvas.
+ expect(store.isSelfWrite(file, raw)).toBe(false)
+ })
+
+ it('refuses unknown / ssh / cwd-less projects and corrupt files (nothing written)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([
+ project({ cwd: projRoot }),
+ project({ id: 'ssh1', ssh: { server: { host: 'h', user: 'u' } as never, remoteCwd: '~/x' }, cwd: undefined }),
+ project({ id: 'inline1' })
+ ]))
+ expect(await store.appendRemoteNode('nope', { id: 'term-a1-1' })).toBe(false)
+ expect(await store.appendRemoteNode('ssh1', { id: 'term-a1-1' })).toBe(false)
+ expect(await store.appendRemoteNode('inline1', { id: 'term-a1-1' })).toBe(false)
+ const file = path.join(projRoot, '.nodeterm/project.json')
+ await fs.writeFile(file, '{ not json')
+ expect(await store.appendRemoteNode('p1', { id: 'term-a1-1' })).toBe(false)
+ expect(await fs.readFile(file, 'utf-8')).toBe('{ not json') // untouched
+ })
+})
+
describe('refreshSshProject', () => {
const sshConn = { server: { host: 'h', user: 'u' } as any, remoteCwd: '~/app' }
const remoteFileOf = async (store: WorkspaceStore, p: Project) => {
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index cf50cd044..1f06345e4 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -12,6 +12,7 @@ import {
type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3
} from './workspace-files'
import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'
+import { appendProjectNode, type RemoteNodeInput } from './project-node-append'
/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection
* down / ssh failure — a failed read is never evidence of absence, so nothing may be pushed). */
@@ -372,6 +373,34 @@ export class WorkspaceStore {
this.unmirrored.add(projectId)
}
+ /**
+ * Registers a PHONE-STARTED session as a node in a LOCAL ref project's file — the host side of
+ * the relay `projects.registerNode` verb. Deliberately written as an OUTSIDE edit
+ * (`lastWritten` untouched): the workspace watcher then broadcasts the change and the renderer
+ * adopts the node onto the live canvas, exactly like a git pull would. v1 scope: local-cwd
+ * projects only (an ssh ref's file lives on another machine; the phone reaches that one over
+ * its own SSH path).
+ */
+ async appendRemoteNode(projectId: string, input: RemoteNodeInput, now = new Date()): Promise<boolean> {
+ const e = this.index?.entries.find((x) => x.id === projectId && x.cwd)
+ if (!e?.cwd) return false
+ const file = projectFilePath(e.cwd)
+ let raw: string
+ try {
+ raw = await fs.readFile(file, 'utf-8')
+ } catch {
+ return false
+ }
+ const updated = appendProjectNode(raw, input, now)
+ if (updated === null) return false
+ try {
+ await writeAtomic(file, updated)
+ return true
+ } catch {
+ return false
+ }
+ }
+
/**
* The ONE place that decides who wins between an ssh entry's cache and the server's
* .nodeterm/project.json. Rules, in order:
diff --git a/src/main/index.ts b/src/main/index.ts
index af703c3e0..575b88ac8 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1048,7 +1048,16 @@ app.whenReady().then(async () => {
// Lazy getter: sshProjectManager is created just below, so a remote account op (which only runs
// after the user has connected an SSH project) always sees the live manager.
initClaudeAccounts(() => sshProjectManager)
- initRemoteHost(win, ptyManager, listProjectsOutput)
+ // The jailed core bridge both phone hosts serve: typed git verbs against the real GitService
+ // (cwd-jailed to the shared canvas roots inside the handlers) and phone node registration
+ // through the workspace store (written as an outside edit, so the watcher broadcasts it and
+ // the canvas adopts the node live).
+ const hostBridge = {
+ git: gitService,
+ registerNode: (projectId: string, node: { id: string; title?: string; agentId?: string }) =>
+ workspaceStore.appendRemoteNode(projectId, node)
+ }
+ initRemoteHost(win, ptyManager, listProjectsOutput, hostBridge)
// NEW interactive relay host (Stage 4): a connecting peer desktop becomes a first-class
// CorePlatform client of this desktop after mutual SAS approval. Runs BESIDE initRemoteHost (the
// phone still uses the legacy flow). Inert until `relay:host:start` — a solo user pays nothing.
@@ -1056,7 +1065,7 @@ app.whenReady().then(async () => {
initRelayHost(win, corePlatform, {})
// Standing (phone) relay host: keep a host connection registered so a paired phone can reach
// this Mac from anywhere. Honors settings.phoneAccessEnabled + the Pro gate internally.
- standingHost = initStandingHost(win, ptyManager, () => settingsStore.get(), listProjectsOutput)
+ standingHost = initStandingHost(win, ptyManager, () => settingsStore.get(), listProjectsOutput, hostBridge)
ipcMain.on(IPC.remoteStandingHostSet, (_e, enabled: boolean) => standingHost?.setEnabled(!!enabled))
// Reconcile from persisted settings on launch (starts hosting if enabled + Pro).
standingHost.syncFromSettings()
diff --git a/src/main/remote/host-git-bridge.test.ts b/src/main/remote/host-git-bridge.test.ts
new file mode 100644
index 000000000..65edbb7f6
--- /dev/null
+++ b/src/main/remote/host-git-bridge.test.ts
@@ -0,0 +1,159 @@
+// The jailed core bridge for the PHONE vocabulary: typed `git.*` verbs and
+// `projects.registerNode`, served only inside the shared roots — never free-form arguments
+// (a `git.run` would be remote command execution). Deny-by-default: no injected dep ⇒ the verb
+// is not served at all.
+import { describe, expect, it, vi } from 'vitest'
+import {
+ createHostHandlers,
+ type HostGitOps,
+ type HostPtyManager,
+ type HostRelaySocket
+} from './host-service'
+
+function makeFakes() {
+ const responses: Array<{ id: string; ok: boolean; body: unknown }> = []
+ const socket: HostRelaySocket = {
+ respond: (id, ok, body) => responses.push({ id, ok, body }),
+ sendFrame: () => true
+ }
+ const calls: Array<{ method: string; args: unknown[] }> = []
+ const rec =
+ (method: string, result: unknown) =>
+ async (...args: unknown[]) => {
+ calls.push({ method, args })
+ return result as never
+ }
+ const git: HostGitOps = {
+ status: rec('status', { branch: 'main', files: [] }),
+ diff: rec('diff', 'DIFF'),
+ stage: rec('stage', { ok: true }),
+ unstage: rec('unstage', { ok: true }),
+ commit: rec('commit', { ok: true }),
+ push: rec('push', { ok: true }),
+ pull: rec('pull', { ok: true }),
+ history: rec('history', { entries: [] })
+ }
+ const registerNode = vi.fn(async () => true)
+ return { socket, responses, calls, git, registerNode }
+}
+
+const mk = (
+ f: ReturnType<typeof makeFakes>,
+ roots: string[] = ['/work'],
+ opts: { git?: boolean; register?: boolean } = { git: true, register: true }
+) =>
+ createHostHandlers(
+ {} as HostPtyManager,
+ f.socket,
+ undefined,
+ () => roots,
+ undefined,
+ undefined,
+ opts.git ? f.git : undefined,
+ opts.register ? f.registerNode : undefined
+ )
+
+const flush = () => new Promise((r) => setTimeout(r, 0))
+
+describe('git.* verbs', () => {
+ it('serves a jailed git.status and responds with the result body', async () => {
+ const f = makeFakes()
+ mk(f).onRpc({ id: '1', method: 'git.status', params: { cwd: '/work/app' } })
+ await flush()
+ expect(f.calls).toEqual([{ method: 'status', args: ['/work/app'] }])
+ expect(f.responses).toEqual([{ id: '1', ok: true, body: { branch: 'main', files: [] } }])
+ })
+
+ it('denies a cwd outside the shared roots — explicit error, git never called', async () => {
+ const f = makeFakes()
+ mk(f).onRpc({ id: '1', method: 'git.status', params: { cwd: '/etc' } })
+ await flush()
+ expect(f.calls).toEqual([])
+ expect(f.responses).toEqual([
+ { id: '1', ok: false, body: { message: expect.stringContaining('outside') } }
+ ])
+ })
+
+ it('no git dep injected ⇒ the verbs are not served (deny-by-default)', async () => {
+ const f = makeFakes()
+ mk(f, ['/work'], { git: false, register: true }).onRpc({
+ id: '1',
+ method: 'git.status',
+ params: { cwd: '/work' }
+ })
+ await flush()
+ expect(f.responses[0].ok).toBe(false)
+ })
+
+ it('stage/unstage pass only STRING paths through (hostile arrays sanitized)', async () => {
+ const f = makeFakes()
+ const h = mk(f)
+ h.onRpc({
+ id: '1',
+ method: 'git.stage',
+ params: { cwd: '/work', paths: ['a.ts', 5, null, { x: 1 }, 'b.ts'] }
+ })
+ await flush()
+ expect(f.calls).toEqual([{ method: 'stage', args: ['/work', ['a.ts', 'b.ts']] }])
+ })
+
+ it('commit forwards the message; diff forwards path/staged/untracked', async () => {
+ const f = makeFakes()
+ const h = mk(f)
+ h.onRpc({ id: '1', method: 'git.commit', params: { cwd: '/work', message: 'msg' } })
+ h.onRpc({
+ id: '2',
+ method: 'git.diff',
+ params: { cwd: '/work', path: 'a.ts', staged: true, untracked: false }
+ })
+ await flush()
+ expect(f.calls).toEqual([
+ { method: 'commit', args: ['/work', 'msg'] },
+ { method: 'diff', args: ['/work', 'a.ts', true, false] }
+ ])
+ })
+
+ it('push/pull/history are served jailed like the rest', async () => {
+ const f = makeFakes()
+ const h = mk(f)
+ h.onRpc({ id: '1', method: 'git.push', params: { cwd: '/work' } })
+ h.onRpc({ id: '2', method: 'git.pull', params: { cwd: '/etc' } }) // denied
+ h.onRpc({ id: '3', method: 'git.history', params: { cwd: '/work' } })
+ await flush()
+ expect(f.calls.map((c) => c.method)).toEqual(['push', 'history'])
+ expect(f.responses.find((r) => r.id === '2')?.ok).toBe(false)
+ })
+})
+
+describe('projects.registerNode', () => {
+ it('routes to the injected registrar and reports its outcome', async () => {
+ const f = makeFakes()
+ mk(f).onRpc({
+ id: '1',
+ method: 'projects.registerNode',
+ params: { projectId: 'p1', node: { id: 'term-abc-1', title: 'Mobile', agentId: 'claude' } }
+ })
+ await flush()
+ expect(f.registerNode).toHaveBeenCalledWith('p1', { id: 'term-abc-1', title: 'Mobile', agentId: 'claude' })
+ expect(f.responses).toEqual([{ id: '1', ok: true, body: { registered: true } }])
+ })
+
+ it('a refused registration (bad shape / unknown project) reports registered:false', async () => {
+ const f = makeFakes()
+ f.registerNode.mockResolvedValueOnce(false as never)
+ mk(f).onRpc({ id: '1', method: 'projects.registerNode', params: { projectId: 'p1', node: { id: 'x' } } })
+ await flush()
+ expect(f.responses).toEqual([{ id: '1', ok: true, body: { registered: false } }])
+ })
+
+ it('no registrar injected ⇒ not served', async () => {
+ const f = makeFakes()
+ mk(f, ['/work'], { git: true, register: false }).onRpc({
+ id: '1',
+ method: 'projects.registerNode',
+ params: { projectId: 'p1', node: { id: 'term-a-1' } }
+ })
+ await flush()
+ expect(f.responses[0].ok).toBe(false)
+ })
+})
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 49c2460ec..e73742346 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -100,6 +100,21 @@ export interface HostFsOps {
writeText(filePath: string, content: string): Promise<boolean>
}
+// The slice of GitService the host serves over `git.*` RPC — the jailed core bridge that lets a
+// relay-only phone (no direct SSH) run the source-control sheet in ONE round trip per operation
+// instead of N ssh execs. Strictly TYPED verbs: a free-form `git.run` would be remote command
+// execution. Same cwd jail as `fs.*` (isWithinRoots); no injected instance ⇒ not served at all.
+export interface HostGitOps {
+ status(cwd: string): Promise<unknown>
+ diff(cwd: string, path: string, staged: boolean, untracked: boolean): Promise<string>
+ stage(cwd: string, paths: string[]): Promise<unknown>
+ unstage(cwd: string, paths: string[]): Promise<unknown>
+ commit(cwd: string, message: string): Promise<unknown>
+ push(cwd: string): Promise<unknown>
+ pull(cwd: string): Promise<unknown>
+ history(cwd: string): Promise<unknown>
+}
+
interface Stream {
sessionId: string
/** The node id (tmux persistKey) this stream attached to. The ONLY tmux target a client can
@@ -162,7 +177,12 @@ export function createHostHandlers(
// session's PhonePresence outlives none of it. It makes the phone's keystrokes attributable —
// the "X is typing" badge for a relay peer costs the iOS app exactly nothing, because the sender
// is the identified HostSession, not something the client claims.
- getClientId: () => number | null = () => null
+ getClientId: () => number | null = () => null,
+ // Typed git bridge (jailed to the shared roots). Absent ⇒ `git.*` verbs are not served.
+ git?: HostGitOps,
+ // Registers a phone-started session as a project node (WorkspaceStore.appendRemoteNode).
+ // Absent ⇒ `projects.registerNode` is not served.
+ registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
@@ -335,6 +355,78 @@ export function createHostHandlers(
socket.respond(req.id, true, {})
}
+ // Serve a typed `git.*` verb against the injected GitService slice, jailed to the shared roots
+ // like `fs.*`. Unlike fs (silent empty degrade — the Explorer just shows nothing), a denied or
+ // failed git op answers with an EXPLICIT error: the source-control sheet must say why.
+ function handleGit(req: RpcRequest): void {
+ if (!git) {
+ socket.respond(req.id, false, { message: 'git is not served on this host.' })
+ return
+ }
+ const p = asRecord(req.params)
+ const cwd = str(p.cwd) ?? ''
+ if (!isWithinRoots(cwd, getRoots())) {
+ socket.respond(req.id, false, { message: 'cwd is outside the shared project roots.' })
+ return
+ }
+ const strings = (v: unknown): string[] =>
+ Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string') : []
+ const run = (): Promise<unknown> => {
+ switch (req.method) {
+ case 'git.status':
+ return git.status(cwd)
+ case 'git.diff':
+ return git.diff(cwd, str(p.path) ?? '', p.staged === true, p.untracked === true)
+ case 'git.stage':
+ return git.stage(cwd, strings(p.paths))
+ case 'git.unstage':
+ return git.unstage(cwd, strings(p.paths))
+ case 'git.commit':
+ return git.commit(cwd, str(p.message) ?? '')
+ case 'git.push':
+ return git.push(cwd)
+ case 'git.pull':
+ return git.pull(cwd)
+ case 'git.history':
+ return git.history(cwd)
+ default:
+ return Promise.reject(new Error(`Unknown git verb: ${req.method}`))
+ }
+ }
+ void run()
+ .then((body) => socket.respond(req.id, true, body ?? {}))
+ .catch((err: unknown) =>
+ socket.respond(req.id, false, { message: (err as Error)?.message ?? 'git failed' })
+ )
+ }
+
+ // Register a phone-started session as a project node. Validation (safe id shape, duplicate,
+ // parsable local project file) lives in the registrar (WorkspaceStore.appendRemoteNode →
+ // appendProjectNode); a refusal is an ok:{registered:false} answer, not a protocol error —
+ // the phone opened its session either way and just stays unregistered.
+ function handleRegisterNode(req: RpcRequest): void {
+ if (!registerNode) {
+ socket.respond(req.id, false, { message: 'projects.registerNode is not served on this host.' })
+ return
+ }
+ const p = asRecord(req.params)
+ const node = asRecord(p.node)
+ const id = str(node.id)
+ const projectId = str(p.projectId)
+ if (!id || !projectId) {
+ socket.respond(req.id, false, { message: 'projects.registerNode requires projectId and node.id.' })
+ return
+ }
+ const input: { id: string; title?: string; agentId?: string } = { id }
+ const title = str(node.title)
+ if (title !== undefined) input.title = title
+ const agentId = str(node.agentId)
+ if (agentId !== undefined) input.agentId = agentId
+ void registerNode(projectId, input)
+ .then((registered) => socket.respond(req.id, true, { registered }))
+ .catch(() => socket.respond(req.id, true, { registered: false }))
+ }
+
function handleKill(req: RpcRequest): void {
const streamId = num(asRecord(req.params).streamId, -1)
const stream = streams.get(streamId)
@@ -369,6 +461,19 @@ export function createHostHandlers(
case 'fs.write':
handleFs(req)
break
+ case 'git.status':
+ case 'git.diff':
+ case 'git.stage':
+ case 'git.unstage':
+ case 'git.commit':
+ case 'git.push':
+ case 'git.pull':
+ case 'git.history':
+ handleGit(req)
+ break
+ case 'projects.registerNode':
+ handleRegisterNode(req)
+ break
case 'projects.list':
// Read-only enumeration of the host's projects/sessions/agent-status (no client params —
// nothing to jail). Gated by the same pre-handler approval check in connectHostSession, so
@@ -586,6 +691,10 @@ export interface HostSessionOptions {
* presence slot serves input exactly as before, unbadged.
*/
getClientId?: () => number | null
+ /** Typed, jailed `git.*` bridge (see HostGitOps). Optional: absent ⇒ the verbs are not served. */
+ git?: HostGitOps
+ /** Registers a phone-started session as a project node (`projects.registerNode`). Optional. */
+ registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
/**
* A peer completed the E2EE handshake and awaits an approval decision. The caller inspects the
* session (sas / peerPublicKeyB64) and either approves immediately (pin-once) or prompts the
@@ -700,7 +809,9 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
fsOps,
() => rootsFromCanvas(opts.getLatestCanvas()),
opts.listProjects ?? (async () => ''),
- opts.getClientId ?? (() => null)
+ opts.getClientId ?? (() => null),
+ opts.git,
+ opts.registerNode
)
canvasSync = createHostCanvasSync(socket, opts.applyMutation)
unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())
@@ -715,10 +826,18 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
* the relay as host, and returns the offer string. `remote:host:stop` closes the relay socket
* (which kills the served PTYs and drops the client's access).
*/
+/** The optional core-bridge deps both hosts thread into connectHostSession (jailed git verbs +
+ * phone node registration). One bag so the init signatures stop growing positionally. */
+export interface HostBridgeDeps {
+ git?: HostGitOps
+ registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
+}
+
export function initRemoteHost(
win: BrowserWindow,
ptyManager: PtyManager,
- listProjects: () => Promise<string> = async () => ''
+ listProjects: () => Promise<string> = async () => '',
+ bridge: HostBridgeDeps = {}
): void {
initHostCanvasHub()
let session: HostSession | null = null
@@ -777,6 +896,8 @@ export function initRemoteHost(
subscribeCanvas,
applyMutation: (mutation) => send(IPC.remoteHostApplyMutation, mutation),
listProjects,
+ git: bridge.git,
+ registerNode: bridge.registerNode,
// Typing attribution: this session's input frames are this phone's keystrokes.
getClientId: () => phone.id(),
// Interactive host: surface the SAS + a fresh pending id so the human can verify + approve.
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index a762bc0c8..06096ffd6 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -34,6 +34,7 @@ import {
connectHostSession,
loadOrCreateKeyPair,
relayAllowed,
+ type HostBridgeDeps,
type HostSession
} from './host-service'
import { currentCanvas, initHostCanvasHub, subscribeCanvas } from './host-canvas-hub'
@@ -138,7 +139,8 @@ export function initStandingHost(
win: BrowserWindow,
ptyManager: PtyManager,
getSettings: () => Settings,
- listProjects: () => Promise<string> = async () => ''
+ listProjects: () => Promise<string> = async () => '',
+ bridge: HostBridgeDeps = {}
): StandingHost {
initHostCanvasHub()
@@ -371,6 +373,8 @@ export function initStandingHost(
subscribeCanvas,
applyMutation: (mutation: CanvasMutation) => send(IPC.remoteHostApplyMutation, mutation),
listProjects,
+ git: bridge.git,
+ registerNode: bridge.registerNode,
// Typing attribution: this pooled session's input frames are ITS phone's keystrokes.
getClientId: () => pooled.presence.id(),
onPeerReady: () => void onPeerReady(pooled),