Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(phone): retain bounded SAS consent across browse disconnects
enes002e88e1db3e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8bb7a4597..f5099434e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,4 +71,4 @@ jobs:run: npm run host:build- name: Windows-relevant tests- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/codex-cli.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsx+ run: npx vitest run src/core/phone-approval.test.ts src/main/remote/standing-host.test.ts src/main/remote/approved-devices.test.ts src/renderer/lib/phone-approval.test.ts src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/codex-cli.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsxdiff --git a/CLAUDE.md b/CLAUDE.mdindex f108819c7..e6662182d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4685,3 +4685,20 @@ sessions is a hazard whatever kills it; this removes the hazard, not a proven cafollow-up note rather than same-PR work — but flag it so it isn't forgotten.When a change is genuinely desktop-only (native menus, auto-update, Keychain), say so; thepoint is to make the call consciously, not to leave the other surfaces to rot.++### Standing phone consent lifetime (#819)++A browse socket can close before the human clicks the SAS dialog. `core/phone-approval.ts` retains+only the handshake-bound id/key for 120 seconds, at most 64 requests, one per key. Socket closure+releases presence and transport but does not discard that bounded consent; replacement, rejection,+expiry and host stop clear the exact dialog id. Approval requires BOTH id and displayed key (no+key-only match or mismatched-key fallback), consumes once, then persists before granting access.+`remote:phone:approve` is raw, owner-window Electron IPC, never a relay RPC. Its response separates+stale/persistence failure from approved/saved-disconnected; renderer rejection/timeout is explicitly+unconfirmed. SAS derivation and mutual trust verification are unchanged. Legacy interactive offers+remain session-only, and Server Edition rejects standing phone approval as unsupported.++Pin/revoke mutations use `updateApprovedDevices` to queue the entire read/modify/write in process;+unique-temp atomic rename alone cannot prevent lost updates. Non-ENOENT reads and malformed JSON+reject rather than overwrite unknown trust state. The queue is not a cross-process lock. A click+accepted before host stop may finish its disk save, but must never open the now-closed session.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0223794bd..5efc1c6a3 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -690,3 +690,10 @@ Two files, two audiences:**If you change or discover something other contributors must know, update this file too.** Aninvariant that only lives in a commit message is one refactor away from being violated by someonewho never saw it.++**Phone consent belongs to the verified handshake, not the browse socket.** A standing phone's+SAS request survives transport closure only until its 120-second deadline; approval requires the+issued id and displayed box key together. Keep request/reply outcomes distinct (stale request,+failed pin save, missing IPC response, saved-but-disconnected). All production pin/revoke writers+must use `updateApprovedDevices` for the whole read/modify/write, so concurrent updates cannot+lose approvals or resurrect revoked keys. Server Edition does not host this legacy relay path.diff --git a/src/core/phone-approval.test.ts b/src/core/phone-approval.test.tsnew file mode 100644index 000000000..c2434d64e--- /dev/null+++ b/src/core/phone-approval.test.ts@@ -0,0 +1,55 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { createPhoneApprovals, PHONE_APPROVAL_TTL_MS } from './phone-approval'++afterEach(() => vi.useRealTimers())+describe('bounded handshake consent', () => {+ function setup() {+ vi.useFakeTimers()+ const persist = vi.fn(async (_pub: string) => {})+ const cleared = vi.fn()+ return { approvals: createPhoneApprovals({ persist, cleared }), persist, cleared }+ }+ it('requires both the issued id and displayed key, and consumes consent once', async () => {+ const { approvals, persist } = setup()+ const id = approvals.add('phone')+ for (const msg of [null, {}, { id }, { pub: 'phone' }, { id, pub: 'other' }, { id: 'stale', pub: 'phone' }]) {+ expect(await approvals.approve(msg)).toEqual({ status: 'stale' })+ }+ expect(persist).not.toHaveBeenCalled()+ expect(await approvals.approve({ id, pub: 'phone' })).toEqual({ status: 'persisted' })+ expect(persist).toHaveBeenCalledExactlyOnceWith('phone')+ expect(await approvals.approve({ id, pub: 'phone' })).toEqual({ status: 'stale' })+ })+ it('expires even if the timer callback has not run, and tells the UI which id died', async () => {+ const { approvals, persist, cleared } = setup()+ const id = approvals.add('phone')+ vi.setSystemTime(Date.now() + PHONE_APPROVAL_TTL_MS)+ expect(await approvals.approve({ id, pub: 'phone' })).toEqual({ status: 'stale' })+ expect(cleared).toHaveBeenCalledWith(id)+ expect(persist).not.toHaveBeenCalled()+ })+ it('expires, replaces, rejects and stops pending dialogs without pinning', async () => {+ const { approvals, persist, cleared } = setup()+ const old = approvals.add('phone')+ const fresh = approvals.add('phone')+ expect(cleared).toHaveBeenCalledWith(old)+ expect(await approvals.approve({ id: old, pub: 'phone' })).toEqual({ status: 'stale' })+ expect(approvals.reject({ id: fresh, pub: 'other' })).toBe(false)+ expect(approvals.reject({ id: fresh, pub: 'phone' })).toBe(true)+ const expired = approvals.add('phone')+ await vi.advanceTimersByTimeAsync(PHONE_APPROVAL_TTL_MS)+ expect(cleared).toHaveBeenCalledWith(expired)+ const stopped = approvals.add('phone')+ approvals.stop()+ expect(await approvals.approve({ id: stopped, pub: 'phone' })).toEqual({ status: 'stale' })+ expect(persist).not.toHaveBeenCalled()+ })+ it('bounds pending records from many distinct devices', async () => {+ const { approvals, cleared } = setup()+ const first = approvals.add('first')+ for (let i = 0; i < 64; i++) approvals.add(String(i))+ expect(cleared).toHaveBeenCalledWith(first)+ expect(await approvals.approve({ id: first, pub: 'first' })).toEqual({ status: 'stale' })+ approvals.stop()+ })+})diff --git a/src/core/phone-approval.ts b/src/core/phone-approval.tsnew file mode 100644index 000000000..b291269d2--- /dev/null+++ b/src/core/phone-approval.ts@@ -0,0 +1,72 @@+import { randomUUID } from 'crypto'+import type { PhoneApprovalResult } from '../shared/types'++export const PHONE_APPROVAL_TTL_MS = 120_000+const MAX_PENDING = 64++/** A handshake's consent survives a browse socket closing, but never its deadline or host stop.+ * The renderer must return the issued id AND its displayed key; a key alone is not consent.+ * No caller-supplied key can enter the trust store. */+export function createPhoneApprovals(deps: {+ persist(pub: string): Promise<void>+ cleared(id: string): void+}) {+ const pending = new Map<string, {+ pub: string+ expiresAt: number+ timer: ReturnType<typeof setTimeout>+ }>()+ function clear(id: string): void {+ const p = pending.get(id)+ if (!p) return+ clearTimeout(p.timer)+ pending.delete(id)+ deps.cleared(id)+ }+ function matches(msg: { id?: string; pub?: string } | null | undefined) {+ if (!msg || typeof msg.id !== 'string' || typeof msg.pub !== 'string') return null+ const p = pending.get(msg.id)+ if (!p || p.pub !== msg.pub) return null+ if (Date.now() >= p.expiresAt) {+ clear(msg.id)+ return null+ }+ return p+ }+ return {+ add(pub: string): string {+ // Reconnects replace the displayed request, without leaving unbounded hidden consent.+ for (const [id, p] of pending) if (p.pub === pub) clear(id)+ if (pending.size >= MAX_PENDING) clear(pending.keys().next().value!)+ const id = randomUUID()+ const timer = setTimeout(() => clear(id), PHONE_APPROVAL_TTL_MS)+ timer.unref?.()+ pending.set(id, { pub, expiresAt: Date.now() + PHONE_APPROVAL_TTL_MS, timer })+ return id+ },+ async approve(msg: { id?: string; pub?: string } | null | undefined): Promise<PhoneApprovalResult> {+ const p = matches(msg)+ if (!p) return { status: 'stale' }+ // Consume exactly once before awaiting disk. A write failure grants no session access.+ clear(msg!.id!)+ try {+ await deps.persist(p.pub)+ return { status: 'persisted' }+ } catch (err) {+ // Deliberately omit paths, keys and tokens from diagnostics.+ const code = (err as NodeJS.ErrnoException)?.code+ console.error('[phone-approval] persistence-failed', /^[A-Z0-9_]+$/.test(code ?? '') ? code : 'unknown')+ return { status: 'persistence-failed' }+ }+ },+ reject(msg: { id?: string; pub?: string } | null | undefined): boolean {+ if (!matches(msg)) return false+ clear(msg!.id!)+ return true+ },+ clear,+ stop(): void {+ for (const id of pending.keys()) clear(id)+ }+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 6e451993a..5d38d073b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -292,7 +292,7 @@ import { initStandingHost } from './remote/standing-host'import { killRelayHostsByPeerKey } from './remote/relay-host'import { initRelayHost } from './remote/relay-host-service'import { createRevoker } from './remote/revocation'-import { loadApprovedDevices, saveApprovedDevices } from './remote/approved-devices'+import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './remote/approved-devices'import { publicKeyToB64 } from './remote/e2ee'import { connectRelayClient, type RelayClientSession } from './remote/relay-client'import { decodeOffer } from './remote/pairing'@@ -1674,6 +1674,7 @@ app.whenReady().then(async () => {const peerRevoker = createRevoker({load: loadApprovedDevices,save: saveApprovedDevices,+ update: updateApprovedDevices,onRevoke: (peerKeyB64) => killRelayHostsByPeerKey(peerKeyB64)})ipcMain.handle(IPC.remoteRevokePeer, (_e, peerKeyB64: string) =>diff --git a/src/main/remote/approved-devices.test.ts b/src/main/remote/approved-devices.test.tsindex bca6243d7..e1a69f42c 100644--- a/src/main/remote/approved-devices.test.ts+++ b/src/main/remote/approved-devices.test.ts@@ -15,7 +15,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { mkdtempSync, promises as fs, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import path from 'path'-import { loadApprovedDevices, saveApprovedDevices } from './approved-devices'+import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './approved-devices'+import { pinDevice, unpinDevice } from './approved-devices-core'import type { ApprovedDevices } from './approved-devices-core'// `file()` resolves <userData> through `app.getPath` on every call, so a mutable dir set in@@ -39,6 +40,34 @@ describe('approved-devices atomic write', () => {const tmpsLeft = async (): Promise<string[]> =>(await fs.readdir(userData)).filter((f) => f.endsWith('.tmp'))+ it('serializes pin/pin/revoke transactions without losing or resurrecting keys', async () => {+ await saveApprovedDevices({ pubkeys: ['revoked'] })+ await Promise.all([+ updateApprovedDevices((s) => pinDevice(s, 'phone-a')),+ updateApprovedDevices((s) => unpinDevice(s, 'revoked')),+ updateApprovedDevices((s) => pinDevice(s, 'phone-b'))+ ])+ expect(await loadApprovedDevices()).toEqual({ pubkeys: ['phone-a', 'phone-b'] })+ })++ it('does not overwrite unreadable or malformed trust data with a new pin', async () => {+ writeFileSync(target, '{broken')+ await expect(updateApprovedDevices((s) => pinDevice(s, 'phone'))).rejects.toThrow()+ expect(await fs.readFile(target, 'utf-8')).toBe('{broken')+ vi.spyOn(fs, 'readFile').mockRejectedValueOnce(Object.assign(new Error('denied'), { code: 'EACCES' }))+ await expect(updateApprovedDevices((s) => pinDevice(s, 'phone'))).rejects.toThrow('denied')+ expect(await fs.readFile(target, 'utf-8')).toBe('{broken')+ })++ it('a failed transaction leaves prior pins intact and does not poison the next save', async () => {+ await saveApprovedDevices({ pubkeys: ['existing'] })+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(Object.assign(new Error('fixture'), { code: 'EXDEV' }))+ await expect(updateApprovedDevices((s) => pinDevice(s, 'failed'))).rejects.toThrow()+ await updateApprovedDevices((s) => pinDevice(s, 'next'))+ expect(await loadApprovedDevices()).toEqual({ pubkeys: ['existing', 'next'] })+ expect(await tmpsLeft()).toEqual([])+ })+it('two overlapping saves never share a tmp file (no torn write, no leftovers)', async () => {// Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the// longer write and fails JSON.parse, instead of quietly parsing as the shorter one.diff --git a/src/main/remote/approved-devices.ts b/src/main/remote/approved-devices.tsindex fccdd9697..c3deb4fba 100644--- a/src/main/remote/approved-devices.ts+++ b/src/main/remote/approved-devices.ts@@ -18,11 +18,12 @@ function file(): string {return path.join(app.getPath('userData'), 'remote-approved-devices.json')}-/** Load the pinned-device list; returns an empty list when the file is absent or malformed. */+/** Load the pinned-device list; returns an empty list when the file is absent; other read/parse failures reject. */export async function loadApprovedDevices(): Promise<ApprovedDevices> {try {return parseApprovedDevices(JSON.parse(await fs.readFile(file(), 'utf-8')))- } catch {+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw errreturn emptyApprovedDevices()}}@@ -31,12 +32,9 @@ export async function loadApprovedDevices(): Promise<ApprovedDevices> {* Persist the pinned-device list atomically (unique temp + retrying rename, 0600) via* `writeFileAtomic`.*- * The temp name is unique per call because three writers reach this from the main process with- * nothing queueing them: the standing host's fire-and-forget pin on approval (standing-host.ts,- * `void loadApprovedDevices().then(...)`), relay-trust's un-awaited pin when a mutual approval- * settles, and the revoke IPC (src/main/index.ts → revocation.ts). With one shared `<file>.tmp`,- * a writer's rename publishes the other's half-written list — or moves the file out from under it,- * so the loser's rename fails.+ * Production mutations use updateApprovedDevices to serialize read/modify/write. Unique temps+ * still protect atomic publication, including explicit snapshot saves and separate processes.+ * This is an in-process queue, not a cross-process trust-store lock.** A failed write removes its own temp and rethrows, and the OLD file is left byte-for-byte* intact — revocation.ts's `persisted:false` contract depends on both halves.@@ -48,3 +46,14 @@ export async function loadApprovedDevices(): Promise<ApprovedDevices> {export async function saveApprovedDevices(store: ApprovedDevices): Promise<void> {await writeFileAtomic(file(), JSON.stringify(store), { mode: 0o600 })}++// Queue the WHOLE read/modify/write, not just rename: otherwise concurrent approvals lose pins,+// and an approval racing a revoke can resurrect the removed key from an obsolete snapshot.+let updateTail: Promise<void> = Promise.resolve()+export function updateApprovedDevices(update: (store: ApprovedDevices) => ApprovedDevices): Promise<void> {+ const next = updateTail.then(async () => {+ await saveApprovedDevices(update(await loadApprovedDevices()))+ })+ updateTail = next.catch(() => {}) // one failed save must not poison later attempts+ return next+}diff --git a/src/main/remote/host-service.presence.test.ts b/src/main/remote/host-service.presence.test.tsindex 9df56f07b..37b404a21 100644--- a/src/main/remote/host-service.presence.test.ts+++ b/src/main/remote/host-service.presence.test.ts@@ -192,3 +192,16 @@ describe('interactive host presence peers', () => {presenceHub.leave(id)})})+++it('a standing phone rejection cannot reject an interactive offer with the same device key', async () => {+ makeHost()+ await start()+ relays[0].opts.onReady()+ ipc[IPC.remoteHostReject](null, { id: 'another-host-request', pub: 'phone-pub' })+ expect(relays[0].closed).toBe(0)+ ipc[IPC.remoteHostReject](null, { id: pendingApprovalId(), pub: 'wrong-key' })+ expect(relays[0].closed).toBe(0)+ ipc[IPC.remoteHostReject](null, { id: pendingApprovalId(), pub: 'phone-pub' })+ expect(relays[0].closed).toBe(1)+})diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 591e38a13..5578446de 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -1279,8 +1279,8 @@ export function initRemoteHost(// so an event meant for the phone must not disturb an already-approved interactive session.ipcMain.on(IPC.remoteHostApprove, (_e, msg: { id?: string; pub?: string } = {}) => {const matched =- (pendingApprovalId && msg?.id === pendingApprovalId) ||- (pendingApprovalPub && msg?.pub === pendingApprovalPub)+ pendingApprovalId && msg?.id === pendingApprovalId &&+ (msg.pub === undefined || msg.pub === pendingApprovalPub)if (!matched) returnpendingApprovalId = nullpendingApprovalPub = null@@ -1289,8 +1289,8 @@ export function initRemoteHost(// Host human rejected the pending device → drop the connection entirely (pending sessions only).ipcMain.on(IPC.remoteHostReject, (_e, msg: { id?: string; pub?: string } = {}) => {const matched =- (pendingApprovalId && msg?.id === pendingApprovalId) ||- (pendingApprovalPub && msg?.pub === pendingApprovalPub)+ pendingApprovalId && msg?.id === pendingApprovalId &&+ (msg.pub === undefined || msg.pub === pendingApprovalPub)if (!matched) returnpendingApprovalId = nullpendingApprovalPub = nulldiff --git a/src/main/remote/relay-client.test.ts b/src/main/remote/relay-client.test.tsindex 0af438aac..575805816 100644--- a/src/main/remote/relay-client.test.ts+++ b/src/main/remote/relay-client.test.ts@@ -51,6 +51,7 @@ vi.mock('../main-window', () => ({import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'let disk: ApprovedDevices = emptyApprovedDevices()vi.mock('./approved-devices', () => ({+ updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },loadApprovedDevices: async () => disk,saveApprovedDevices: async (s: ApprovedDevices) => {disk = sdiff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.tsindex 947df8df0..f686f00a3 100644--- a/src/main/remote/relay-host-service.test.ts+++ b/src/main/remote/relay-host-service.test.ts@@ -38,6 +38,7 @@ vi.mock('../main-window', () => ({import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'let disk: ApprovedDevices = emptyApprovedDevices()vi.mock('./approved-devices', () => ({+ updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },loadApprovedDevices: async () => disk,saveApprovedDevices: async (s: ApprovedDevices) => {disk = sdiff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.tsindex 1fc0da104..6950e5525 100644--- a/src/main/remote/relay-host.test.ts+++ b/src/main/remote/relay-host.test.ts@@ -52,6 +52,7 @@ vi.mock('../main-window', () => ({import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'let disk: ApprovedDevices = emptyApprovedDevices()vi.mock('./approved-devices', () => ({+ updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },loadApprovedDevices: async () => disk,saveApprovedDevices: async (s: ApprovedDevices) => {disk = sdiff --git a/src/main/remote/relay-trust.test.ts b/src/main/remote/relay-trust.test.tsindex cea1613fd..d4c0eebb4 100644--- a/src/main/remote/relay-trust.test.ts+++ b/src/main/remote/relay-trust.test.ts@@ -20,6 +20,7 @@ import { TRUST_CONFIRM, createTrustGate, type TrustGate } from './relay-trust'// the production default path, not a test-only branch.let disk: ApprovedDevices = emptyApprovedDevices()vi.mock('./approved-devices', () => ({+ updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },loadApprovedDevices: async () => disk,saveApprovedDevices: async (s: ApprovedDevices) => {disk = sdiff --git a/src/main/remote/relay-trust.ts b/src/main/remote/relay-trust.tsindex 2c5ae6337..7ba1f371c 100644--- a/src/main/remote/relay-trust.ts+++ b/src/main/remote/relay-trust.ts@@ -33,7 +33,7 @@ import {recordApproval,type MutualApproval} from './mutual-approval-core'-import { loadApprovedDevices, saveApprovedDevices } from './approved-devices'+import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './approved-devices'import type { ApprovedDevices } from './approved-devices-core'import { parseRpcMessage } from '../../shared/rpc'@@ -101,7 +101,8 @@ export function createTrustGate(opts: TrustGateOptions): TrustGate {const load = opts.load ?? loadApprovedDevicesconst save = opts.save ?? saveApprovedDevicestry {- await save(recordApproval(await load(), pinned))+ if (opts.load || opts.save) await save(recordApproval(await load(), pinned))+ else await updateApprovedDevices((store) => recordApproval(store, pinned))} catch {// Persisting the pin is best-effort; consent for THIS session is already mutual.}diff --git a/src/main/remote/revocation.ts b/src/main/remote/revocation.tsindex 11ee085bf..cc3b2efd0 100644--- a/src/main/remote/revocation.ts+++ b/src/main/remote/revocation.ts@@ -32,6 +32,7 @@ export type OnRevoke = (peerId: string) => void | Promise<void>export interface RevocationDeps {load(): Promise<ApprovedDevices>save(store: ApprovedDevices): Promise<void>+ update?(change: (store: ApprovedDevices) => ApprovedDevices): Promise<void>onRevoke: OnRevoke}@@ -75,8 +76,8 @@ export function createRevoker(deps: RevocationDeps): {async revoke(peerKeyB64) {let persisted = falsetry {- const store = await deps.load()- await deps.save(revoke(store, peerKeyB64))+ if (deps.update) await deps.update((store) => revoke(store, peerKeyB64))+ else await deps.save(revoke(await deps.load(), peerKeyB64))persisted = true} catch {// load() or save() threw. Do NOT swallow silently: the on-disk pin may be intact, so thediff --git a/src/main/remote/standing-host.test.ts b/src/main/remote/standing-host.test.tsindex 41c1f26bf..13e3d6139 100644--- a/src/main/remote/standing-host.test.ts+++ b/src/main/remote/standing-host.test.ts@@ -10,13 +10,15 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { initPlatform, resetPlatformForTests } from '../../core/platform'import { fakePlatform } from '../../core/platform-fake'import { presenceHub } from '../../core/presence/hub'+import type { ApprovedDevices } from './approved-devices-core'import type { HostSession, HostSessionOptions } from './host-service'-const ipc: Record<string, (e: unknown, msg: unknown) => void> = {}+const ipc: Record<string, (e: unknown, msg: unknown) => any> = {}const errorBoxes: Array<{ title: string; body: string }> = []vi.mock('electron', () => ({ipcMain: {+ handle: (ch: string, fn: (e: unknown, msg: unknown) => unknown) => { ipc[ch] = fn },on: (ch: string, fn: (e: unknown, msg: unknown) => void) => {ipc[ch] = fn}@@ -35,8 +37,12 @@ vi.mock('./host-canvas-hub', () => ({currentCanvas: () => null,subscribeCanvas: () => () => {}}))+let disk: ApprovedDevices = { pubkeys: [] }+const persist = vi.fn(async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) })+vi.mock('./relay-advertise', () => ({ writeRelayAdvertisement: async () => {}, removeRelayAdvertisement: async () => {} }))vi.mock('./approved-devices', () => ({- loadApprovedDevices: async () => ({ pubkeys: [] as string[] }),+ updateApprovedDevices: (update: (s: ApprovedDevices) => ApprovedDevices) => persist(update),+ loadApprovedDevices: async () => disk,saveApprovedDevices: async () => {}}))vi.mock('./e2ee', () => ({ publicKeyToB64: () => 'host-pub' }))@@ -58,7 +64,7 @@ vi.mock('./host-service', () => ({connectHostSession: (opts: HostSessionOptions): HostSession => {const entry = { opts, closed: 0, session: null as unknown as HostSession }entry.session = {- approve: () => {},+ approve: vi.fn(),isApproved: () => false,sas: () => '12345',// A real relay socket close() is "intentional" and does NOT fire onClose — modelled here.@@ -86,6 +92,7 @@ function phones(): number {const sentToWin: Array<{ channel: string; args: unknown[] }> = []+let sender: unknownfunction makeHost() {const win = {isDestroyed: () => false,@@ -93,6 +100,7 @@ function makeHost() {send: (channel: string, ...args: unknown[]) => sentToWin.push({ channel, args })}}+ sender = win.webContentsreturn initStandingHost(win as never, {} as never, () => ({ phoneAccessEnabled: true }) as never)}@@ -107,6 +115,9 @@ beforeEach(() => {sessions.length = 0sentToWin.length = 0errorBoxes.length = 0+ persist.mockReset()+ disk = { pubkeys: [] }+ persist.mockImplementation(async (update) => { disk = update(disk) })keyError = nullfor (const key of Object.keys(ipc)) delete ipc[key]vi.stubGlobal(@@ -157,7 +168,7 @@ describe('standing host presence peers', () => {// Reject → removeFromPool → session.close(). A real relay socket treats an intentional close// as final and does NOT call onClose, so the leave has to happen on this path too.- ipc[IPC.remoteHostReject](null, { id: pendingApprovalId() })+ ipc[IPC.remoteHostReject]({ sender }, { id: pendingApprovalId(), pub: 'phone-pub' })expect(sessions[0].closed).toBe(1)expect(phones()).toBe(0)@@ -218,3 +229,66 @@ describe('standing host: the host key cannot be read (locked keyring)', () => {host.stop()})})+++describe('standing phone approval lifecycle (#819)', () => {+ async function pending() {+ const host = makeHost()+ host.setEnabled(true)+ await settle()+ sessions[0].opts.onPeerReady(sessions[0].session)+ await settle()+ return { host, msg: { id: pendingApprovalId(), pub: 'phone-pub' } }+ }+ it('pins the displayed handshake after its browse socket closes, without approving a dead session', async () => {+ const { host, msg } = await pending()+ sessions[0].opts.onClose()+ expect(await ipc[IPC.remotePhoneApprove]({ sender }, msg)).toEqual({ status: 'saved-disconnected' })+ expect(persist).toHaveBeenCalledOnce()+ expect(sessions[0].session.approve).not.toHaveBeenCalled()+ expect(disk.pubkeys).toEqual(['phone-pub'])+ const count = sentToWin.filter((s) => s.channel === IPC.remoteHostPeerPending).length+ sessions[1].opts.onPeerReady(sessions[1].session)+ await settle()+ expect(sessions[1].session.approve).toHaveBeenCalledOnce()+ expect(sentToWin.filter((s) => s.channel === IPC.remoteHostPeerPending)).toHaveLength(count)+ host.stop()+ })+ it('waits for persistence before granting access', async () => {+ const { host, msg } = await pending()+ let release!: () => void+ persist.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve }))+ const approval = ipc[IPC.remotePhoneApprove]({ sender }, msg)+ expect(sessions[0].session.approve).not.toHaveBeenCalled()+ release()+ expect(await approval).toEqual({ status: 'approved' })+ expect(sessions[0].session.approve).toHaveBeenCalledOnce()+ host.stop()+ })+ it('reports a failed write and grants no access', async () => {+ const { host, msg } = await pending()+ persist.mockRejectedValueOnce(Object.assign(new Error('fixture'), { code: 'EACCES' }))+ expect(await ipc[IPC.remotePhoneApprove]({ sender }, msg)).toEqual({ status: 'persistence-failed' })+ expect(sessions[0].session.approve).not.toHaveBeenCalled()+ host.stop()+ })+ it('rejects stale, mismatched and non-owner requests without writing', async () => {+ const { host, msg } = await pending()+ for (const [owner, request] of [[{}, msg], [sender, { ...msg, pub: 'other' }], [sender, { ...msg, id: 'stale' }]]) {+ expect(await ipc[IPC.remotePhoneApprove]({ sender: owner }, request)).toEqual({ status: 'stale' })+ }+ expect(persist).not.toHaveBeenCalled()+ host.stop()+ expect(await ipc[IPC.remotePhoneApprove]({ sender }, msg)).toEqual({ status: 'stale' })+ })+ it('host stop during a save never grants a closed session access', async () => {+ const { host, msg } = await pending()+ let release!: () => void+ persist.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve }))+ const approval = ipc[IPC.remotePhoneApprove]({ sender }, msg)+ host.stop()+ release()+ expect(await approval).toEqual({ status: 'saved-disconnected' })+ expect(sessions[0].session.approve).not.toHaveBeenCalled()+ })+})diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsindex af1e3376e..dbc94f60f 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -17,7 +17,6 @@// shared with the interactive host via `connectHostSession`. Pin/lookup logic is the pure,// unit-tested `approved-devices-core`.-import { randomUUID } from 'crypto'import { dialog, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import type { CanvasMutation, Settings } from '../../shared/types'@@ -39,7 +38,8 @@ import { currentCanvas, initHostCanvasHub, subscribeCanvas } from './host-canvasimport { hostIdFromPublicKeyB64 } from './relay-id'import { removeRelayAdvertisement, writeRelayAdvertisement } from './relay-advertise'import { isPinned, pinDevice } from './approved-devices-core'-import { loadApprovedDevices, saveApprovedDevices } from './approved-devices'+import { loadApprovedDevices, updateApprovedDevices } from './approved-devices'+import { createPhoneApprovals } from '../../core/phone-approval'// Re-mint the token this long before its expiry (TTL is ~120s). Floored so a bogus/short exp can't// spin us.@@ -150,7 +150,6 @@ export function initStandingHost(/** Per-session pending approval (unknown device awaiting the human's SAS decision). */approvalPub: string | nullapprovalId: string | null- approvalTimer: ReturnType<typeof setTimeout> | nullrefreshTimer: ReturnType<typeof setTimeout> | null}@@ -177,17 +176,13 @@ export function initStandingHost(// deliberately does NOT fire onClose. `PhonePresence.leave()` (shared with the interactive host)// is exactly-once, so a peer never leaves twice (its color is never freed for someone else).- function clearApproval(p: Pooled): void {- if (p.approvalTimer) {- clearTimeout(p.approvalTimer)- p.approvalTimer = null- }- p.approvalPub = null- p.approvalId = null- }+ const approvals = createPhoneApprovals({+ persist: (pub) => updateApprovedDevices((store) => pinDevice(store, pub)),+ cleared: (id) => send(IPC.remoteHostPeerPendingCleared, { id })+ })function removeFromPool(p: Pooled): void {- clearApproval(p)+ if (p.approvalId) approvals.clear(p.approvalId)p.presence.leave()if (p.refreshTimer) {clearTimeout(p.refreshTimer)@@ -197,15 +192,6 @@ export function initStandingHost(p.session.close()}- // The peer's box key is STABLE across the phone's reconnect churn while the per-attach id- // dies with each socket, so an Approve clicked mid-retry still lands when matched by pub- // (issue #372's race note). The id stays as the exact-match fallback.- function findPending(msg: { id?: string; pub?: string }): Pooled | null {- if (msg.pub) for (const p of pool) if (p.approvalPub && p.approvalPub === msg.pub) return p- if (msg.id) for (const p of pool) if (p.approvalId && p.approvalId === msg.id) return p- return null- }-/** Keep the pool topped up with TARGET_PENDING un-bridged listeners. */function ensurePool(): void {if (running && pendingCount() < TARGET_PENDING) void connectOne()@@ -265,26 +251,14 @@ export function initStandingHost(s.approve() // pinned device → auto-approve silentlyreturn}- // Unknown device → require the host human's approval (shared SAS dialog). Remember the pubkey +- // a fresh id on THIS pooled session, so approval pins it even if the phone's browse socket- // closes first, and only the matching approve id acts on it.+ // Keep the handshake-bound consent record after a browse socket closes (#819). The+ // human may still compare its SAS and pin this exact identity until the bounded deadline.+ if (!pub || !s.sas()) return // never offer consent without a verified handshake identitypooled.approvalPub = pub- pooled.approvalId = randomUUID()- if (pooled.approvalTimer) clearTimeout(pooled.approvalTimer)- pooled.approvalTimer = setTimeout(() => {- const expiredId = pooled.approvalId- pooled.approvalPub = null- pooled.approvalId = null- pooled.approvalTimer = null- // Tell the renderer the prompt died — without this the dialog outlives the id and- // Approve becomes a silent no-op (issue #372).- send(IPC.remoteHostPeerPendingCleared, { id: expiredId, pub })- }, 120_000)- pooled.approvalTimer.unref?.()- // `pub` rides along so the renderer can key the dialog on the STABLE device identity: a- // retry-churning phone re-raises this event with a fresh id but the same pub + SAS, and- // the open dialog just updates in place instead of flashing.- send(IPC.remoteHostPeerPending, { sas: s.sas(), id: pooled.approvalId, pub })+ pooled.approvalId = approvals.add(pub)+ send(IPC.remoteHostPeerPending, {+ sas: s.sas(), id: pooled.approvalId, pub, standing: true+ })}async function connectOne(): Promise<void> {@@ -321,7 +295,6 @@ export function initStandingHost(presence: createPhonePresence(),approvalPub: null,approvalId: null,- approvalTimer: null,refreshTimer: null}pooled.session = connectHostSession({@@ -344,7 +317,7 @@ export function initStandingHost(getClientId: () => pooled.presence.id(),onPeerReady: () => void onPeerReady(pooled),onClose: () => {- clearApproval(pooled)+ console.info('[phone-approval] socket-closed', { pending: !!pooled.approvalId })pooled.presence.leave()if (pooled.refreshTimer) {clearTimeout(pooled.refreshTimer)@@ -384,6 +357,7 @@ export function initStandingHost(function stop(): void {running = false+ approvals.stop()if (reconnectTimer) {clearTimeout(reconnectTimer)reconnectTimer = null@@ -400,28 +374,31 @@ export function initStandingHost(else if (!want && running) stop()}- // Host human approved / rejected a pending phone (by its pending id). Shared with the interactive- // host; the id scoping means each acts only on its own pending session.- ipcMain.on(IPC.remoteHostApprove, (_e, msg: { id?: string; pub?: string } = {}) => {- const p = findPending(msg ?? {})- if (!p) return- // Pin the DEVICE (its stable box key), whether or not its session is still live — the phone's- // browse socket may have already closed. Prefer the live peer's key, else the remembered one.- const pub = p.session.peerPublicKeyB64() ?? p.approvalPub- clearApproval(p)- if (pub) {- void loadApprovedDevices()- .then((store) => saveApprovedDevices(pinDevice(store, pub)))- .catch(() => {- // A failed pin is non-fatal: the device re-prompts next connect. Never block on the write.- })+ // Dedicated request/reply channel: a missing IPC handler rejects instead of silently+ // discarding consent. Never expose this host-security operation through the relay RPC bridge.+ ipcMain.handle(IPC.remotePhoneApprove, async (event, msg: { id?: string; pub?: string }) => {+ if (event.sender !== win.webContents) return { status: 'stale' as const }+ console.info('[phone-approval] received')+ const result = await approvals.approve(msg)+ console.info('[phone-approval] result', result.status)+ if (result.status !== 'persisted') return result+ let connected = false+ for (const p of pool) {+ if (p.bridged && p.session.peerPublicKeyB64() === msg.pub) {+ if (p.approvalId) approvals.clear(p.approvalId)+ p.approvalId = null+ p.approvalPub = null+ p.session.approve()+ connected = true+ }}- p.session.approve()+ return { status: connected ? 'approved' as const : 'saved-disconnected' as const }})- ipcMain.on(IPC.remoteHostReject, (_e, msg: { id?: string; pub?: string } = {}) => {- const p = findPending(msg ?? {})- if (!p) return- removeFromPool(p) // drop this rejected session+ ipcMain.on(IPC.remoteHostReject, (event, msg: { id?: string; pub?: string } = {}) => {+ if (event.sender !== win.webContents || !approvals.reject(msg)) return+ for (const p of [...pool]) {+ if (p.approvalPub === msg.pub) removeFromPool(p)+ }ensurePool()})diff --git a/src/preload/index.ts b/src/preload/index.tsindex ce50c6fd6..944143250 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -48,7 +48,7 @@ function subscribe<A extends unknown[] = []>(channel: string) {const subscribeMutation = subscribe<[CanvasMutation]>(IPC.remoteHostApplyMutation)// Fan-out subscriber for the connection-approval prompt (main → host renderer when a client// finishes the handshake; carries the SAS to show in the approval dialog).-const subscribePeerPending = subscribe<[{ sas: string | null; id: string; pub?: string | null }]>(+const subscribePeerPending = subscribe<[{ sas: string | null; id: string; pub?: string | null; standing?: boolean }]>(IPC.remoteHostPeerPending)const subscribePeerPendingCleared = subscribe<[{ id: string | null; pub?: string | null }]>(@@ -600,6 +600,7 @@ const api: NodeTerminalApi = {onApplyMutation: subscribeMutation,onPeerPending: subscribePeerPending,onPeerPendingCleared: subscribePeerPendingCleared,+ approvePhone: (id, pub) => ipcRenderer.invoke(IPC.remotePhoneApprove, { id, pub }),approve: (id: string, pub?: string) => ipcRenderer.send(IPC.remoteHostApprove, { id, pub }),reject: (id: string, pub?: string) => ipcRenderer.send(IPC.remoteHostReject, { id, pub }),setPhoneAccess: (enabled) => ipcRenderer.send(IPC.remoteStandingHostSet, enabled)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex cc48eb0aa..90209fe1e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -404,6 +404,8 @@ export function buildStubApi(): Omit<onApplyMutation: noopUnsub,onPeerPending: noopUnsub,onPeerPendingCleared: noopUnsub,+ // Standing phone hosting is Desktop-only; never pretend that a browser pinned a phone.+ approvePhone: U('remoteHost.approvePhone'),approve: (_id: string) => {},reject: (_id: string) => {},setPhoneAccess: noopdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9cbed6b7a..a5bdebd5d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -201,6 +201,7 @@ import { CapabilityNotice } from '../components/CapabilityNotice'import { ClosedTranscriptDialog } from '../components/ClosedTranscriptDialog'import { SetupConsentDialog } from '../components/SetupConsentDialog'import { ConsentNotice } from '../remote/ConsentNotice'+import { approvePhoneWithFeedback } from '../lib/phone-approval'import { peerApprovalView } from '@shared/remote/approval'import { promptDialog } from '../components/promptDialog'import { UpgradeDialog } from '../components/UpgradeDialog'@@ -752,6 +753,7 @@ interface MergeState {hasOrigin: boolean}interface PendingPeerState {+ standing?: booleansas: string | nullid: string/** Human-facing peer name, if the tunnel carries one. The relay `RelayPeerPending` payload does@@ -3087,11 +3089,8 @@ export function Canvas() {// Host connection-approval gate: when a client finishes the handshake, prompt the host to// verify the SAS and allow/deny before any remote pty/fs RPC is served.//- // Sourced off the NEW relay tunnel (`relayHost`, Stage 4 Task 2), NOT the legacy- // `remoteHost.onPeerPending`. Migrating means the old standing-host (phone) path no longer raises- // THIS dialog — deliberate: the phone is being moved to the relay tunnel separately- // (docs/ios-protocol-migration.md) and Task 10 deletes the `remoteHost` dialect outright. So we- // fully migrate rather than keep both sources alive (which would only complicate that removal).+ // Team relay and legacy phone handshakes share the SAS dialog until the mobile protocol+ // migration is complete. Standing phone consent has a request/reply persistence outcome.useEffect(() => {return window.nodeTerminal.relayHost.onPeerPending((info) =>setPendingPeer({ ...info, source: 'relay' })@@ -14965,7 +14964,12 @@ export function Canvas() {enterConfirms={false}dangeronConfirm={() => {- if (pendingPeer.source === 'phone') {+ if (pendingPeer.source === 'phone' && pendingPeer.standing) {+ void approvePhoneWithFeedback(+ () => window.nodeTerminal.remoteHost.approvePhone(pendingPeer.id, pendingPeer.pub ?? ''),+ setCopyError+ )+ } else if (pendingPeer.source === 'phone') {window.nodeTerminal.remoteHost.approve(pendingPeer.id, pendingPeer.pub ?? undefined)} else {window.nodeTerminal.relayHost.confirm(peerApprovalView(pendingPeer).confirmId)diff --git a/src/renderer/lib/phone-approval.test.ts b/src/renderer/lib/phone-approval.test.tsnew file mode 100644index 000000000..04770a478--- /dev/null+++ b/src/renderer/lib/phone-approval.test.ts@@ -0,0 +1,25 @@+import { afterEach, expect, it, vi } from 'vitest'+import { approvePhoneWithFeedback } from './phone-approval'+afterEach(() => vi.useRealTimers())+it('distinguishes stale, failed persistence and a saved but disconnected phone', async () => {+ const report = vi.fn()+ await approvePhoneWithFeedback(async () => ({ status: 'stale' }), report)+ expect(report).toHaveBeenLastCalledWith(expect.stringContaining('expired or was replaced'))+ await approvePhoneWithFeedback(async () => ({ status: 'persistence-failed' }), report)+ expect(report).toHaveBeenLastCalledWith(expect.stringContaining('could not be saved'))+ await approvePhoneWithFeedback(async () => ({ status: 'saved-disconnected' }), report)+ expect(report).toHaveBeenLastCalledWith(expect.stringContaining('approval saved'))+ await approvePhoneWithFeedback(async () => ({ status: 'approved' }), report)+ expect(report).toHaveBeenCalledTimes(3)+})+it('reports missing IPC and bounded missing responses as unconfirmed, never success', async () => {+ vi.useFakeTimers()+ const report = vi.fn()+ await approvePhoneWithFeedback(async () => { throw new Error('No handler registered') }, report)+ expect(report).toHaveBeenLastCalledWith(expect.stringContaining('unconfirmed'))+ const waiting = approvePhoneWithFeedback(() => new Promise(() => {}), report)+ await vi.advanceTimersByTimeAsync(15_000)+ await waiting+ expect(report).toHaveBeenCalledTimes(2)+ expect(report).toHaveBeenLastCalledWith(expect.stringContaining('unconfirmed'))+})diff --git a/src/renderer/lib/phone-approval.ts b/src/renderer/lib/phone-approval.tsnew file mode 100644index 000000000..78b6b20a9--- /dev/null+++ b/src/renderer/lib/phone-approval.ts@@ -0,0 +1,28 @@+import type { PhoneApprovalResult } from '@shared/types'++/** A cast cannot tell a stale request from missing IPC or failed persistence (#819). */+export async function approvePhoneWithFeedback(+ approve: () => Promise<PhoneApprovalResult>,+ report: (message: string) => void+): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ const result = await Promise.race([+ approve(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('approval response timeout')), 15_000)+ })+ ])+ if (result.status === 'stale') {+ report('This phone approval expired or was replaced. Reconnect the phone and compare the new code.')+ } else if (result.status === 'persistence-failed') {+ report('The phone approval could not be saved. Access was not granted. Reconnect the phone to try again.')+ } else if (result.status === 'saved-disconnected') {+ report('Phone approval saved. The phone disconnected; retry browsing projects on the phone.')+ }+ } catch {+ report('No phone approval response was received. Approval is unconfirmed; reconnect the phone to check.')+ } finally {+ clearTimeout(timer)+ }+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 5854e1dec..652426006 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -530,6 +530,7 @@ export const IPC = {remoteHostPeerPending: 'remote:host:peer-pending',remoteHostPeerPendingCleared: 'remote:host:peer-pending-cleared',remoteHostApprove: 'remote:host:approve',+ remotePhoneApprove: 'remote:phone:approve',remoteHostReject: 'remote:host:reject',// Host canvas mirror: renderer pushes its serialized active-project canvas to main;// main pushes a client's mutation back to the host renderer to apply.diff --git a/src/shared/types.ts b/src/shared/types.tsindex d05cad046..272e6b7ee 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3133,6 +3133,10 @@ export interface LicenseApi {releaseOthers(): Promise<LicenseDetail>}+export type PhoneApprovalResult = {+ status: 'persisted' | 'approved' | 'saved-disconnected' | 'stale' | 'persistence-failed'+}+export interface RemoteHostApi {/*** Enter host mode: mint a pairing token, connect to the relay as the host, and return the@@ -3158,16 +3162,17 @@ export interface RemoteHostApi {* verification code to display. Returns an unsubscribe function.*/onPeerPending(- listener: (info: { sas: string | null; id: string; pub?: string | null }) => void+ listener: (info: { sas: string | null; id: string; pub?: string | null; standing?: boolean }) => void): () => void/** The pending prompt expired host-side (120 s) — the dialog must drop or re-arm, else its* Approve is a silent no-op against a dead id (issue #372). */onPeerPendingCleared(listener: (info: { id: string | null; pub?: string | null }) => void): () => void- /** Approve the pending client → the host begins serving its pty/fs RPCs. `pub` (the peer's- * stable box key) survives the phone's reconnect churn where the per-attach `id` does not —- * pass both when known. */+ /** Standing phone consent: persist the displayed handshake identity before granting access.+ * Both fields must match a bounded pending request. Desktop-only; Server rejects explicitly. */+ approvePhone(id: string, pub: string): Promise<PhoneApprovalResult>+ /** Legacy interactive (single-use offer) approval; does not persist a device pin. */approve(id: string, pub?: string): void/** Reject the pending client → the connection is dropped. Same id/pub matching as approve. */reject(id: string, pub?: string): void