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(push): read SSH-possession push grants off the connected hosts

enes96e49c17a301
diff --git a/src/core/remote-push-grants.test.ts b/src/core/remote-push-grants.test.ts
new file mode 100644
index 000000000..60ba6123e
--- /dev/null
+++ b/src/core/remote-push-grants.test.ts
@@ -0,0 +1,158 @@
+import { spawnSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, describe, expect, it } from 'vitest'
+import {
+ REMOTE_GRANT_SCAN_CMD,
+ createRemoteGrantsCache,
+ parseRemoteGrants
+} from './remote-push-grants'
+
+const grantFile = (grant: string, connectionId?: string): string =>
+ JSON.stringify({ v: 1, grant, ...(connectionId ? { connectionId } : {}) })
+
+describe('parseRemoteGrants', () => {
+ it('parses `<deviceId>\\t<json>` lines', () => {
+ const out = parseRemoteGrants(
+ `dev-a\t${grantFile('tok-a', 'conn-a')}\ndev-b\t${grantFile('tok-b')}\n`
+ )
+ expect(out).toEqual([
+ { deviceId: 'dev-a', grant: 'tok-a', connectionId: 'conn-a' },
+ { deviceId: 'dev-b', grant: 'tok-b' }
+ ])
+ })
+
+ it('skips junk without throwing: no tab, bad JSON, wrong version, empty/absent grant', () => {
+ const out = parseRemoteGrants(
+ [
+ '',
+ 'no-tab-here',
+ `dev-a\t{"v":1,"grant":`, // half-written file
+ `dev-b\t${JSON.stringify({ v: 2, grant: 'tok' })}`,
+ `dev-c\t${JSON.stringify({ v: 1, grant: '' })}`,
+ `dev-d\t${JSON.stringify({ v: 1 })}`,
+ `dev-e\t"a string, not an object"`,
+ `\t${grantFile('tok-no-device')}`,
+ `${'x'.repeat(200)}\t${grantFile('tok-long-device')}`,
+ `dev-ok\t${grantFile('tok-ok')}`
+ ].join('\n')
+ )
+ expect(out).toEqual([{ deviceId: 'dev-ok', grant: 'tok-ok' }])
+ })
+})
+
+describe('createRemoteGrantsCache', () => {
+ it('is empty until a sweep lands', () => {
+ expect(createRemoteGrantsCache().get()).toEqual([])
+ })
+
+ it('keeps ONE grant per device id — two hosts holding the same phone must not double-push', () => {
+ const c = createRemoteGrantsCache()
+ c.set([
+ { deviceId: 'phone', grant: 'tok-host1' },
+ { deviceId: 'phone', grant: 'tok-host2' },
+ { deviceId: 'other', grant: 'tok-other' }
+ ])
+ expect(c.get()).toEqual([
+ { deviceId: 'phone', grant: 'tok-host1' },
+ { deviceId: 'other', grant: 'tok-other' }
+ ])
+ })
+
+ it('a 401 on the chosen token promotes the OTHER host’s grant for the same device', () => {
+ const c = createRemoteGrantsCache()
+ c.set([
+ { deviceId: 'phone', grant: 'tok-host1' },
+ { deviceId: 'phone', grant: 'tok-host2' }
+ ])
+ c.markDead('tok-host1')
+ expect(c.get()).toEqual([{ deviceId: 'phone', grant: 'tok-host2' }])
+ })
+
+ it('a dead mark survives later sweeps while the token is still there', () => {
+ const c = createRemoteGrantsCache()
+ c.set([{ deviceId: 'phone', grant: 'tok' }])
+ c.markDead('tok')
+ c.set([{ deviceId: 'phone', grant: 'tok' }])
+ expect(c.get()).toEqual([])
+ })
+
+ it('forgets the dead mark once the token is gone, so a re-minted grant is used again', () => {
+ const c = createRemoteGrantsCache()
+ c.set([{ deviceId: 'phone', grant: 'tok-old' }])
+ c.markDead('tok-old')
+ c.set([{ deviceId: 'phone', grant: 'tok-new' }])
+ expect(c.get()).toEqual([{ deviceId: 'phone', grant: 'tok-new' }])
+ // ...and re-appearance of the OLD token is a fresh start too (the mark was dropped).
+ c.set([{ deviceId: 'phone', grant: 'tok-old' }])
+ expect(c.get()).toEqual([{ deviceId: 'phone', grant: 'tok-old' }])
+ })
+})
+
+// Generated shell no compiler checks: run the real command under /bin/sh against a fake $HOME,
+// the same discipline as the canvas-control shim and the remote-usage command.
+describe('REMOTE_GRANT_SCAN_CMD, executed under /bin/sh', () => {
+ const sh = spawnSync('sh', ['-c', 'exit 0'])
+ const shAvailable = sh.status === 0 && !sh.error
+ const dir = shAvailable ? mkdtempSync(join(tmpdir(), 'nt-remote-grants-')) : ''
+ afterAll(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true })
+ })
+ const run = (home: string): { status: number | null; stdout: string } => {
+ const r = spawnSync('sh', ['-c', REMOTE_GRANT_SCAN_CMD], {
+ encoding: 'utf8',
+ env: { HOME: home, PATH: process.env.PATH ?? '' }
+ })
+ return { status: r.status, stdout: r.stdout ?? '' }
+ }
+
+ it.skipIf(!shAvailable)('exits 0 with no output when the directory does not exist', () => {
+ const home = join(dir, 'bare')
+ mkdirSync(home, { recursive: true })
+ const r = run(home)
+ expect(r.status).toBe(0)
+ expect(r.stdout).toBe('')
+ })
+
+ it.skipIf(!shAvailable)('exits 0 with no output when the directory is empty (no-glob case)', () => {
+ const home = join(dir, 'empty')
+ mkdirSync(join(home, '.nodeterm', 'push-grants'), { recursive: true })
+ const r = run(home)
+ expect(r.status).toBe(0)
+ expect(r.stdout).toBe('')
+ })
+
+ it.skipIf(!shAvailable)('emits one parseable line per grant, ignoring other files', () => {
+ const home = join(dir, 'full')
+ const gd = join(home, '.nodeterm', 'push-grants')
+ mkdirSync(gd, { recursive: true })
+ writeFileSync(join(gd, 'dev-a.grant'), grantFile('tok-a', 'conn-a'), 'utf8')
+ // Pretty-printed + trailing newline: the flatten is what keeps it one line.
+ writeFileSync(
+ join(gd, 'dev-b.grant'),
+ JSON.stringify({ v: 1, grant: 'tok-b' }, null, 2) + '\n',
+ 'utf8'
+ )
+ writeFileSync(join(gd, 'README.txt'), 'not a grant', 'utf8')
+ const r = run(home)
+ expect(r.status).toBe(0)
+ const grants = parseRemoteGrants(r.stdout)
+ expect(grants).toEqual([
+ { deviceId: 'dev-a', grant: 'tok-a', connectionId: 'conn-a' },
+ { deviceId: 'dev-b', grant: 'tok-b' }
+ ])
+ })
+
+ it.skipIf(!shAvailable)('bounds a huge file instead of streaming it back', () => {
+ const home = join(dir, 'huge')
+ const gd = join(home, '.nodeterm', 'push-grants')
+ mkdirSync(gd, { recursive: true })
+ writeFileSync(join(gd, 'dev-big.grant'), 'x'.repeat(200_000), 'utf8')
+ const r = run(home)
+ expect(r.status).toBe(0)
+ expect(r.stdout.length).toBeLessThan(4200)
+ // Truncated junk parses to nothing — tolerated, never thrown.
+ expect(parseRemoteGrants(r.stdout)).toEqual([])
+ })
+})
diff --git a/src/core/remote-push-grants.ts b/src/core/remote-push-grants.ts
new file mode 100644
index 000000000..e13081662
--- /dev/null
+++ b/src/core/remote-push-grants.ts
@@ -0,0 +1,120 @@
+// SSH-possession push grants that live on a REMOTE host (the Mac → SSH-host topology).
+//
+// `push-grants.ts` reads `~/.nodeterm/push-grants` on the machine that owns the agent-status
+// mirror. That is the whole story when the phone and the mirror owner are the same box (a headless
+// Server Edition the phone SSHes into). It is NOT the story for the common desktop setup:
+//
+// phone --SSH--> Linux dev host <--SSH-- macOS nodeterm (owns the canvas, the hooks, the mirror)
+//
+// There the phone drops its grant on the HOST — the only machine it can reach — while the process
+// that has something to push runs on the Mac and scans only its own `$HOME`. Result: an SSH-only
+// user gets no push at all, and no error anywhere (`resolveTarget` just returns null: no paired
+// phone, no grants). The remote read-acks already had their counterpart sweep
+// (`SshProjectManager.sweepRemoteAcks`); grants did not. This module is that missing half.
+//
+// It stays pure + electron-free (`src/core`): the ssh execution is injected, so the command is
+// unit-testable and the cache's dead-mark lifecycle is testable without a host. Tolerant of junk
+// at every step, exactly like `push-grants.ts` — a phone mid-write must never break a sweep.
+
+import type { PushGrant } from './push-grants'
+
+/**
+ * One host's grant listing, as ONE literal `sh` line (no interpolation — nothing from a host or a
+ * project id is ever spliced in). Prints `<deviceId>\t<json>` per grant file:
+ *
+ * - `[ -e "$f" ] || break` handles the no-glob case (the pattern stays literal when nothing
+ * matches) — same idiom as the ack sweep.
+ * - `tr -d '\r\n'` flattens the JSON to one line so the reply is line-parseable; a pretty-printed
+ * or CRLF file still parses.
+ * - `cut -c1-4096` bounds a junk/huge file. A truncation yields invalid JSON, which the parser
+ * skips — the tolerant outcome, not a crash.
+ *
+ * Read-only: unlike the ack sweep, grants are NOT consumed. A grant is re-usable until the phone
+ * re-mints it (and the backend is what actually validates it).
+ */
+export const REMOTE_GRANT_SCAN_CMD =
+ 'd="$HOME/.nodeterm/push-grants"; [ -d "$d" ] || exit 0; ' +
+ 'for f in "$d"/*.grant; do [ -e "$f" ] || break; ' +
+ 'printf \'%s\\t\' "$(basename "$f" .grant)"; ' +
+ "tr -d '\\r\\n' < \"$f\" | cut -c1-4096; printf '\\n'; done"
+
+/** Longest device id we accept from a filename (it is only ever a map key, never a path). */
+const DEVICE_ID_MAX = 128
+
+/**
+ * Parse the sweep's stdout into grants. Every malformed line is skipped silently: a partial write,
+ * a non-JSON file someone dropped in the directory, a schema-version bump, a truncated giant.
+ */
+export function parseRemoteGrants(stdout: string): PushGrant[] {
+ const out: PushGrant[] = []
+ for (const line of stdout.split('\n')) {
+ const tab = line.indexOf('\t')
+ if (tab <= 0) continue
+ const deviceId = line.slice(0, tab)
+ if (!deviceId || deviceId.length > DEVICE_ID_MAX) continue
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(line.slice(tab + 1))
+ } catch {
+ continue
+ }
+ if (!parsed || typeof parsed !== 'object') continue
+ const rec = parsed as { v?: unknown; grant?: unknown; connectionId?: unknown }
+ if (rec.v !== 1) continue
+ if (typeof rec.grant !== 'string' || rec.grant.length === 0) continue
+ out.push({
+ deviceId,
+ grant: rec.grant,
+ ...(typeof rec.connectionId === 'string' ? { connectionId: rec.connectionId } : {})
+ })
+ }
+ return out
+}
+
+export interface RemoteGrantsCache {
+ /** The live remote grants: dead-marked tokens dropped, then ONE per device id. Sync, so it can
+ * sit behind `push-notify`'s `getGrants`. */
+ get(): PushGrant[]
+ /** Replace the cache with a completed sweep's result (all hosts). */
+ set(grants: readonly PushGrant[]): void
+ /** Mark a grant dead after a 401/403 — dropped until it disappears from a later sweep (which is
+ * what a re-minted, re-dropped grant looks like: a NEW token, so the dead mark never blocks it). */
+ markDead(grant: string): void
+}
+
+/**
+ * The cache `src/main` refreshes on a timer and `push-notify` reads synchronously.
+ *
+ * Device-id dedupe happens at READ time, after the dead filter, deliberately: one phone paired to
+ * two hosts drops a different token on each, and pushing both would double every notification.
+ * Picking the survivor after the dead filter means a 401 on the first host's (stale) token
+ * promotes the other host's on the very next send — self-healing, no extra round-trip.
+ */
+export function createRemoteGrantsCache(): RemoteGrantsCache {
+ let all: PushGrant[] = []
+ const dead = new Set<string>()
+
+ return {
+ get() {
+ const seen = new Set<string>()
+ const out: PushGrant[] = []
+ for (const g of all) {
+ if (dead.has(g.grant)) continue
+ if (seen.has(g.deviceId)) continue
+ seen.add(g.deviceId)
+ out.push(g)
+ }
+ return out
+ },
+ set(grants) {
+ all = [...grants]
+ // Forget dead marks for tokens no longer on any host — the phone re-minted, or the grant was
+ // revoked. Without this the set grows for the life of the process.
+ const live = new Set(all.map((g) => g.grant))
+ for (const g of [...dead]) if (!live.has(g)) dead.delete(g)
+ },
+ markDead(grant) {
+ dead.add(grant)
+ }
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index a1e42b8bb..16719c807 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -65,7 +65,8 @@ import {
nodeSessionName
} from '../core/agent-status-mirror'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
-import { createGrantsAccessor } from '../core/push-grants'
+import { createGrantsAccessor, type PushGrant } from '../core/push-grants'
+import { createRemoteGrantsCache } from '../core/remote-push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
import { getDeviceId } from '../core/device-id'
@@ -926,6 +927,19 @@ app.whenReady().then(async () => {
// Mac-tracked sessions with NO QR pairing, and QR-pairing later flips `hasPairedPhone` true →
// host-mode automatically (grants suppressed — no double-push to the same phone).
const pushGrants = createGrantsAccessor()
+ // ...and the REMOTE half of the same idea. A Mac-driven SSH project's phone can only reach the
+ // HOST, so its grant is dropped there, not here — without this sweep an SSH-only user got no
+ // push at all (no paired phone, no local grant ⇒ `resolveTarget` silently returns null). Filled
+ // by a timer below; `get()` is sync so it can sit behind `getGrants`. See
+ // core/remote-push-grants.ts.
+ const remoteGrants = createRemoteGrantsCache()
+ /** Local grants first (this machine's own phone), then the hosts' — deduped per device inside. */
+ const allPushGrants = (): PushGrant[] => [...pushGrants.get(), ...remoteGrants.get()]
+ /** A 401/403 could be on either side's token; neither accessor knows the other's. */
+ const markPushGrantDead = (grant: string): void => {
+ pushGrants.markDead(grant)
+ remoteGrants.markDead(grant)
+ }
let pushHostKeyB64: string | null = null
let pushHasPairedPhone = false
const refreshPushIdentity = async (): Promise<void> => {
@@ -999,8 +1013,8 @@ app.whenReady().then(async () => {
: null,
// Granted-mode fallback (unpaired / no relay identity → push to SSH-dropped grants; see the
// block comment above). resolveTarget keeps a single sender: host wins when paired.
- getGrants: () => pushGrants.get(),
- markGrantDead: (grant) => pushGrants.markDead(grant),
+ getGrants: allPushGrants,
+ markGrantDead: markPushGrantDead,
hostLabel: () => hostname(),
mobilePushEnabled: () => settingsStore.get().mobilePushEnabled !== false,
mobilePushNeedsYou: () => settingsStore.get().mobilePushNeedsYou !== false,
@@ -1035,8 +1049,8 @@ app.whenReady().then(async () => {
hasPairedPhone: pushHasPairedPhone
}
: null,
- getGrants: () => pushGrants.get(),
- markGrantDead: (grant) => pushGrants.markDead(grant),
+ getGrants: allPushGrants,
+ markGrantDead: markPushGrantDead,
hostLabel: () => hostname(),
mobilePushEnabled: () => settingsStore.get().mobilePushEnabled !== false,
mobileLiveActivities: () => settingsStore.get().mobileLiveActivities !== false,
@@ -1449,6 +1463,23 @@ app.whenReady().then(async () => {
})
}, 15_000)
ackSweepTimer.unref?.()
+ // Push grants on the connected SSH hosts (core/remote-push-grants.ts). Its own, slower cadence:
+ // unlike an ack — which the phone waits on — a grant only has to be fresh by the time something
+ // is actually pushed, and the phone re-drops it long before it expires. One ssh exec per
+ // connected host per minute, and none at all with no SSH project open.
+ let remoteGrantSweepBusy = false
+ const grantSweepTimer = setInterval(() => {
+ if (remoteGrantSweepBusy || !sshProjectManager) return
+ remoteGrantSweepBusy = true
+ void sshProjectManager
+ .readRemoteGrants()
+ .then((grants) => remoteGrants.set(grants))
+ .catch(() => {})
+ .finally(() => {
+ remoteGrantSweepBusy = false
+ })
+ }, 60_000)
+ grantSweepTimer.unref?.()
// Sweep stale request/answer files (~/.nodeterm/pending) on boot + hourly — orphans from killed
// sessions that never got an answer. Local only; a remote host runs its own sweep if it hosts
// nodeterm, else the files age out harmlessly.
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 6f0ac0e15..9706308d1 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -11,6 +11,8 @@ import { findExecutableSync, shellPathNow } from '../../core/exec-path'
import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
import { allowMediaPath } from '../media-protocol'
import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../../core/claude-accounts-core'
+import type { PushGrant } from '../../core/push-grants'
+import { REMOTE_GRANT_SCAN_CMD, parseRemoteGrants } from '../../core/remote-push-grants'
import { supportsAutoPermissionMode, supportsFullscreenTui } from '../../shared/agents/config'
import {
controlPathFor,
@@ -1033,6 +1035,37 @@ export class SshProjectManager {
return out
}
+ /**
+ * Read the SSH-possession push grants the phone dropped on the connected hosts
+ * (`~/.nodeterm/push-grants/<deviceId>.grant`) — the remote counterpart of the local
+ * `push-grants` scan, and the reason an SSH-only user got no push notifications at all: in the
+ * phone→host→Mac topology the grant lands on the HOST, while the process with something to push
+ * (this one) only ever scanned its own `$HOME`. See core/remote-push-grants.ts.
+ *
+ * One command per connected HOST (deduped by host key — projects sharing a host share
+ * `$HOME/.nodeterm/push-grants`). The command is fully literal, and unlike the ack sweep it
+ * consumes nothing: a grant stays valid until the phone re-mints it. Best-effort per host; a
+ * disconnected/failed project simply contributes nothing (the cache keeps the last sweep).
+ */
+ async readRemoteGrants(): Promise<PushGrant[]> {
+ const seenHosts = new Set<string>()
+ const out: PushGrant[] = []
+ for (const c of this.conns.values()) {
+ const hk = sshHostKey(c.conn)
+ if (seenHosts.has(hk)) continue
+ seenHosts.add(hk)
+ try {
+ const { code, stdout } = await this.r.run(
+ childArgs(c.conn, c.controlPath, REMOTE_GRANT_SCAN_CMD)
+ )
+ if (code === 0 && stdout) out.push(...parseRemoteGrants(stdout))
+ } catch {
+ // best-effort per host — a failed read just keeps the previous sweep's grants
+ }
+ }
+ return out
+ }
+
/**
* Deterministic hook-reply approvals (docs/hook-reply-approvals.md): write the one-line answer
* file for a held REMOTE permission hook, on the project's host over its ControlMaster (atomic