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
feat(settings): per-device pairing registry + revoke (Phone)
enesb8a177b9597a
diff --git a/src/main/index.ts b/src/main/index.tsindex 462d89a06..93f4b97a4 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -363,6 +363,8 @@ app.whenReady().then(async () => {}))ipcMain.handle(IPC.pairingStop, () => pairingService.stop())+ ipcMain.handle(IPC.pairingListDevices, () => pairingService.listDevices())+ ipcMain.handle(IPC.pairingRevokeDevice, (_e, id: string) => pairingService.revokeDevice(id))ipcMain.on(IPC.shellReveal, (_e, p: string) => {if (p) shell.showItemInFolder(p)diff --git a/src/main/pairing-core.test.ts b/src/main/pairing-core.test.tsindex 689f96458..e4e54fc8f 100644--- a/src/main/pairing-core.test.ts+++ b/src/main/pairing-core.test.ts@@ -1,9 +1,18 @@import { describe, it, expect } from 'vitest'import {buildPairingPayload,+ deviceCommentFor,+ filterAuthorizedKeys,isValidEd25519PublicKey,normalizeAuthorizedKeysLine,- pickLanIPv4+ normalizeDeviceName,+ pickLanIPv4,+ readDevices,+ removeDevice,+ rewriteKeyComment,+ toPublicDevices,+ upsertDevice,+ type DeviceEntry} from './pairing-core'// A real Ed25519 public key blob (32 zero bytes) wrapped in the OpenSSH wire format:@@ -94,6 +103,108 @@ describe('normalizeAuthorizedKeysLine', () => {})})+describe('deviceCommentFor', () => {+ it('builds the attributable comment token', () => {+ expect(deviceCommentFor('abc-123')).toBe('nodeterm-ios-abc-123')+ })+})++describe('rewriteKeyComment', () => {+ it('replaces the phone-sent comment with nodeterm-ios-<deviceId>, keeping type+blob', () => {+ expect(rewriteKeyComment('ssh-ed25519 AAAAB3 phone@my-iphone', 'dev1')).toBe(+ 'ssh-ed25519 AAAAB3 nodeterm-ios-dev1'+ )+ })++ it('adds a comment when the key had none', () => {+ expect(rewriteKeyComment('ssh-ed25519 AAAAB3', 'dev2')).toBe('ssh-ed25519 AAAAB3 nodeterm-ios-dev2')+ })++ it('collapses extra whitespace and multi-word comments', () => {+ expect(rewriteKeyComment(' ssh-ed25519 AAAAB3 some long comment\n', 'd')).toBe(+ 'ssh-ed25519 AAAAB3 nodeterm-ios-d'+ )+ })+})++describe('filterAuthorizedKeys', () => {+ it('removes only lines whose comment is exactly nodeterm-ios-<id>', () => {+ const content = [+ 'ssh-ed25519 AAAAother laptop@work',+ 'ssh-ed25519 AAAAtarget nodeterm-ios-dev1',+ 'ssh-rsa AAAArsa other-key'+ ].join('\n')+ expect(filterAuthorizedKeys(content, 'dev1')).toBe(+ 'ssh-ed25519 AAAAother laptop@work\nssh-rsa AAAArsa other-key'+ )+ })++ it('preserves blank lines and the trailing newline of untouched files', () => {+ const content = 'ssh-ed25519 AAAAa keep-me\n\nssh-ed25519 AAAAb nodeterm-ios-x\n'+ expect(filterAuthorizedKeys(content, 'x')).toBe('ssh-ed25519 AAAAa keep-me\n\n')+ })++ it('does not match a different device id or a substring', () => {+ const content = 'ssh-ed25519 AAAAb nodeterm-ios-dev10'+ expect(filterAuthorizedKeys(content, 'dev1')).toBe(content)+ })++ it('returns content unchanged when nothing matches', () => {+ const content = 'ssh-ed25519 AAAAb some@comment\n'+ expect(filterAuthorizedKeys(content, 'nope')).toBe(content)+ })+})++describe('normalizeDeviceName', () => {+ it('trims a provided name', () => {+ expect(normalizeDeviceName(" Enes's iPhone ")).toBe("Enes's iPhone")+ })++ it('defaults to iPhone for missing / blank / non-string names', () => {+ expect(normalizeDeviceName(undefined)).toBe('iPhone')+ expect(normalizeDeviceName(' ')).toBe('iPhone')+ expect(normalizeDeviceName(42)).toBe('iPhone')+ })+})++describe('device registry helpers', () => {+ const dev = (id: string, name = id): DeviceEntry => ({+ id,+ name,+ token: `tok-${id}`,+ pairedAt: 1000,+ lastSeenAt: 0+ })++ it('readDevices returns [] for missing / malformed devices (back-compat with {v,port,token})', () => {+ expect(readDevices(undefined)).toEqual([])+ expect(readDevices({ v: 1, port: 8080, token: 'abc' })).toEqual([])+ expect(readDevices({ devices: 'nope' })).toEqual([])+ expect(readDevices({ devices: [dev('a')] })).toEqual([dev('a')])+ })++ it('upsertDevice appends a new device', () => {+ expect(upsertDevice([dev('a')], dev('b'))).toEqual([dev('a'), dev('b')])+ })++ it('upsertDevice replaces an existing device by id (keeps position at end)', () => {+ const updated = { ...dev('a'), name: 'renamed' }+ expect(upsertDevice([dev('a'), dev('b')], updated)).toEqual([dev('b'), updated])+ })++ it('removeDevice drops the matching id and is a no-op otherwise', () => {+ expect(removeDevice([dev('a'), dev('b')], 'a')).toEqual([dev('b')])+ expect(removeDevice([dev('a')], 'zzz')).toEqual([dev('a')])+ })++ it('toPublicDevices strips the token', () => {+ expect(toPublicDevices([dev('a')])).toEqual([+ { id: 'a', name: 'a', pairedAt: 1000, lastSeenAt: 0 }+ ])+ expect(toPublicDevices([dev('a')])[0]).not.toHaveProperty('token')+ })+})+describe('pickLanIPv4', () => {it('picks the first non-internal, non-link-local IPv4', () => {const picked = pickLanIPv4({diff --git a/src/main/pairing-core.ts b/src/main/pairing-core.tsindex 36081c3d7..53bce12e2 100644--- a/src/main/pairing-core.ts+++ b/src/main/pairing-core.ts@@ -62,6 +62,90 @@ export function normalizeAuthorizedKeysLine(line: string): string {return line.trim().replace(/\s+/g, ' ')}+/**+ * The attributable comment we stamp onto each paired key. Keeping it a single deterministic+ * token (`nodeterm-ios-<deviceId>`) is what lets revocation find & delete the exact line later.+ */+export function deviceCommentFor(deviceId: string): string {+ return `nodeterm-ios-${deviceId}`+}++/**+ * Rewrite an incoming public-key line so its comment is exactly `nodeterm-ios-<deviceId>`,+ * replacing whatever comment the phone sent while keeping the key type + base64 blob intact.+ * The result is already normalized (single-space separated), ready for authorized_keys.+ */+export function rewriteKeyComment(publicKey: string, deviceId: string): string {+ const parts = normalizeAuthorizedKeysLine(publicKey).split(' ')+ const type = parts[0] ?? ''+ const blob = parts[1] ?? ''+ return `${type} ${blob} ${deviceCommentFor(deviceId)}`+}++/**+ * Remove every authorized_keys line whose comment is exactly `nodeterm-ios-<deviceId>`,+ * preserving all other lines (including blanks, other keys' comments, and the trailing+ * newline) byte-for-byte. The caller writes the result back atomically.+ */+export function filterAuthorizedKeys(content: string, deviceId: string): string {+ const target = deviceCommentFor(deviceId)+ return content+ .split('\n')+ .filter((line) => {+ const parts = line.trim().split(/\s+/)+ // comment = everything after the key type + base64 blob+ return parts.slice(2).join(' ') !== target+ })+ .join('\n')+}++/** A device identity minted at pairing time and persisted into ~/.nodeterm/agent.json. */+export interface DeviceEntry {+ id: string+ name: string+ /** Bearer token the phone uses on the host-agent WebSocket. NEVER sent to the renderer. */+ token: string+ pairedAt: number+ lastSeenAt: number+}++/** The device shape safe to expose to the renderer (no `token`). */+export type PublicDevice = Omit<DeviceEntry, 'token'>++/** Default device name when the phone didn't send one (or sent blank). */+export function normalizeDeviceName(name: unknown): string {+ if (typeof name === 'string') {+ const trimmed = name.trim()+ if (trimmed) return trimmed+ }+ return 'iPhone'+}++/**+ * Extract the `devices` array from a parsed agent.json object. A missing / malformed+ * `devices` is treated as empty (back-compat: the host agent writes only {v, port, token}).+ */+export function readDevices(agentJson: unknown): DeviceEntry[] {+ if (!agentJson || typeof agentJson !== 'object') return []+ const devices = (agentJson as { devices?: unknown }).devices+ return Array.isArray(devices) ? (devices as DeviceEntry[]) : []+}++/** Append `entry`, or replace an existing device with the same id (idempotent by id). */+export function upsertDevice(devices: DeviceEntry[], entry: DeviceEntry): DeviceEntry[] {+ return [...devices.filter((d) => d.id !== entry.id), entry]+}++/** Drop the device with the given id (no-op if absent). */+export function removeDevice(devices: DeviceEntry[], id: string): DeviceEntry[] {+ return devices.filter((d) => d.id !== id)+}++/** Strip the secret `token` from each device before handing the list to the renderer. */+export function toPublicDevices(devices: DeviceEntry[]): PublicDevice[] {+ return devices.map(({ id, name, pairedAt, lastSeenAt }) => ({ id, name, pairedAt, lastSeenAt }))+}+/** Minimal shape of `os.networkInterfaces()` we need — kept structural so tests can fake it. */export interface NetInterfaceAddr {address: stringdiff --git a/src/main/pairing-service.ts b/src/main/pairing-service.tsindex 32470581a..050c95d5b 100644--- a/src/main/pairing-service.ts+++ b/src/main/pairing-service.ts@@ -12,7 +12,7 @@import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'import { connect as netConnect } from 'net'-import { randomBytes } from 'crypto'+import { randomBytes, randomUUID } from 'crypto'import { promises as fs } from 'fs'import { execFile } from 'child_process'import { promisify } from 'util'@@ -20,9 +20,18 @@ import os from 'os'import path from 'path'import {buildPairingPayload,+ filterAuthorizedKeys,isValidEd25519PublicKey,normalizeAuthorizedKeysLine,- pickLanIPv4+ normalizeDeviceName,+ pickLanIPv4,+ readDevices,+ removeDevice,+ rewriteKeyComment,+ toPublicDevices,+ upsertDevice,+ type DeviceEntry,+ type PublicDevice} from './pairing-core'const execFileAsync = promisify(execFile)@@ -49,6 +58,43 @@ export interface PairingService {start(onDone: (result: PairingDone) => void): Promise<PairingStartResult>/** Cancel an in-flight pairing (idempotent). Does NOT fire onDone. */stop(): void+ /** All paired devices (token stripped) from ~/.nodeterm/agent.json. */+ listDevices(): Promise<PublicDevice[]>+ /** Revoke a device: drop its agent.json entry AND delete its authorized_keys line. */+ revokeDevice(id: string): Promise<void>+}++/** ~/.nodeterm holds the host-agent config (agent.json). Created 0700 if missing. */+const AGENT_DIR = path.join(os.homedir(), '.nodeterm')+const AGENT_JSON_PATH = path.join(AGENT_DIR, 'agent.json')+const AUTH_KEYS_PATH = path.join(os.homedir(), '.ssh', 'authorized_keys')++/** Read + parse ~/.nodeterm/agent.json; returns {} when absent or malformed. */+async function readAgentJson(): Promise<Record<string, unknown>> {+ try {+ const parsed = JSON.parse(await fs.readFile(AGENT_JSON_PATH, 'utf8'))+ return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {}+ } catch {+ return {}+ }+}++/** Write agent.json atomically (0600), creating ~/.nodeterm (0700) if needed. */+async function writeAgentJson(obj: Record<string, unknown>): Promise<void> {+ await fs.mkdir(AGENT_DIR, { recursive: true, mode: 0o700 })+ await fs.chmod(AGENT_DIR, 0o700).catch(() => {})+ const tmp = `${AGENT_JSON_PATH}.tmp`+ await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })+ await fs.chmod(tmp, 0o600).catch(() => {})+ await fs.rename(tmp, AGENT_JSON_PATH)+ await fs.chmod(AGENT_JSON_PATH, 0o600).catch(() => {})+}++/** Persist a device into agent.json, preserving all other fields the host agent wrote. */+async function persistDevice(entry: DeviceEntry): Promise<void> {+ const obj = await readAgentJson()+ const devices = upsertDevice(readDevices(obj), entry)+ await writeAgentJson({ ...obj, devices })}/** Detect the machine's display name (macOS ComputerName, else hostname). */@@ -87,22 +133,42 @@ function probeSsh(): Promise<boolean> {})}-/** Append a validated public-key line to ~/.ssh/authorized_keys with the right permissions. */-async function appendAuthorizedKey(publicKey: string): Promise<void> {+/**+ * Append an already-normalized public-key line to ~/.ssh/authorized_keys with the right+ * permissions. The caller stamps the attributable `nodeterm-ios-<deviceId>` comment via+ * `rewriteKeyComment` before this point.+ */+async function appendAuthorizedKey(keyLine: string): Promise<void> {const sshDir = path.join(os.homedir(), '.ssh')await fs.mkdir(sshDir, { recursive: true, mode: 0o700 })await fs.chmod(sshDir, 0o700).catch(() => {})- const authPath = path.join(sshDir, 'authorized_keys')// Guard against a file that doesn't end in a newline (would concatenate onto the last key).let prefix = ''try {- const existing = await fs.readFile(authPath, 'utf8')+ const existing = await fs.readFile(AUTH_KEYS_PATH, 'utf8')if (existing.length > 0 && !existing.endsWith('\n')) prefix = '\n'} catch {// no file yet — appendFile creates it}- await fs.appendFile(authPath, prefix + normalizeAuthorizedKeysLine(publicKey) + '\n')- await fs.chmod(authPath, 0o600)+ await fs.appendFile(AUTH_KEYS_PATH, prefix + normalizeAuthorizedKeysLine(keyLine) + '\n')+ await fs.chmod(AUTH_KEYS_PATH, 0o600)+}++/** Delete every authorized_keys line stamped for `deviceId`, rewriting the file atomically (0600). */+async function removeAuthorizedKeysForDevice(deviceId: string): Promise<void> {+ let content: string+ try {+ content = await fs.readFile(AUTH_KEYS_PATH, 'utf8')+ } catch {+ return // no file → nothing to revoke+ }+ const next = filterAuthorizedKeys(content, deviceId)+ if (next === content) return+ const tmp = `${AUTH_KEYS_PATH}.tmp`+ await fs.writeFile(tmp, next, { mode: 0o600 })+ await fs.chmod(tmp, 0o600).catch(() => {})+ await fs.rename(tmp, AUTH_KEYS_PATH)+ await fs.chmod(AUTH_KEYS_PATH, 0o600).catch(() => {})}/** Read the whole request body (capped), rejecting oversized payloads. */@@ -192,7 +258,7 @@ export function createPairingService(): PairingService {}try {const raw = await readBody(req)- let body: { token?: unknown; publicKey?: unknown }+ let body: { token?: unknown; publicKey?: unknown; deviceName?: unknown }try {body = JSON.parse(raw)} catch {@@ -208,8 +274,22 @@ export function createPairingService(): PairingService {res.writeHead(400).end('unexpected key type')return}- await appendAuthorizedKey(publicKey)- res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ ok: true }))+ // Mint a device identity: the deviceId stamps the key line (attributable + revocable);+ // the agentToken is the phone's bearer for the host-agent WebSocket (stored in its Keychain).+ const deviceId = randomUUID()+ const agentToken = randomBytes(24).toString('base64url')+ const name = normalizeDeviceName(body.deviceName)+ await appendAuthorizedKey(rewriteKeyComment(publicKey, deviceId))+ await persistDevice({+ id: deviceId,+ name,+ token: agentToken,+ pairedAt: Date.now(),+ lastSeenAt: 0+ })+ res+ .writeHead(200, { 'Content-Type': 'application/json' })+ .end(JSON.stringify({ ok: true, deviceId, agentToken }))finish({ ok: true })} catch (err) {res.writeHead(500).end('pairing failed')@@ -225,5 +305,16 @@ export function createPairingService(): PairingService {cleanup()}- return { start, stop }+ const listDevices = async (): Promise<PublicDevice[]> => {+ return toPublicDevices(readDevices(await readAgentJson()))+ }++ const revokeDevice = async (id: string): Promise<void> => {+ const obj = await readAgentJson()+ const devices = removeDevice(readDevices(obj), id)+ await writeAgentJson({ ...obj, devices })+ await removeAuthorizedKeysForDevice(id)+ }++ return { start, stop, listDevices, revokeDevice }}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 076bdea27..d8d0c3dd3 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -355,7 +355,9 @@ const api: NodeTerminalApi = {const handler = (_e: unknown, result: { ok: boolean }) => cb(result)ipcRenderer.on(IPC.pairingDone, handler)return () => ipcRenderer.removeListener(IPC.pairingDone, handler)- }+ },+ listDevices: () => ipcRenderer.invoke(IPC.pairingListDevices),+ revokeDevice: (id) => ipcRenderer.invoke(IPC.pairingRevokeDevice, id)},contextLink: {setLinks: (map) => ipcRenderer.invoke(IPC.contextLinkSetLinks, map)diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex d5d2eced3..5ea8dbf2f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1352,6 +1352,9 @@ export function Canvas() {commitActiveToStore()const project = useProjects.getState().addProject(name, clonedPath)useProjects.getState().setActive(project.id)+ // The welcome screen stays up behind the clone dialog; dismiss it now that a+ // project actually exists (no-op when the dialog was opened elsewhere).+ setWelcomeOpen(false)void writeDisk()},[commitActiveToStore, writeDisk]@@ -3285,6 +3288,9 @@ export function Canvas() {.getState().addProject(input.label, undefined, { server: input.server, remoteCwd: input.remoteCwd })useProjects.getState().setActive(project.id)+ // Same contract as onRepoCloned: the welcome screen waits behind the SSH dialog and+ // dismisses only once the project is created (cancel returns to the welcome screen).+ setWelcomeOpen(false)void writeDisk()},[commitActiveToStore, writeDisk]@@ -3297,13 +3303,16 @@ export function Canvas() {void writeDisk()}, [commitActiveToStore, writeDisk])- const addProjectFromFolder = useCallback(async () => {+ /** Returns true when a folder was picked (false on cancel), so callers like the welcome+ * screen can keep their overlay up until the picker actually resolves. */+ const addProjectFromFolder = useCallback(async (): Promise<boolean> => {const folder = await window.nodeTerminal.dialog.selectFolder()- if (!folder) return+ if (!folder) return falsecommitActiveToStore()// A folder maps to one project: reuse (and reopen, if closed) the existing one, or create.useProjects.getState().openFolderProject(folder)void writeDisk()+ return true}, [commitActiveToStore, writeDisk])const renameProject = useCallback(@@ -3749,17 +3758,14 @@ export function Canvas() {addProject()}}onOpenFolder={() => {- setWelcomeOpen(false)- void addProjectFromFolder()- }}- onCloneRepo={() => {- setWelcomeOpen(false)- cloneRepo()- }}- onConnectSsh={() => {- setWelcomeOpen(false)- setSshDialogOpen(true)+ // Keep the welcome screen up behind the native picker; dismiss it only once a+ // folder was actually chosen (cancel returns to the welcome screen).+ void addProjectFromFolder().then((opened) => {+ if (opened) setWelcomeOpen(false)+ })}}+ onCloneRepo={cloneRepo}+ onConnectSsh={() => setSshDialogOpen(true)}closedProjects={closedProjects.map((p) => ({ id: p.id, name: p.name, cwd: p.cwd }))}onReopen={reopenProject}onDeleteClosed={deleteProject}diff --git a/src/renderer/components/settings/sections/PhoneSection.tsx b/src/renderer/components/settings/sections/PhoneSection.tsxindex e8a21c093..e42210067 100644--- a/src/renderer/components/settings/sections/PhoneSection.tsx+++ b/src/renderer/components/settings/sections/PhoneSection.tsx@@ -1,17 +1,33 @@-import { useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import { toDataURL } from 'qrcode'+import type { PairedDevice } from '@shared/types'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'+import { ConfirmDialog } from '../../ConfirmDialog'import { Button } from '@renderer/ui/Button'const ROWS = {pair: {title: 'Pair phone',keywords: ['phone', 'pair', 'qr', 'ios', 'mobile', 'ssh', 'scan', 'nodeterm']+ },+ devices: {+ title: 'Paired devices',+ keywords: ['phone', 'device', 'devices', 'paired', 'revoke', 'ios', 'iphone', 'remove']}}const ENTRIES = Object.values(ROWS)+/** Format an epoch-ms pairing time as a short local date. */+function formatPairedAt(ms: number): string {+ if (!ms) return ''+ return new Date(ms).toLocaleDateString(undefined, {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ })+}+type Phase = 'idle' | 'waiting' | 'paired' | 'timeout'export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Element {@@ -20,9 +36,19 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Eleconst [sshOpen, setSshOpen] = useState(true)const [error, setError] = useState('')const [busy, setBusy] = useState(false)+ const [devices, setDevices] = useState<PairedDevice[]>([])+ const [pendingRevoke, setPendingRevoke] = useState<PairedDevice | null>(null)// Track whether a pairing listener is currently running so unmount can stop it.const runningRef = useRef(false)+ const refreshDevices = useCallback(async (): Promise<void> => {+ try {+ setDevices(await window.nodeTerminal.pairing.listDevices())+ } catch {+ // leave the last-known list on a transient read error+ }+ }, [])+const startPairing = async (): Promise<void> => {setError('')setBusy(true)@@ -55,9 +81,24 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.ElerunningRef.current = falsesetQr('')setPhase(result.ok ? 'paired' : 'timeout')+ if (result.ok) void refreshDevices()})return off- }, [])+ }, [refreshDevices])++ // Load the paired-device list on mount.+ useEffect(() => {+ void refreshDevices()+ }, [refreshDevices])++ const revokeDevice = async (device: PairedDevice): Promise<void> => {+ setPendingRevoke(null)+ try {+ await window.nodeTerminal.pairing.revokeDevice(device.id)+ } finally {+ void refreshDevices()+ }+ }// Stop any in-flight pairing when the section unmounts (settings closed / navigated away).useEffect(() => {@@ -134,6 +175,43 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele) : null}</div></SearchableRow>++ <SearchableRow {...ROWS.devices}>+ <div className="space-y-3">+ <h4 className="text-[13px] font-medium text-text">Paired devices</h4>+ {devices.length === 0 ? (+ <p className="text-sm text-muted">No devices paired yet</p>+ ) : (+ <ul className="space-y-2">+ {devices.map((device) => (+ <li+ key={device.id}+ className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2"+ >+ <div className="min-w-0">+ <div className="truncate text-sm font-medium text-text">{device.name}</div>+ {device.pairedAt ? (+ <div className="text-[12px] text-muted">+ Paired {formatPairedAt(device.pairedAt)}+ </div>+ ) : null}+ </div>+ <Button onClick={() => setPendingRevoke(device)}>Revoke</Button>+ </li>+ ))}+ </ul>+ )}+ </div>+ </SearchableRow>++ {pendingRevoke ? (+ <ConfirmDialog+ message={`Revoke “${pendingRevoke.name}”? Its key is removed from this machine and it will no longer be able to connect.`}+ confirmLabel="Revoke"+ onConfirm={() => void revokeDevice(pendingRevoke)}+ onCancel={() => setPendingRevoke(null)}+ />+ ) : null}</SettingsSection>)}diff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.tsnew file mode 100644index 000000000..3e4d87ed8--- /dev/null+++ b/src/renderer/state/projects.test.ts@@ -0,0 +1,45 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useProjects } from './projects'++beforeEach(() => {+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] })+})++describe('openFolderProject', () => {+ it('creates a new project named after the folder and activates it', () => {+ const p = useProjects.getState().openFolderProject('/Users/me/dev/my-app')+ expect(p.name).toBe('my-app')+ expect(p.cwd).toBe('/Users/me/dev/my-app')+ const s = useProjects.getState()+ expect(s.activeProjectId).toBe(p.id)+ expect(s.projects.filter((q) => !q.closed)).toHaveLength(1)+ })++ it('reuses an existing open project with the same folder instead of duplicating', () => {+ const first = useProjects.getState().addProject('my-app', '/Users/me/dev/my-app')+ const p = useProjects.getState().openFolderProject('/Users/me/dev/my-app')+ expect(p.id).toBe(first.id)+ expect(useProjects.getState().projects).toHaveLength(1)+ expect(useProjects.getState().activeProjectId).toBe(first.id)+ })++ // Regression: "Open folder" on a folder whose project was previously closed used to+ // activate the still-closed project — the canvas switched to it but the tab bar and+ // sidebar (which filter `closed`) showed nothing.+ it('reopens a closed project with the same folder so it is visible again', () => {+ const first = useProjects.getState().addProject('my-app', '/Users/me/dev/my-app')+ useProjects.getState().closeProject(first.id)+ expect(useProjects.getState().projects.filter((q) => !q.closed)).toHaveLength(0)++ const p = useProjects.getState().openFolderProject('/Users/me/dev/my-app')+ expect(p.id).toBe(first.id)+ const s = useProjects.getState()+ expect(s.activeProjectId).toBe(first.id)+ expect(s.projects.filter((q) => !q.closed).map((q) => q.id)).toEqual([first.id])+ })++ it('falls back to a generic name for a root-ish folder', () => {+ const p = useProjects.getState().openFolderProject('/')+ expect(p.name).toBe('Project')+ })+})diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 6e914258d..2a5a23fe3 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -12,6 +12,11 @@ interface ProjectsState {setActive(id: string): void/** Adds a new project and returns it (caller commits the current canvas first). */addProject(name?: string, cwd?: string, ssh?: Project['ssh']): Project+ /** "Open folder…": a folder maps to one project. Reuses the existing project with that+ * cwd — reopening it if it was closed, so it shows in the tab bar again — or creates a+ * new one named after the folder. Activates and returns it (caller commits the current+ * canvas first). */+ openFolderProject(folder: string): ProjectrenameProject(id: string, name: string): voidsetProjectCwd(id: string, cwd: string): void/** Sets (or clears, with undefined) the project's default Claude account for new nodes. */@@ -103,6 +108,20 @@ export const useProjects = create<ProjectsState>((set, get) => ({return project},+ openFolderProject(folder) {+ const existing = get().projects.find((p) => p.cwd === folder)+ if (existing) {+ // reopenProject also clears `closed` — an "Open folder" on a previously closed+ // project must bring its tab back, not activate an invisible project.+ get().reopenProject(existing.id)+ return existing+ }+ const name = folder.split('/').filter(Boolean).pop() || 'Project'+ const project = get().addProject(name, folder)+ set({ activeProjectId: project.id })+ return project+ },+renameProject(id, name) {set((s) => ({projects: s.projects.map((p) => (p.id === id ? { ...p, name } : p))diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex e859e89a9..2d98b1f7b 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -180,8 +180,11 @@ export const IPC = {remoteClientClosed: (connectionId: string) => `remote:client:closed:${connectionId}`,handoffBuild: 'handoff:build',// Phone pairing (nodeterm iOS "scan a QR" flow): renderer starts/stops the one-shot LAN- // listener; main pushes the completion result back over `pairing:done`.+ // listener; main pushes the completion result back over `pairing:done`. The per-device+ // registry (list/revoke) lives in ~/.nodeterm/agent.json.pairingStart: 'pairing:start',pairingStop: 'pairing:stop',- pairingDone: 'pairing:done'+ pairingDone: 'pairing:done',+ pairingListDevices: 'pairing:listDevices',+ pairingRevokeDevice: 'pairing:revokeDevice'} as constdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 82cb22d4f..6fdedca4f 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -960,6 +960,16 @@ export interface RemoteClientApi {fsWrite(connectionId: string, path: string, content: string): Promise<boolean>}+/** A paired device as exposed to the renderer — the bearer token is never included. */+export interface PairedDevice {+ id: string+ name: string+ /** epoch-ms the device was paired. */+ pairedAt: number+ /** epoch-ms the host agent last saw this device (0 = never). */+ lastSeenAt: number+}+/** Phone-pairing (nodeterm iOS "scan a QR" flow) bridge. */export interface PairingApi {/** Start the one-shot LAN listener; resolves with the QR payload + an SSH-reachable hint. */@@ -968,6 +978,10 @@ export interface PairingApi {stop(): Promise<void>/** Fires once when pairing finishes (ok=true paired, ok=false timeout). Returns unsubscribe. */onDone(cb: (result: { ok: boolean }) => void): () => void+ /** List paired devices from ~/.nodeterm/agent.json (never includes the token). */+ listDevices(): Promise<PairedDevice[]>+ /** Revoke a device: remove its registry entry and delete its authorized_keys line. */+ revokeDevice(id: string): Promise<void>}export interface NodeTerminalApi {