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.

fix(push): a paired phone no longer silences every SSH-only one, and ts says ms

enes5b2641a4b9db
diff --git a/src/core/push-notify.test.ts b/src/core/push-notify.test.ts
index 9e40201e1..9886c9b0d 100644
--- a/src/core/push-notify.test.ts
+++ b/src/core/push-notify.test.ts
@@ -548,27 +548,116 @@ describe('createPushNotify', () => {
h.stop()
})
- it('a paired host identity WINS: grants are never consulted (no double-push)', async () => {
- const getGrants = vi.fn(() => GRANTS)
+ })
+
+ // The regression this matrix exists for: targeting used to be either/or — one relay-paired phone
+ // made `resolveTarget` return host mode and never look at the grants, and since host mode fans out
+ // over the backend's `relay_devices` rows (where an SSH-only phone has no row), that ONE pairing
+ // silenced every SSH-only phone on the machine. Both legs now send. See resolveSendTarget for why
+ // the per-device exclusion is not expressible on the desktop.
+ describe('send-target matrix (host + grants)', () => {
+ const GRANTS = [
+ { deviceId: 'dev-A', grant: 'tok-A' },
+ { deviceId: 'dev-B', grant: 'tok-B' }
+ ]
+
+ it('paired ONLY (no grants) → host mode alone, byte-identical to the legacy body', async () => {
const em = makeEmitter()
- // getHostIdentity defaults to the paired IDENTITY via baseDeps.
- const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getGrants, hostLabel: () => 'niova' }))
+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getGrants: () => [] }))
em.emit(iev({ nodeId: 'a', title: 'A' }))
await vi.advanceTimersByTimeAsync(2000)
expect(fetchMock).toHaveBeenCalledTimes(1)
- const body = bodyOf()
- expect(body.hostDeviceId).toBe('host-device-1')
+ expect(bodyOf().hostDeviceId).toBe('host-device-1')
expect(fetchMock.mock.calls[0][1].headers.authorization).toBeUndefined()
- expect(getGrants).not.toHaveBeenCalled()
h.stop()
})
- })
- describe('single-sender matrix (granted vs host)', () => {
- // paired → host only, and neither → inert, are covered in the granted-mode block above. This
- // pins the third leg: an UNPAIRED host identity (identity present, no phone pinned) must fall
- // THROUGH to granted mode — the desktop granted-mode fallback (spec: 2026-07-21-push-grants).
- it('unpaired host identity + grants → GRANTED mode only (host fields absent)', async () => {
+ it('granted ONLY (no paired phone) → one Bearer POST per grant, no host fields', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(
+ baseDeps({
+ subscribe: em.subscribe,
+ getHostIdentity: () => null,
+ getGrants: () => GRANTS,
+ hostLabel: () => 'niova'
+ })
+ )
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(fetchMock.mock.calls.map((c) => c[1].headers.authorization)).toEqual([
+ 'Bearer tok-A',
+ 'Bearer tok-B'
+ ])
+ for (const c of fetchMock.mock.calls) expect(JSON.parse(c[1].body)).not.toHaveProperty('hostDeviceId')
+ h.stop()
+ })
+
+ it('BOTH: a relay-paired phone must NOT silence the granted (SSH-only) ones', async () => {
+ const em = makeEmitter()
+ // getHostIdentity defaults to the PAIRED identity via baseDeps.
+ const h = createPushNotify(
+ baseDeps({ subscribe: em.subscribe, getGrants: () => GRANTS, hostLabel: () => 'niova' })
+ )
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ // Host leg first, then one per grant — three POSTs, all carrying the same event.
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ const [host, ...granted] = fetchMock.mock.calls
+ expect(JSON.parse(host[1].body).hostDeviceId).toBe('host-device-1')
+ expect(host[1].headers.authorization).toBeUndefined()
+ expect(granted.map((c) => c[1].headers.authorization)).toEqual(['Bearer tok-A', 'Bearer tok-B'])
+ for (const c of granted) {
+ const body = JSON.parse(c[1].body)
+ expect(body).not.toHaveProperty('hostDeviceId')
+ expect(body).not.toHaveProperty('hostPublicKeyB64')
+ expect(body.hostLabel).toBe('niova')
+ expect(body.events[0].title).toBe('A')
+ }
+ h.stop()
+ })
+
+ // The one overlap the desktop CAN see: the same phone dropped a grant on this Mac AND on an SSH
+ // host it reaches (src/main's allPushGrants concatenates both lists), so the same deviceId shows
+ // up twice with different tokens. First occurrence wins — main puts the local grants first.
+ it('OVERLAP: two grants for the same deviceId collapse to ONE POST (first wins)', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(
+ baseDeps({
+ subscribe: em.subscribe,
+ getHostIdentity: () => null,
+ getGrants: () => [
+ { deviceId: 'dev-A', grant: 'tok-local' },
+ { deviceId: 'dev-A', grant: 'tok-remote' },
+ { deviceId: 'dev-B', grant: 'tok-B' }
+ ],
+ hostLabel: () => 'niova'
+ })
+ )
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(fetchMock.mock.calls.map((c) => c[1].headers.authorization)).toEqual([
+ 'Bearer tok-local',
+ 'Bearer tok-B'
+ ])
+ h.stop()
+ })
+
+ it('NEITHER (no paired phone, no grants) → inert', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(
+ baseDeps({ subscribe: em.subscribe, getHostIdentity: () => null, getGrants: () => [] })
+ )
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).not.toHaveBeenCalled()
+ h.stop()
+ })
+
+ // Third leg: an UNPAIRED host identity (identity present, no phone pinned) must fall THROUGH to
+ // granted mode — the desktop granted-mode fallback (spec: 2026-07-21-push-grants).
+ it('unpaired host identity + grants → GRANTED only (host fields absent)', async () => {
const em = makeEmitter()
const getGrants = vi.fn(() => [{ deviceId: 'd', grant: 'tok-X' }])
const h = createPushNotify(
@@ -1338,15 +1427,39 @@ describe('createLiveUpdatePush', () => {
h.stop()
})
- it('a paired host identity WINS: grants are never consulted (no double-push)', async () => {
- const getGrants = vi.fn(() => GRANTS)
- const { h, st } = wire({ getGrants, hostLabel: () => 'niova' })
+ // Same rule as createPushNotify's send-target matrix (both senders call resolveSendTarget, so
+ // they cannot drift): a relay-paired phone must not silence the SSH-only ones. The live-update
+ // stream is where it bites hardest — a granted phone would show an island that never moves.
+ it('BOTH: a relay-paired phone must NOT silence the granted (SSH-only) ones', async () => {
+ const { h, st } = wire({ getGrants: () => GRANTS, hostLabel: () => 'niova' })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ const [host, ...granted] = fetchMock.mock.calls
+ expect(JSON.parse(host[1].body).hostDeviceId).toBe('host-device-1')
+ expect(host[1].headers.authorization).toBeUndefined()
+ expect(granted.map((c) => c[1].headers.authorization)).toEqual(['Bearer tok-A', 'Bearer tok-B'])
+ for (const c of granted) {
+ const body = JSON.parse(c[1].body)
+ expect(body).not.toHaveProperty('hostDeviceId')
+ expect(body.updates[0]).toMatchObject({ nodeId: 'a', event: 'start', state: 'working' })
+ }
+ h.stop()
+ })
+
+ it('OVERLAP: two grants for the same deviceId collapse to ONE POST (first wins)', async () => {
+ const { h, st } = wire({
+ getHostIdentity: () => null,
+ getGrants: () => [
+ { deviceId: 'dev-A', grant: 'tok-local' },
+ { deviceId: 'dev-A', grant: 'tok-remote' }
+ ],
+ hostLabel: () => 'niova'
+ })
st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
await vi.advanceTimersByTimeAsync(1000)
expect(fetchMock).toHaveBeenCalledTimes(1)
- expect(liveBodyOf().hostDeviceId).toBe('host-device-1')
- expect(fetchMock.mock.calls[0][1].headers.authorization).toBeUndefined()
- expect(getGrants).not.toHaveBeenCalled()
+ expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer tok-local')
h.stop()
})
@@ -1400,3 +1513,103 @@ describe('live-update: the You: prompt line', () => {
h.stop()
})
})
+
+// ---- ts unit -------------------------------------------------------------------------------
+//
+// Every `ts` this file emits is Unix MILLISECONDS, forwarded verbatim from the agent-status mirror
+// (Date.now()). The trap this pins: the iOS Live Activity's ContentState.ts has TWO producers —
+// these pushes and the phone's own foreground poll — and a producer that writes seconds disagrees
+// with the other by a factor of 1000, so every "is this newer than what I'm showing?" comparison
+// silently inverts. The assertions below are exact, so any scaling (× or ÷ 1000) fails them.
+describe('push payload ts is Unix MILLISECONDS (the mirror is the source)', () => {
+ // A real ms epoch: 2025-10-09T07:33:20Z. Its seconds form (1_760_000_000) is 1000× smaller, which
+ // is what the toBe below rejects.
+ const TS_MS = 1_760_000_000_000
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ fetchMock = vi.fn().mockResolvedValue({ ok: true })
+ clock = 0
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('ALERT path (/v1/push/notify) forwards the mirror InboxEvent.ts unscaled', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
+ em.emit(iev({ nodeId: 'a', title: 'A', ts: TS_MS }))
+ await vi.advanceTimersByTimeAsync(2000)
+ const sent = JSON.parse(fetchMock.mock.calls[0][1].body).events[0]
+ expect(sent.ts).toBe(TS_MS)
+ expect(sent.ts).toBeGreaterThan(1e12) // ms scale, not seconds
+ h.stop()
+ })
+
+ it('LIVE-UPDATE state edge forwards the mirror NodeStateChange.ts unscaled', async () => {
+ const st = emitter<NodeStateChange>()
+ const h = createLiveUpdatePush({
+ subscribeStateChange: st.subscribe,
+ subscribeNowChange: () => () => {},
+ getHostIdentity: () => IDENTITY,
+ mobilePushEnabled: () => true,
+ mobileLiveActivities: () => true,
+ isPackaged: () => true,
+ env: {},
+ fetchImpl: fetchMock as unknown as typeof fetch,
+ now: () => clock,
+ batchWindowMs: 1000
+ })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: TS_MS })
+ await vi.advanceTimersByTimeAsync(1000)
+ const sent = JSON.parse(fetchMock.mock.calls[0][1].body).updates[0]
+ expect(sent.ts).toBe(TS_MS)
+ expect(sent.ts).toBeGreaterThan(1e12)
+ h.stop()
+ })
+
+ it('LIVE-UPDATE now-tick forwards the mirror NodeNowChange.ts unscaled', async () => {
+ const nw = emitter<NodeNowChange>()
+ const h = createLiveUpdatePush({
+ subscribeStateChange: () => () => {},
+ subscribeNowChange: nw.subscribe,
+ getHostIdentity: () => IDENTITY,
+ mobilePushEnabled: () => true,
+ mobileLiveActivities: () => true,
+ isPackaged: () => true,
+ env: {},
+ fetchImpl: fetchMock as unknown as typeof fetch,
+ now: () => clock,
+ batchWindowMs: 1000,
+ coalesceMs: 20000
+ })
+ nw.emit({ nodeId: 'a', activity: 'Editing a.ts', ts: TS_MS })
+ await vi.advanceTimersByTimeAsync(1000)
+ const sent = JSON.parse(fetchMock.mock.calls[0][1].body).updates[0]
+ expect(sent.ts).toBe(TS_MS)
+ expect(sent.ts).toBeGreaterThan(1e12)
+ h.stop()
+ })
+
+ it('the mirror really does stamp ms (both seams, end to end)', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'push-ts-'))
+ try {
+ _resetForTest()
+ initAgentStatusMirror(path.join(dir, 'agent-status.json'))
+ const inbox: InboxEvent[] = []
+ const edges: NodeStateChange[] = []
+ onInboxActionable((e) => inbox.push(e))
+ onNodeStateChange((c) => edges.push(c))
+ const before = Date.now()
+ recordAgentEvent({ nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'blocked', lastMessage: 'Approve' } as NormalizedAgentEvent)
+ const after = Date.now()
+ expect(inbox[0].ts).toBeGreaterThanOrEqual(before)
+ expect(inbox[0].ts).toBeLessThanOrEqual(after)
+ expect(edges[0].ts).toBeGreaterThanOrEqual(before)
+ expect(edges[0].ts).toBeLessThanOrEqual(after)
+ } finally {
+ _resetForTest()
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/src/core/push-notify.ts b/src/core/push-notify.ts
index b6fcfc4a3..0af726a10 100644
--- a/src/core/push-notify.ts
+++ b/src/core/push-notify.ts
@@ -61,14 +61,91 @@ export interface PushNotifyEvent {
/** question only: the AskUserQuestion `multiSelect` flag — the picker accepts multiple choices.
* Rides the `nt` block so the phone renders multi-select. Omitted when absent/false. */
multiSelect?: boolean
+ /** Unix **MILLISECONDS** — see `TS_UNIT` below. Forwarded verbatim from `InboxEvent.ts`
+ * (`Date.now()` in agent-status-mirror); never divided, never re-stamped here. */
ts: number
}
-/** Where a batch is sent: the relay host (legacy) or, in granted mode, a list of grants to
- * fan the same body out over (once each, Bearer-authorized). */
-type SendTarget =
- | { mode: 'host'; id: PushHostIdentity }
- | { mode: 'grants'; grants: PushGrant[] }
+/** The unit EVERY `ts` in this file's payloads carries: Unix **milliseconds**, straight from the
+ * agent-status mirror (`InboxEvent.ts` / `NodeStateChange.ts` / `NodeNowChange.ts`, all
+ * `Date.now()`). The mirror is the source of truth for the whole timestamp story — the phone
+ * already divides `InboxEvent.ts` / `installedAt` / `resetsAt` by 1000 to build a `Date`, and the
+ * Live Activity `ContentState.ts` is the same field from the same producer. A second producer that
+ * writes SECONDS into one of these fields (an iOS foreground poll stamping
+ * `Date().timeIntervalSince1970`, say) disagrees with this one by a factor of 1000 and makes every
+ * comparison — "is this update newer than what I'm showing?" — nonsense. Nothing in this file may
+ * scale a `ts`: forward the mirror's number or don't send one. */
+export const TS_UNIT = 'unix-ms' as const
+
+/** Where a batch is sent. BOTH legs can be live at once: `host` is the relay-identity POST the
+ * backend fans out over its `relay_devices` rows, `grants` is one Bearer-authorized POST per
+ * SSH-possession grant. `null` on either side means that leg has no destination. */
+interface SendTarget {
+ host: PushHostIdentity | null
+ grants: PushGrant[]
+}
+
+/**
+ * One POST per DEVICE, not per grant FILE.
+ *
+ * `src/main`'s `allPushGrants` concatenates this machine's `~/.nodeterm/push-grants` with a sweep of
+ * every connected SSH host, and one phone that reached two of them dropped a DIFFERENT token on
+ * each — so the same `deviceId` can appear twice in the merged list and would earn that phone two
+ * notifications for one event. (`remote-push-grants`'s cache dedupes only within its own half.)
+ * First occurrence wins, which is why main puts the local grants first; a 401/403 on the survivor
+ * marks it dead and the next send promotes the other, the same self-healing the remote cache does.
+ */
+function dedupeGrantsByDevice(grants: readonly PushGrant[]): PushGrant[] {
+ const seen = new Set<string>()
+ const out: PushGrant[] = []
+ for (const g of grants) {
+ if (seen.has(g.deviceId)) continue
+ seen.add(g.deviceId)
+ out.push(g)
+ }
+ return out
+}
+
+/**
+ * The single targeting rule, shared by BOTH senders (`createPushNotify` and `createLiveUpdatePush`
+ * each had their own copy of it, and a copy is a thing that drifts). The per-sender gates — the
+ * master switch, DNT/packaged, the live-activities sub-gate — stay with their sender; this answers
+ * only "who does a batch go to".
+ *
+ * **It is a UNION, not an either/or.** It used to return host-mode the moment a phone was
+ * relay-paired and never look at the grants at all, to avoid double-pushing a phone that was both
+ * paired AND granted. The goal was right, the granularity was wrong: host mode fans out over the
+ * backend's `relay_devices` rows, and an SSH-ONLY phone has no row there — its grant was its only
+ * route — so ONE relay-paired phone silenced every other phone on the machine, with no error
+ * anywhere. A duplicate notification is a cheap regression; a phone that never rings is not.
+ *
+ * The correct exclusion is per DEVICE, and this process cannot express it: a `PushGrant` is keyed by
+ * the phone's `deviceId` (the grant filename), while the relay-paired registry
+ * (`remote-approved-devices.json`, read by `loadApprovedDevices`) stores nothing but base64 NaCl box
+ * PUBLIC KEYS — and this service is only told `hasPairedPhone: boolean` in the first place. The two
+ * identifiers never meet on the desktop: the phone's own deviceId is seen exactly once, transiently,
+ * during a LAN QR pair (`pairing-service.ts`'s `phoneDeviceId`, spent on the `/v1/relay/device` mint
+ * and never persisted), and not at all on the relay-only path where an unknown phone is pinned by
+ * pubkey after the SAS prompt. So neither core nor `src/main` can subtract the paired phones from
+ * the grant list today.
+ *
+ * Consequence, stated plainly: a phone that is BOTH relay-paired to this machine AND has dropped a
+ * grant it can reach receives TWO pushes for one event. Closing that needs the overlap to be
+ * knowable — either the backend does it (it sees the relay device row AND the grant's deviceId, so
+ * it is the only party holding both halves) or the desktop starts persisting the phone's deviceId
+ * beside its pinned pubkey at pair time. Both are protocol changes, not a filter we can add here.
+ */
+function resolveSendTarget(
+ getHostIdentity: () => PushHostIdentity | null,
+ getGrants: (() => PushGrant[]) | undefined
+): SendTarget | null {
+ const id = getHostIdentity()
+ // The paired-phone gate is host-mode only — a grant IS the phone's opt-in.
+ const host = id && id.hasPairedPhone ? id : null
+ const grants = dedupeGrantsByDevice(getGrants?.() ?? [])
+ if (!host && grants.length === 0) return null
+ return { host, grants }
+}
/** POST a JSON body with the shared timeout, swallowing network errors (no retry queue — the phone
* still polls the mirror). Returns the Response (so granted mode can read 401/403) or null on a
@@ -104,11 +181,11 @@ export interface PushNotifyDeps {
subscribe: (cb: (e: InboxEvent) => void) => () => void
/** The standing relay host identity, or null when none is configured/available. */
getHostIdentity: () => PushHostIdentity | null
- /** Granted mode (SSH-possession push grants; spec: 2026-07-21-push-grants). When there is no
- * usable relay host identity but grants exist, the batch is POSTed once PER grant with
- * `Authorization: Bearer <grant>` (no host identity fields) — the Server Edition's path. Optional:
- * the desktop leaves it unwired (it uses its relay identity; a host that is both paired AND
- * granted would double-push the same phone). */
+ /** Granted mode (SSH-possession push grants; spec: 2026-07-21-push-grants). The batch is POSTed
+ * once PER grant with `Authorization: Bearer <grant>` (no host identity fields) — the Server
+ * Edition's only path, and the desktop's route to any phone that reaches it over plain SSH.
+ * Sent ALONGSIDE host mode when both are live, never instead of it: see `resolveSendTarget` for
+ * why the exclusion cannot be done per device here, and what that costs. */
getGrants?: () => PushGrant[]
/** Mark a grant dead after a 401/403 (dropped until its file changes). Paired with `getGrants`. */
markGrantDead?: (grant: string) => void
@@ -191,18 +268,15 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
return true
}
- /** Resolve where a batch goes: the relay host (byte-identical legacy behavior) when a paired host
- * identity is available; else, in granted mode, the live grant list; else null (inert). The
- * master + DNT/packaged gates apply to both modes; the paired-phone gate is host-mode only (a
- * grant IS the phone's opt-in). */
+ /** Resolve where a batch goes. The master + DNT/packaged gates are this sender's; the rule for
+ * WHO gets it is the shared `resolveSendTarget` (both senders call it, so they cannot drift). */
function resolveTarget(): SendTarget | null {
if (!allowed()) return null
if (!deps.mobilePushEnabled()) return null
- const id = deps.getHostIdentity()
- if (id && id.hasPairedPhone) return { mode: 'host', id }
- const grants = deps.getGrants?.() ?? []
- if (grants.length > 0) return { mode: 'grants', grants }
- return null
+ return resolveSendTarget(
+ () => deps.getHostIdentity(),
+ deps.getGrants ? () => deps.getGrants!() : undefined
+ )
}
function scheduleFlush(): void {
@@ -250,6 +324,7 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
...(nodeTitle ? { nodeTitle } : {}),
...(e.options && e.options.length > 0 ? { options: e.options } : {}),
...(e.multiSelect ? { multiSelect: true } : {}),
+ // Unix MILLISECONDS (TS_UNIT): the mirror's InboxEvent.ts (Date.now()), forwarded verbatim.
ts: e.ts
}
// Presence-aware deferral: if the user is at the desktop right now, hold the alert instead of
@@ -290,17 +365,17 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
if (buffer.length > 0) scheduleFlush()
const url = `${apiBase}/v1/push/notify`
- if (target.mode === 'host') {
- // Legacy relay-identity body — byte-identical to the pre-grants shape.
+ if (target.host) {
+ // Relay-identity body — byte-identical to the pre-grants shape.
await postJson(fetchImpl, url, {
- hostDeviceId: target.id.hostDeviceId,
- hostPublicKeyB64: target.id.hostPublicKeyB64,
- hostLabel: target.id.hostLabel,
+ hostDeviceId: target.host.hostDeviceId,
+ hostPublicKeyB64: target.host.hostPublicKeyB64,
+ hostLabel: target.host.hostLabel,
events
})
- return
}
- // Granted mode: one POST per live grant, Bearer-authorized, NO host identity fields —
+ // …and the grants, in the SAME flush (see resolveSendTarget: a paired phone must not silence
+ // the SSH-only ones). One POST per live grant, Bearer-authorized, NO host identity fields —
// just `hostLabel` (os.hostname(), injected). A 401/403 marks that grant dead.
const label = deps.hostLabel?.()
for (const g of target.grants) {
@@ -396,6 +471,9 @@ export interface LiveUpdateItem {
* The backend uses it for APNs priority: an edge is priority 10, a tick priority 5 (iOS delays
* priority-5 liveactivity pushes, which was leaving the island up minutes after an answer). */
edge?: boolean
+ /** Unix **MILLISECONDS** (`TS_UNIT`) — the mirror's `Date.now()`, forwarded verbatim. This is the
+ * field the iOS Live Activity reads as `ContentState.ts`; it is ms on both producers (the push
+ * below and the phone's own foreground poll), so it is compared, never mixed with seconds. */
ts: number
}
@@ -407,8 +485,8 @@ export interface LiveUpdateDeps {
/** The standing relay host identity, or null when none is configured/available. */
getHostIdentity: () => PushHostIdentity | null
/** Granted mode (SSH-possession push grants; spec: 2026-07-21-push-grants). See the identical
- * field on `PushNotifyDeps`: no usable host identity + grants present ⇒ one POST per grant,
- * Bearer-authorized, no host fields. Desktop leaves it unwired. */
+ * field on `PushNotifyDeps`: one POST per grant, Bearer-authorized, no host fields, sent
+ * ALONGSIDE host mode when both are live (`resolveSendTarget`). */
getGrants?: () => PushGrant[]
/** Mark a grant dead after a 401/403 (dropped until its file changes). Paired with `getGrants`. */
markGrantDead?: (grant: string) => void
@@ -477,15 +555,16 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
return true
}
+ /** This sender's own gates (master + live-activities sub-gate + DNT/packaged), then the SHARED
+ * targeting rule — the same one `createPushNotify` uses, so the two cannot drift apart. */
function resolveTarget(): SendTarget | null {
if (!allowed()) return null
if (!deps.mobilePushEnabled()) return null
if (!deps.mobileLiveActivities()) return null
- const id = deps.getHostIdentity()
- if (id && id.hasPairedPhone) return { mode: 'host', id }
- const grants = deps.getGrants?.() ?? []
- if (grants.length > 0) return { mode: 'grants', grants }
- return null
+ return resolveSendTarget(
+ () => deps.getHostIdentity(),
+ deps.getGrants ? () => deps.getGrants!() : undefined
+ )
}
function nodeTitleOf(nodeId: string): string | undefined {
@@ -543,6 +622,8 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
...(needsYou && c.pendingId ? { pendingId: c.pendingId } : {}),
...(done && c.interrupted ? { interrupted: true } : {}),
...(done && c.stale ? { stale: true } : {}),
+ // Unix MILLISECONDS (TS_UNIT): the mirror's NodeStateChange.ts (Date.now()), forwarded
+ // verbatim. This lands in the phone's Live Activity ContentState.ts — do not scale it.
ts: c.ts
})
scheduleFlush()
@@ -558,6 +639,8 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
state: 'working',
...(c.activity ? { activity: c.activity.slice(0, LIVE_ACTIVITY_MAX) } : {}),
...(typeof c.contextPercent === 'number' ? { contextPercent: c.contextPercent } : {}),
+ // Unix MILLISECONDS (TS_UNIT): the mirror's NodeNowChange.ts (Date.now()), forwarded
+ // verbatim — the same field, same unit, as the state-edge sender above.
ts: c.ts
})
scheduleFlush()
@@ -621,17 +704,17 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
if (buffer.length > 0) scheduleFlush()
const url = `${apiBase}/v1/push/live-update`
- if (target.mode === 'host') {
- // Legacy relay-identity body — byte-identical to the pre-grants shape.
+ if (target.host) {
+ // Relay-identity body — byte-identical to the pre-grants shape.
await postJson(fetchImpl, url, {
- hostDeviceId: target.id.hostDeviceId,
- hostPublicKeyB64: target.id.hostPublicKeyB64,
- hostLabel: target.id.hostLabel,
+ hostDeviceId: target.host.hostDeviceId,
+ hostPublicKeyB64: target.host.hostPublicKeyB64,
+ hostLabel: target.host.hostLabel,
updates
})
- return
}
- // Granted mode: one POST per live grant, Bearer-authorized, NO host identity fields.
+ // …and the grants, in the SAME flush (see resolveSendTarget). One POST per live grant,
+ // Bearer-authorized, NO host identity fields.
const label = deps.hostLabel?.()
for (const g of target.grants) {
const res = await postJson(
diff --git a/src/main/index.ts b/src/main/index.ts
index 82d1d6569..32067ee58 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1320,11 +1320,15 @@ app.whenReady().then(async () => {
// GRANTED-MODE FALLBACK (spec: 2026-07-21-push-grants; owner-approved "B"). The desktop ALSO
// wires the SSH-possession push grants the Server Edition uses (src/server/index.ts) — a phone
// that reached this Mac by plain SSH drops a signed, device-scoped grant at
- // `~/.nodeterm/push-grants/<deviceId>.grant` on the Mac's own fs. `resolveTarget` keeps a SINGLE
- // sender: host-mode only when a relay identity is present AND a phone is paired; else (unpaired,
- // or no identity) it falls through to the grants. So a plain-SSH phone gets pushes for
- // 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).
+ // `~/.nodeterm/push-grants/<deviceId>.grant` on the Mac's own fs. `resolveSendTarget` sends BOTH
+ // legs whenever both are live — host mode for the relay-paired phones, one Bearer POST per grant
+ // for the SSH-only ones. It used to be either/or (host wins), which meant a SINGLE relay-paired
+ // phone silenced every SSH-only phone on this Mac: host mode fans out over the backend's
+ // `relay_devices` rows, where an SSH-only phone has no row at all. The per-device exclusion that
+ // would prevent the reverse cost (a phone that is paired AND granted gets two pushes) is not
+ // expressible here — a grant is keyed by the phone's deviceId, `loadApprovedDevices` stores only
+ // NaCl box pubkeys, and nothing on this machine maps one to the other. See the long note on
+ // `resolveSendTarget` in core/push-notify.ts.
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
@@ -1332,7 +1336,10 @@ app.whenReady().then(async () => {
// 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. */
+ /** Local grants first (this machine's own phone), then the hosts'. ORDER MATTERS: one phone that
+ * reached both this Mac and an SSH host dropped a different token on each, and push-notify's
+ * `dedupeGrantsByDevice` keeps the FIRST occurrence per deviceId — so the local token, the one
+ * that needs no host round-trip to stay fresh, is the survivor. */
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 => {