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.

98.9 KB
Raw Blame
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
import type { NormalizedAgentEvent } from '@shared/agents/normalize'
import nacl from 'tweetnacl'
import {
  createPushNotify,
  createLiveUpdatePush,
  createHostAuthCache,
  type PushNotifyDeps,
  type PushNotifyHandle,
  type PushHostIdentity,
  type LiveUpdateDeps,
  type LiveUpdateHandle
} from './push-notify'
import { popProverFor } from './relay/relay-pop'
import { createTestPopServer } from './relay/relay-pop.test-server'
import {
  onInboxActionable,
  onNodeStateChange,
  onNodeNowChange,
  recordAgentEvent,
  recordRawToolEvent,
  sweepStaleWorking,
  initAgentStatusMirror,
  _resetForTest,
  type InboxEvent,
  type NodeStateChange,
  type NodeNowChange
} from './agent-status-mirror'
import { syntheticAnsweredEvent } from './agents/pending-approvals'

/** A generic manual event source standing in for the mirror subscribe seams. */
function emitter<T>(): { subscribe: (cb: (e: T) => void) => () => void; emit: (e: T) => void } {
  const cbs = new Set<(e: T) => void>()
  return {
    subscribe: (cb) => {
      cbs.add(cb)
      return () => cbs.delete(cb)
    },
    emit: (e) => {
      for (const cb of cbs) cb(e)
    }
  }
}

// ---- helpers -------------------------------------------------------------------------------

/** A manual actionable-event source standing in for `onInboxActionable`. */
function makeEmitter(): {
  subscribe: (cb: (e: InboxEvent) => void) => () => void
  emit: (e: InboxEvent) => void
} {
  const cbs = new Set<(e: InboxEvent) => void>()
  return {
    subscribe: (cb) => {
      cbs.add(cb)
      return () => cbs.delete(cb)
    },
    emit: (e) => {
      for (const cb of cbs) cb(e)
    }
  }
}

function iev(p: Partial<InboxEvent>): InboxEvent {
  return { id: 'id', ts: 1000, nodeId: 'n1', kind: 'approval', title: 'Approve write', ...p }
}

const IDENTITY: PushHostIdentity = {
  hostDeviceId: 'host-device-1',
  hostPublicKeyB64: 'PUBKEYB64==',
  hostLabel: 'niova',
  hasPairedPhone: true
}

let fetchMock: ReturnType<typeof vi.fn>
let clock: number

function baseDeps(over: Partial<PushNotifyDeps> = {}): PushNotifyDeps {
  return {
    subscribe: () => () => {},
    getHostIdentity: () => IDENTITY,
    mobilePushEnabled: () => true,
    mobilePushNeedsYou: () => true,
    mobilePushDone: () => true,
    isPackaged: () => true,
    getNodeTitle: () => undefined,
    env: {},
    fetchImpl: fetchMock as unknown as typeof fetch,
    now: () => clock,
    batchWindowMs: 2000,
    throttleMs: 5000,
    ...over
  }
}

function bodyOf(callIndex = 0): {
  hostDeviceId: string
  hostPublicKeyB64: string
  hostLabel: string
  events: Array<Record<string, unknown>>
} {
  return JSON.parse(fetchMock.mock.calls[callIndex][1].body)
}

// ---- actionable-hook seam (via the REAL mirror) --------------------------------------------

describe('onInboxActionable seam (agent-status-mirror)', () => {
  let dir: string
  beforeEach(() => {
    _resetForTest()
    dir = fs.mkdtempSync(path.join(os.tmpdir(), 'push-hook-'))
    initAgentStatusMirror(path.join(dir, 'agent-status.json'))
  })
  afterEach(() => {
    _resetForTest()
    fs.rmSync(dir, { recursive: true, force: true })
  })

  function ev(p: Partial<NormalizedAgentEvent>): NormalizedAgentEvent {
    return { nodeId: 'n1', agentId: 'claude', kind: 'state', ...p } as NormalizedAgentEvent
  }

  it('fires approval ONCE for a re-asserted identical prompt (dedup)', () => {
    const seen: InboxEvent[] = []
    onInboxActionable((e) => seen.push(e))
    recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write to /etc/hosts' }))
    recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write to /etc/hosts' }))
    expect(seen.filter((e) => e.kind === 'approval')).toHaveLength(1)
    expect(seen[0].title).toBe('Approve write to /etc/hosts')
  })

  it('fires again when the ask genuinely changes', () => {
    const seen: InboxEvent[] = []
    onInboxActionable((e) => seen.push(e))
    recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write to A' }))
    recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write to B' }))
    expect(seen.filter((e) => e.kind === 'approval')).toHaveLength(2)
  })

  it('fires done on the turn edge, once', () => {
    const seen: InboxEvent[] = []
    onInboxActionable((e) => seen.push(e))
    recordAgentEvent(ev({ nodeId: 'n2', state: 'working', newTurn: true }))
    recordAgentEvent(ev({ nodeId: 'n2', state: 'done', lastMessage: 'All set.' }))
    recordAgentEvent(ev({ nodeId: 'n2', state: 'done' })) // no second edge
    const dones = seen.filter((e) => e.kind === 'done')
    expect(dones).toHaveLength(1)
    expect(dones[0].detail).toBe('All set.')
  })

  it('a subscriber that throws never breaks production or siblings', () => {
    const seen: InboxEvent[] = []
    onInboxActionable(() => {
      throw new Error('boom')
    })
    onInboxActionable((e) => seen.push(e))
    expect(() => recordAgentEvent(ev({ state: 'waiting', lastMessage: 'Pick one' }))).not.toThrow()
    expect(seen).toHaveLength(1)
    expect(seen[0].kind).toBe('question')
  })
})

// ---- push-notify service -------------------------------------------------------------------

describe('createPushNotify', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    fetchMock = vi.fn().mockResolvedValue({ ok: true })
    clock = 0
  })
  afterEach(() => {
    vi.useRealTimers()
  })

  it('batches events landing in the window into ONE POST', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
    em.emit(iev({ nodeId: 'b', kind: 'question', title: 'B' }))
    em.emit(iev({ nodeId: 'c', kind: 'done', title: 'C' }))
    expect(fetchMock).not.toHaveBeenCalled() // still buffering
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    expect(bodyOf().events).toHaveLength(3)
    h.stop()
  })

  it('per-node throttle drops a second event for the same node inside the window', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    em.emit(iev({ nodeId: 'a', title: 'first' }))
    em.emit(iev({ nodeId: 'a', title: 'second' })) // throttled (clock unchanged)
    await vi.advanceTimersByTimeAsync(2000)
    expect(bodyOf().events).toHaveLength(1)
    expect(bodyOf().events[0].title).toBe('first')
    // After the throttle window, the node can push again.
    clock = 5000
    em.emit(iev({ nodeId: 'a', title: 'third' }))
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).toHaveBeenCalledTimes(2)
    expect(bodyOf(1).events[0].title).toBe('third')
    h.stop()
  })

  it('caps at 10 events per POST and sends the remainder next', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    for (let i = 0; i < 12; i++) em.emit(iev({ nodeId: `n${i}`, title: `t${i}` }))
    await vi.advanceTimersByTimeAsync(2000)
    expect(bodyOf(0).events).toHaveLength(10)
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).toHaveBeenCalledTimes(2)
    expect(bodyOf(1).events).toHaveLength(2)
    h.stop()
  })

  it('emits the contract payload shape (host identity + trimmed event fields)', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    em.emit(
      iev({
        nodeId: 'node-9',
        agentId: 'claude',
        kind: 'approval',
        title: 'Approve write to /etc/hosts',
        detail: 'Edit needs sudo',
        ts: 1789,
        resolved: false,
        // Deterministic-approval ticket rides the mirror to the phone but MUST NOT ride the push
        // body (the phone re-reads the mirror before acting). See docs/hook-reply-approvals.md.
        pendingId: 'node-9-1789-42'
      })
    )
    await vi.advanceTimersByTimeAsync(2000)
    const [url, init] = fetchMock.mock.calls[0]
    expect(url).toBe('https://api.nodeterm.dev/v1/push/notify')
    expect(init.method).toBe('POST')
    const body = bodyOf()
    expect(body.hostDeviceId).toBe('host-device-1')
    expect(body.hostPublicKeyB64).toBe('PUBKEYB64==')
    expect(body.hostLabel).toBe('niova')
    expect(body.events[0]).toEqual({
      kind: 'approval',
      eventId: 'id', // the mirror InboxEvent.id, renamed — the raw `id` key itself stays out
      title: 'Approve write to /etc/hosts',
      detail: 'Edit needs sudo',
      nodeId: 'node-9',
      agentId: 'claude',
      ts: 1789
    })
    // The internal InboxEvent fields do not leak into the payload.
    expect(body.events[0]).not.toHaveProperty('id')
    expect(body.events[0]).not.toHaveProperty('resolved')
    expect(body.events[0]).not.toHaveProperty('pendingId')
    h.stop()
  })

  it('forwards the mirror inbox event id as eventId on an immediate send', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    em.emit(iev({ nodeId: 'a', id: '1789-7', title: 'A' }))
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    expect(bodyOf().events[0].eventId).toBe('1789-7')
    h.stop()
  })

  it('batched events each carry their OWN eventId, in order', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    em.emit(iev({ nodeId: 'a', id: '1000-1', title: 'A' }))
    em.emit(iev({ nodeId: 'b', id: '1000-2', kind: 'done', title: 'B' }))
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    expect(bodyOf().events.map((e) => e.eventId)).toEqual(['1000-1', '1000-2'])
    h.stop()
  })

  it('honors NODETERM_API_BASE override', async () => {
    const em = makeEmitter()
    const h = createPushNotify(
      baseDeps({ subscribe: em.subscribe, env: { NODETERM_API_BASE: 'http://localhost:9999' } })
    )
    em.emit(iev({ nodeId: 'a' }))
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock.mock.calls[0][0]).toBe('http://localhost:9999/v1/push/notify')
    h.stop()
  })

  it('drops on network error without throwing (no retry queue)', async () => {
    fetchMock.mockRejectedValue(new Error('offline'))
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    em.emit(iev({ nodeId: 'a' }))
    // The rejected fetch must not surface — flush swallows it (no retry queue).
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    h.stop()
  })

  describe('inert gates (no POST)', () => {
    async function expectNoPost(over: Partial<PushNotifyDeps>): Promise<void> {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe, ...over }))
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
      h.stop()
    }

    it('setting off', async () => {
      await expectNoPost({ mobilePushEnabled: () => false })
    })
    it('no relay host identity', async () => {
      await expectNoPost({ getHostIdentity: () => null })
    })
    it('no paired phone', async () => {
      await expectNoPost({ getHostIdentity: () => ({ ...IDENTITY, hasPairedPhone: false }) })
    })
    it('DO_NOT_TRACK', async () => {
      await expectNoPost({ env: { DO_NOT_TRACK: '1' } })
    })
    it('NODETERM_TELEMETRY_DISABLED', async () => {
      await expectNoPost({ env: { NODETERM_TELEMETRY_DISABLED: '1' } })
    })
    it('unpackaged without a local API base', async () => {
      await expectNoPost({ isPackaged: () => false, env: {} })
    })
  })

  describe('per-kind selection', () => {
    it('defaults send all kinds (needsYou + done both on)', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
      em.emit(iev({ nodeId: 'b', kind: 'question', title: 'B' }))
      em.emit(iev({ nodeId: 'c', kind: 'done', title: 'C' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events.map((e) => e.kind)).toEqual(['approval', 'question', 'done'])
      h.stop()
    })

    it('needsYou off drops approval + question but done still sends', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, mobilePushNeedsYou: () => false })
      )
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
      em.emit(iev({ nodeId: 'b', kind: 'question', title: 'B' }))
      em.emit(iev({ nodeId: 'c', kind: 'done', title: 'C' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events.map((e) => e.kind)).toEqual(['done'])
      h.stop()
    })

    it('done off drops done but needs-you kinds still send', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe, mobilePushDone: () => false }))
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
      em.emit(iev({ nodeId: 'b', kind: 'question', title: 'B' }))
      em.emit(iev({ nodeId: 'c', kind: 'done', title: 'C' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events.map((e) => e.kind)).toEqual(['approval', 'question'])
      h.stop()
    })

    it('both sub-gates off sends nothing (master stays honest)', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({
          subscribe: em.subscribe,
          mobilePushNeedsYou: () => false,
          mobilePushDone: () => false
        })
      )
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
      em.emit(iev({ nodeId: 'b', kind: 'question', title: 'B' }))
      em.emit(iev({ nodeId: 'c', kind: 'done', title: 'C' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
      h.stop()
    })

    it('a dropped kind does not consume the node throttle window', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, mobilePushNeedsYou: () => false })
      )
      // A dropped approval on node 'a' must not throttle a following done on 'a'.
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'dropped' }))
      em.emit(iev({ nodeId: 'a', kind: 'done', title: 'kept' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events).toHaveLength(1)
      expect(bodyOf().events[0].title).toBe('kept')
      h.stop()
    })
  })

  describe('nodeTitle enrichment', () => {
    it('includes nodeTitle when the accessor resolves one', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, getNodeTitle: (id) => (id === 'a' ? 'Backend server' : undefined) })
      )
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0].nodeTitle).toBe('Backend server')
      h.stop()
    })

    it('omits nodeTitle when the accessor returns undefined', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getNodeTitle: () => undefined }))
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0]).not.toHaveProperty('nodeTitle')
      h.stop()
    })

    it('omits nodeTitle when no accessor is wired at all', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getNodeTitle: undefined }))
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0]).not.toHaveProperty('nodeTitle')
      h.stop()
    })

    it('clips nodeTitle to 80 chars', async () => {
      const em = makeEmitter()
      const long = 'x'.repeat(200)
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getNodeTitle: () => long }))
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0].nodeTitle).toBe('x'.repeat(80))
      h.stop()
    })

    it('omits nodeTitle when the accessor throws (fail-open)', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({
          subscribe: em.subscribe,
          getNodeTitle: () => {
            throw new Error('boom')
          }
        })
      )
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events[0]).not.toHaveProperty('nodeTitle')
      h.stop()
    })
  })

  describe('question options pass-through', () => {
    it('passes question options into the notify payload', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', kind: 'question', title: 'Pick a theme', options: ['Dark', 'Light', 'System'] }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0].options).toEqual(['Dark', 'Light', 'System'])
      h.stop()
    })

    it('omits options when the event has none', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'Approve' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0]).not.toHaveProperty('options')
      h.stop()
    })

    it('passes multiSelect through when the question is multi-select', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', kind: 'question', title: 'Pick', options: ['A', 'B'], multiSelect: true }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(bodyOf().events[0].multiSelect).toBe(true)
      expect(bodyOf().events[0].options).toEqual(['A', 'B'])
      h.stop()
    })

    it('omits multiSelect when absent or false', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', kind: 'question', title: 'Pick', options: ['A'], multiSelect: false }))
      em.emit(iev({ nodeId: 'b', kind: 'question', title: 'Pick', options: ['A'] }))
      await vi.advanceTimersByTimeAsync(2000)
      for (const e of bodyOf().events) expect(e).not.toHaveProperty('multiSelect')
      h.stop()
    })
  })

  describe('granted mode (SSH-possession push grants)', () => {
    const GRANTS = [
      { deviceId: 'dev-A', grant: 'tok-A', connectionId: 'conn-A' },
      { deviceId: 'dev-B', grant: 'tok-B' }
    ]

    function grantDeps(over: Partial<PushNotifyDeps> = {}): PushNotifyDeps {
      return baseDeps({
        getHostIdentity: () => null, // no relay identity → granted mode
        getGrants: () => GRANTS,
        hostLabel: () => 'niova',
        ...over
      })
    }

    it('fans one POST out per grant: Bearer auth + hostLabel, and NO host identity fields', async () => {
      const em = makeEmitter()
      const h = createPushNotify(grantDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(2)
      const calls = fetchMock.mock.calls
      expect(calls.map((c) => c[1].headers.authorization)).toEqual(['Bearer tok-A', 'Bearer tok-B'])
      for (const c of calls) {
        expect(c[0]).toBe('https://api.nodeterm.dev/v1/push/notify')
        const body = JSON.parse(c[1].body)
        expect(body.hostLabel).toBe('niova')
        expect(body).not.toHaveProperty('hostDeviceId')
        expect(body).not.toHaveProperty('hostPublicKeyB64')
        expect(body.events).toHaveLength(1)
        expect(body.events[0].title).toBe('A')
      }
      h.stop()
    })

    it('grant-mode POSTs carry the same eventId as host mode', async () => {
      const em = makeEmitter()
      const h = createPushNotify(grantDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', id: '2000-3', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(2)
      for (const c of fetchMock.mock.calls) {
        expect(c[1].headers.authorization).toMatch(/^Bearer /)
        expect(JSON.parse(c[1].body).events[0].eventId).toBe('2000-3')
      }
      h.stop()
    })

    it('marks a grant dead on a 401/403 (only the failing one)', async () => {
      const dead: string[] = []
      // tok-A → 403, tok-B → 200 (keyed on the Bearer header).
      fetchMock.mockImplementation(async (_url: string, init: { headers: Record<string, string> }) => ({
        status: init.headers.authorization === 'Bearer tok-A' ? 403 : 200
      }))
      const em = makeEmitter()
      const h = createPushNotify(grantDeps({ subscribe: em.subscribe, markGrantDead: (g) => dead.push(g) }))
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(dead).toEqual(['tok-A'])
      h.stop()
    })

    it('only POSTs the grants getGrants currently returns (a dead grant is dropped)', async () => {
      const em = makeEmitter()
      const h = createPushNotify(grantDeps({ subscribe: em.subscribe, getGrants: () => [GRANTS[1]] }))
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer tok-B')
      h.stop()
    })

    it('is inert when no host identity AND no grants', async () => {
      const em = makeEmitter()
      const h = createPushNotify(grantDeps({ subscribe: em.subscribe, getGrants: () => [] }))
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
      h.stop()
    })

    it('honors the master + sub-gates in granted mode', async () => {
      const em = makeEmitter()
      const h = createPushNotify(grantDeps({ subscribe: em.subscribe, mobilePushEnabled: () => false }))
      em.emit(iev({ nodeId: 'a' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
      h.stop()
    })

  })

  // 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()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getGrants: () => [] }))
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().hostDeviceId).toBe('host-device-1')
      expect(fetchMock.mock.calls[0][1].headers.authorization).toBeUndefined()
      h.stop()
    })

    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()
    })

    // A grant authorizes pushes about the HOST it was dropped on — nothing else. src/main's
    // allPushGrants concatenates this machine's grants with a sweep of every connected SSH host, so
    // one phone that reached three hosts contributes three grants, each signed for a DIFFERENT
    // connectionId (the phone's own saved-connection UUID for that host — exactly the scope its
    // per-host mute is keyed by). Collapsing them per deviceId and posting every event under the
    // survivor sent host B's events under host A's grant: the backend then consulted A's mute for
    // B's event, and a host the user had turned OFF kept ringing the phone (issue #435, field
    // report). Events are routed to the grants swept from THEIR host; a node with no host
    // attribution (a local node, or the Server Edition) goes to this machine's own grants.
    it('PER-HOST: an event routes ONLY to the grants swept from the host its node lives on', 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-h1', host: 'u@h1' },
            { deviceId: 'dev-A', grant: 'tok-h2', host: 'u@h2' },
            { deviceId: 'dev-B', grant: 'tok-h2-B', host: 'u@h2' }
          ],
          grantHostFor: (nodeId) => ({ a: 'u@h1', b: 'u@h2' })[nodeId],
          hostLabel: () => 'niova'
        })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      em.emit(iev({ nodeId: 'b', title: 'B' }))
      em.emit(iev({ nodeId: 'c', title: 'C' })) // no attribution → local
      await vi.advanceTimersByTimeAsync(2000)
      const sent = fetchMock.mock.calls.map((c) => [
        c[1].headers.authorization,
        JSON.parse(c[1].body).events.map((e: { title: string }) => e.title)
      ])
      expect(sent).toEqual(
        expect.arrayContaining([
          ['Bearer tok-h1', ['A']],
          ['Bearer tok-h2', ['B']],
          ['Bearer tok-h2-B', ['B']],
          ['Bearer tok-local', ['C']]
        ])
      )
      expect(sent).toHaveLength(4)
      h.stop()
    })

    it('PER-HOST: a phone holding grants on two hosts gets ONE push per event, under the right host', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({
          subscribe: em.subscribe,
          getHostIdentity: () => null,
          getGrants: () => [
            { deviceId: 'dev-A', grant: 'tok-h1', host: 'u@h1' },
            { deviceId: 'dev-A', grant: 'tok-h2', host: 'u@h2' }
          ],
          grantHostFor: () => 'u@h2',
          hostLabel: () => 'niova'
        })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer tok-h2')
      h.stop()
    })

    // Without any host attribution (the Server Edition: one machine, its own grant dir) every
    // grant is local and every event is local — the pre-existing fan-out, unchanged. Two files
    // for one device cannot exist in one dir (the filename IS the deviceId), so the within-host
    // first-wins dedupe is defensive only.
    it('no grantHostFor (Server Edition): every event goes to every local grant, first-wins per device', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({
          subscribe: em.subscribe,
          getHostIdentity: () => null,
          getGrants: () => [
            { deviceId: 'dev-A', grant: 'tok-A' },
            { deviceId: 'dev-A', grant: 'tok-A-dup' },
            { deviceId: 'dev-B', grant: 'tok-B' }
          ],
          hostLabel: () => 'niova'
        })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock.mock.calls.map((c) => c[1].headers.authorization)).toEqual([
        'Bearer tok-A',
        'Bearer tok-B'
      ])
      h.stop()
    })

    // A remote node's event must NEVER fall back to this machine's grants: a grant dropped here
    // authorizes pushes about this machine only, and a phone that only reaches host h1 has no
    // connection to open a "local" event with anyway.
    it('PER-HOST: a remote node with no grant on its host is dropped from the granted leg', async () => {
      const em = makeEmitter()
      const h = createPushNotify(
        baseDeps({
          subscribe: em.subscribe,
          getHostIdentity: () => null,
          getGrants: () => [{ deviceId: 'dev-A', grant: 'tok-local' }],
          grantHostFor: () => 'u@h1',
          hostLabel: () => 'niova'
        })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
      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(
        baseDeps({
          subscribe: em.subscribe,
          getHostIdentity: () => ({ ...IDENTITY, hasPairedPhone: false }),
          getGrants,
          hostLabel: () => 'niova'
        })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      const body = JSON.parse(fetchMock.mock.calls[0][1].body)
      expect(body).not.toHaveProperty('hostDeviceId')
      expect(body).not.toHaveProperty('hostPublicKeyB64')
      expect(body.hostLabel).toBe('niova')
      expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer tok-X')
      expect(getGrants).toHaveBeenCalled()
      h.stop()
    })
  })

  describe('presence-aware alert deferral', () => {
    /** A manual present→away poke standing in for the desktop's powerMonitor edge detector. */
    function presenceEmitter(): { subscribe: (cb: () => void) => () => void; away: () => void } {
      let cb: (() => void) | null = null
      return {
        subscribe: (fn) => {
          cb = fn
          return () => {
            cb = null
          }
        },
        away: () => cb?.()
      }
    }

    it('HOLDS alerts while the user is present, releasing them on the away edge', async () => {
      const em = makeEmitter()
      const pres = presenceEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, isUserPresent: () => true, subscribePresence: pres.subscribe })
      )
      em.emit(iev({ nodeId: 'a', id: 'e1', title: 'A' }))
      em.emit(iev({ nodeId: 'b', id: 'e2', title: 'B' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled() // held while present
      pres.away()
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events.map((e) => e.title)).toEqual(['A', 'B'])
      h.stop()
    })

    it('a held event flushed on the away edge still carries its eventId', async () => {
      const em = makeEmitter()
      const pres = presenceEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, isUserPresent: () => true, subscribePresence: pres.subscribe })
      )
      em.emit(iev({ nodeId: 'a', id: '3000-1', title: 'A' }))
      em.emit(iev({ nodeId: 'b', id: '3000-2', title: 'B' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled() // held while present
      pres.away()
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events.map((e) => e.eventId)).toEqual(['3000-1', '3000-2'])
      h.stop()
    })

    it('on the away flush, DROPS held events resolved in the mirror and sends the rest', async () => {
      const em = makeEmitter()
      const pres = presenceEmitter()
      const h = createPushNotify(
        baseDeps({
          subscribe: em.subscribe,
          isUserPresent: () => true,
          subscribePresence: pres.subscribe,
          // e2 got resolved (answered / read) while held → dropped; e1 still unresolved → sent.
          isEventUnresolved: (_nodeId, eventId) => eventId !== 'e2'
        })
      )
      em.emit(iev({ nodeId: 'a', id: 'e1', kind: 'approval', title: 'A' }))
      em.emit(iev({ nodeId: 'b', id: 'e2', kind: 'done', title: 'B' }))
      pres.away()
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events.map((e) => e.title)).toEqual(['A'])
      h.stop()
    })

    it('presence OFF (isUserPresent false) sends immediately — no hold', async () => {
      const em = makeEmitter()
      const pres = presenceEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, isUserPresent: () => false, subscribePresence: pres.subscribe })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(bodyOf().events[0].title).toBe('A')
      h.stop()
    })

    it('no presence deps at all = exact legacy behavior (immediate send)', async () => {
      const em = makeEmitter()
      const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      h.stop()
    })

    it('bounds the hold queue, dropping the OLDEST past the cap of 50', async () => {
      const em = makeEmitter()
      const pres = presenceEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, isUserPresent: () => true, subscribePresence: pres.subscribe })
      )
      // 60 events on distinct nodes (so the per-node throttle never interferes). Cap 50 → oldest 10
      // (t0..t9) drop.
      for (let i = 0; i < 60; i++) em.emit(iev({ nodeId: `n${i}`, id: `e${i}`, title: `t${i}` }))
      pres.away()
      // 50 survivors flush 10/POST across sequential batch windows.
      for (let i = 0; i < 5; i++) await vi.advanceTimersByTimeAsync(2000)
      const titles = fetchMock.mock.calls.flatMap((c) =>
        JSON.parse(c[1].body).events.map((e: { title: string }) => e.title)
      )
      expect(titles).toHaveLength(50)
      expect(titles).toContain('t59') // newest kept
      expect(titles).not.toContain('t0') // oldest dropped
      h.stop()
    })

    it('stop() clears the hold queue (a later away edge sends nothing)', async () => {
      const em = makeEmitter()
      const pres = presenceEmitter()
      const h = createPushNotify(
        baseDeps({ subscribe: em.subscribe, isUserPresent: () => true, subscribePresence: pres.subscribe })
      )
      em.emit(iev({ nodeId: 'a', title: 'A' }))
      h.stop()
      pres.away()
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
    })
  })

  it('stop() unsubscribes so later events are ignored', async () => {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
    h.stop()
    em.emit(iev({ nodeId: 'a' }))
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).not.toHaveBeenCalled()
  })
})

// ---- live-update stream --------------------------------------------------------------------

describe('createLiveUpdatePush', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    fetchMock = vi.fn().mockResolvedValue({ ok: true })
    clock = 0
  })
  afterEach(() => {
    vi.useRealTimers()
  })

  function liveDeps(over: Partial<LiveUpdateDeps> = {}): LiveUpdateDeps {
    return {
      subscribeStateChange: () => () => {},
      subscribeNowChange: () => () => {},
      getHostIdentity: () => IDENTITY,
      mobilePushEnabled: () => true,
      mobileLiveActivities: () => true,
      isPackaged: () => true,
      getNodeTitle: () => undefined,
      env: {},
      fetchImpl: fetchMock as unknown as typeof fetch,
      now: () => clock,
      batchWindowMs: 1000,
      coalesceMs: 20000,
      ...over
    }
  }

  function liveBodyOf(callIndex = 0): {
    hostDeviceId: string
    hostPublicKeyB64: string
    hostLabel: string
    updates: Array<Record<string, unknown>>
  } {
    return JSON.parse(fetchMock.mock.calls[callIndex][1].body)
  }

  function wire(over: Partial<LiveUpdateDeps> = {}): {
    h: ReturnType<typeof createLiveUpdatePush>
    st: ReturnType<typeof emitter<NodeStateChange>>
    nw: ReturnType<typeof emitter<NodeNowChange>>
  } {
    const st = emitter<NodeStateChange>()
    const nw = emitter<NodeNowChange>()
    const h = createLiveUpdatePush(
      liveDeps({ subscribeStateChange: st.subscribe, subscribeNowChange: nw.subscribe, ...over })
    )
    return { h, st, nw }
  }

  it('posts a state edge within the batch window (immediate)', async () => {
    const { h, st } = wire()
    st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
    expect(fetchMock).not.toHaveBeenCalled() // still batching
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    const [url, init] = fetchMock.mock.calls[0]
    expect(url).toBe('https://api.nodeterm.dev/v1/push/live-update')
    expect(init.method).toBe('POST')
    expect(liveBodyOf().updates[0]).toMatchObject({ nodeId: 'a', event: 'start', state: 'working' })
    h.stop()
  })

  it('emits the contract payload shape (host identity + trimmed update fields)', async () => {
    const { h, st } = wire({ getNodeTitle: () => 'api-server' })
    st.emit({ nodeId: 'node-1', agentId: 'claude', event: 'update', state: 'needsYou', message: 'Approve write', ts: 42 })
    await vi.advanceTimersByTimeAsync(1000)
    const body = liveBodyOf()
    expect(body.hostDeviceId).toBe('host-device-1')
    expect(body.hostPublicKeyB64).toBe('PUBKEYB64==')
    expect(body.hostLabel).toBe('niova')
    expect(body.updates[0]).toEqual({
      nodeId: 'node-1',
      nodeTitle: 'api-server',
      agentId: 'claude',
      event: 'update',
      state: 'needsYou',
      // A state edge (here the needsYou edge) is marked so the backend can prioritize it (10 vs 5).
      edge: true,
      message: 'Approve write',
      ts: 42
    })
    h.stop()
  })

  it('sends a now-update immediately on the leading edge, then COALESCES ticks to ≥20s/node', async () => {
    const { h, nw } = wire()
    // Leading edge (no prior send) → sent.
    clock = 0
    nw.emit({ nodeId: 'a', activity: 'Editing a.ts', contextPercent: 10, ts: 0 })
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    expect(liveBodyOf(0).updates[0]).toMatchObject({
      event: 'update',
      state: 'working',
      activity: 'Editing a.ts',
      contextPercent: 10
    })
    // A second tick 5s later is inside the 20s window → coalesced (NOT sent yet).
    clock = 5000
    nw.emit({ nodeId: 'a', activity: 'Editing b.ts', ts: 5000 })
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    // At the window edge the coalesced LATEST flushes.
    clock = 20000
    await vi.advanceTimersByTimeAsync(20000)
    expect(fetchMock).toHaveBeenCalledTimes(2)
    expect(liveBodyOf(1).updates[0].activity).toBe('Editing b.ts')
    h.stop()
  })

  // A now-tick carries no state of its own, so it used to hardcode `state: 'working'` — and it can
  // sit parked for the whole coalesce window. Two producers fire one at exactly the wrong moment
  // (the raw Stop hook clears the activity; the context tail's 1 s poll lands the turn's final
  // usage record), so a tick would land AFTER the end and flip the island back to Working, with no
  // further edge left to end it.
  describe('a coalesced tick can never resurrect a finished session', () => {
    it('drops a PARKED tick when the state edge that supersedes it goes out', async () => {
      const { h, st, nw } = wire()
      clock = 0
      nw.emit({ nodeId: 'a', activity: 'Editing a.ts', ts: 0 }) // leading edge → sent
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      // A tick parked inside the window…
      clock = 5000
      nw.emit({ nodeId: 'a', activity: 'Editing b.ts', ts: 5000 })
      // …then the turn ends.
      st.emit({ nodeId: 'a', event: 'end', state: 'done', ts: 6000 } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      expect(liveBodyOf(1).updates[0]).toMatchObject({ event: 'end', state: 'done' })
      // Past the coalesce window: the parked tick must NOT flush behind the end.
      clock = 30000
      await vi.advanceTimersByTimeAsync(30000)
      expect(fetchMock).toHaveBeenCalledTimes(2)
      h.stop()
    })

    it('drops a tick that arrives AFTER the end (the 1 s context tail lands late)', async () => {
      const { h, st, nw } = wire()
      clock = 0
      st.emit({ nodeId: 'a', event: 'end', state: 'done', ts: 0 } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      clock = 2000
      nw.emit({ nodeId: 'a', activity: 'Editing late.ts', contextPercent: 42, ts: 2000 })
      await vi.advanceTimersByTimeAsync(30000)
      expect(fetchMock).toHaveBeenCalledTimes(1) // nothing followed the end
      h.stop()
    })

    it('also refuses a tick once the node is NEEDS-YOU (it would drop the buttons)', async () => {
      const { h, st, nw } = wire()
      clock = 0
      st.emit({
        nodeId: 'a',
        event: 'update',
        state: 'needsYou',
        kind: 'approval',
        pendingId: 'p1',
        ts: 0
      } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      clock = 2000
      nw.emit({ nodeId: 'a', activity: 'Running tests', ts: 2000 })
      await vi.advanceTimersByTimeAsync(30000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      h.stop()
    })

    it('a working node keeps ticking, and a re-entry into working resumes them', async () => {
      const { h, st, nw } = wire()
      clock = 0
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 0 } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      // Still working → the tick goes out as before.
      clock = 2000
      nw.emit({ nodeId: 'a', activity: 'Editing a.ts', ts: 2000 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(2)
      expect(liveBodyOf(1).updates[0]).toMatchObject({ state: 'working', activity: 'Editing a.ts' })
      // needsYou silences ticks…
      clock = 30000
      st.emit({ nodeId: 'a', event: 'update', state: 'needsYou', ts: 30000 } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(3)
      // …and answering it (back to working) lets them through again.
      clock = 60000
      st.emit({ nodeId: 'a', event: 'update', state: 'working', ts: 60000 } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      clock = 90000
      nw.emit({ nodeId: 'a', activity: 'Editing c.ts', ts: 90000 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(5)
      expect(liveBodyOf(4).updates[0]).toMatchObject({ state: 'working', activity: 'Editing c.ts' })
      h.stop()
    })

    it('a node we have seen no edge for still ticks (unchanged pre-edge behaviour)', async () => {
      const { h, nw } = wire()
      clock = 0
      nw.emit({ nodeId: 'never-edged', activity: 'Editing a.ts', ts: 0 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(1)
      expect(liveBodyOf(0).updates[0]).toMatchObject({ state: 'working' })
      h.stop()
    })
  })

  it('a state edge is NOT subject to the now-coalesce window', async () => {
    const { h, st, nw } = wire()
    clock = 0
    nw.emit({ nodeId: 'a', activity: 'x', ts: 0 })
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    // A state edge on the same node 2s later still posts immediately (no 20s wait).
    clock = 2000
    st.emit({ nodeId: 'a', event: 'end', state: 'done', message: 'Finished', ts: 2000 })
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(2)
    expect(liveBodyOf(1).updates[0]).toMatchObject({ event: 'end', state: 'done' })
    h.stop()
  })

  it('caps at 20 updates per POST and sends the remainder next', async () => {
    const { h, st } = wire()
    for (let i = 0; i < 25; i++) st.emit({ nodeId: `n${i}`, event: 'start', state: 'working', ts: i })
    await vi.advanceTimersByTimeAsync(1000)
    expect(liveBodyOf(0).updates).toHaveLength(20)
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(2)
    expect(liveBodyOf(1).updates).toHaveLength(5)
    h.stop()
  })

  it('honors NODETERM_API_BASE override', async () => {
    const { h, st } = wire({ env: { NODETERM_API_BASE: 'http://localhost:9999' } })
    st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock.mock.calls[0][0]).toBe('http://localhost:9999/v1/push/live-update')
    h.stop()
  })

  it('drops on network error without throwing', async () => {
    fetchMock.mockRejectedValue(new Error('offline'))
    const { h, st } = wire()
    st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
    await vi.advanceTimersByTimeAsync(1000)
    expect(fetchMock).toHaveBeenCalledTimes(1)
    h.stop()
  })

  describe('inert gates (no POST)', () => {
    async function expectNoPost(over: Partial<LiveUpdateDeps>): Promise<void> {
      const { h, st, nw } = wire(over)
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      nw.emit({ nodeId: 'a', activity: 'x', ts: 1 })
      await vi.advanceTimersByTimeAsync(2000)
      expect(fetchMock).not.toHaveBeenCalled()
      h.stop()
    }

    it('master switch off', async () => {
      await expectNoPost({ mobilePushEnabled: () => false })
    })
    it('live-activities sub-gate off', async () => {
      await expectNoPost({ mobileLiveActivities: () => false })
    })
    it('no relay host identity', async () => {
      await expectNoPost({ getHostIdentity: () => null })
    })
    it('no paired phone', async () => {
      await expectNoPost({ getHostIdentity: () => ({ ...IDENTITY, hasPairedPhone: false }) })
    })
    it('DO_NOT_TRACK', async () => {
      await expectNoPost({ env: { DO_NOT_TRACK: '1' } })
    })
    it('unpackaged without a local API base', async () => {
      await expectNoPost({ isPackaged: () => false, env: {} })
    })
  })

  describe('needsYou kind/options/pendingId pass-through (interactive Dynamic Island)', () => {
    it('passes kind + pendingId on an approval needsYou edge', async () => {
      const { h, st } = wire()
      st.emit({
        nodeId: 'a',
        event: 'update',
        state: 'needsYou',
        kind: 'approval',
        message: 'Approve write',
        pendingId: 'a-123-9',
        ts: 1
      })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u.kind).toBe('approval')
      expect(u.pendingId).toBe('a-123-9')
      expect(u).not.toHaveProperty('options')
      h.stop()
    })

    it('passes kind + options on a question needsYou edge', async () => {
      const { h, st } = wire()
      st.emit({
        nodeId: 'a',
        event: 'update',
        state: 'needsYou',
        kind: 'question',
        message: 'Pick a theme',
        options: ['Dark', 'Light', 'System'],
        ts: 1
      })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u.kind).toBe('question')
      expect(u.options).toEqual(['Dark', 'Light', 'System'])
      expect(u).not.toHaveProperty('pendingId')
      h.stop()
    })

    it('omits kind/options/pendingId on working and done edges', async () => {
      const { h, st } = wire()
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      st.emit({ nodeId: 'b', event: 'end', state: 'done', message: 'Finished', ts: 2 })
      await vi.advanceTimersByTimeAsync(1000)
      for (const u of liveBodyOf().updates) {
        expect(u).not.toHaveProperty('kind')
        expect(u).not.toHaveProperty('options')
        expect(u).not.toHaveProperty('pendingId')
      }
      h.stop()
    })

    it('now-update (activity/context) ticks never carry kind/options/pendingId', async () => {
      const { h, nw } = wire()
      clock = 0
      nw.emit({ nodeId: 'a', activity: 'Editing a.ts', contextPercent: 10, ts: 0 })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u).not.toHaveProperty('kind')
      expect(u).not.toHaveProperty('options')
      expect(u).not.toHaveProperty('pendingId')
      h.stop()
    })

    it('passes multiSelect on a question needsYou edge; omits it when absent', async () => {
      const { h, st } = wire()
      st.emit({
        nodeId: 'a',
        event: 'update',
        state: 'needsYou',
        kind: 'question',
        options: ['A', 'B'],
        multiSelect: true,
        ts: 1
      })
      st.emit({ nodeId: 'b', event: 'update', state: 'needsYou', kind: 'question', options: ['A'], ts: 2 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(liveBodyOf().updates[0].multiSelect).toBe(true)
      expect(liveBodyOf().updates[1]).not.toHaveProperty('multiSelect')
      h.stop()
    })

    it('never carries multiSelect on a working/done edge even if the change object has it', async () => {
      const { h, st } = wire()
      // Belt-and-braces: a non-needsYou change with a stray multiSelect must not leak it.
      st.emit({ nodeId: 'a', event: 'start', state: 'working', multiSelect: true, ts: 1 } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      expect(liveBodyOf().updates[0]).not.toHaveProperty('multiSelect')
      h.stop()
    })
  })

  // The mirror sends message:'Stopped' for BOTH an interrupt and the stale sweep, and 'Finished'
  // for a real completion — so the phone was deciding WHY a turn ended from a display STRING, and
  // could not tell "you stopped it" from "we lost the host" at all. These two flags are the
  // structured answer; they ride done edges only.
  describe('done-edge end reason (interrupted / stale)', () => {
    it('forwards interrupted:true on an interrupted done edge', async () => {
      const { h, st } = wire()
      st.emit({ nodeId: 'a', event: 'end', state: 'done', message: 'Stopped', interrupted: true, ts: 1 })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u.interrupted).toBe(true)
      expect(u).not.toHaveProperty('stale')
      h.stop()
    })

    it('forwards stale:true on a sweep-produced done edge', async () => {
      const { h, st } = wire()
      st.emit({ nodeId: 'a', event: 'end', state: 'done', message: 'Stopped', stale: true, ts: 1 })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u.stale).toBe(true)
      expect(u).not.toHaveProperty('interrupted')
      h.stop()
    })

    it('omits both on a real completion (a plain done edge)', async () => {
      const { h, st } = wire()
      st.emit({ nodeId: 'a', event: 'end', state: 'done', message: 'Finished', ts: 1 })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u).not.toHaveProperty('interrupted')
      expect(u).not.toHaveProperty('stale')
      h.stop()
    })

    it('never carries either on a working/needsYou edge even if the change object has them', async () => {
      const { h, st } = wire()
      // Belt-and-braces: only a done edge may carry an end reason.
      st.emit({ nodeId: 'a', event: 'start', state: 'working', interrupted: true, stale: true, ts: 1 } as NodeStateChange)
      st.emit({
        nodeId: 'b',
        event: 'update',
        state: 'needsYou',
        message: 'Approve',
        interrupted: true,
        stale: true,
        ts: 2
      } as NodeStateChange)
      await vi.advanceTimersByTimeAsync(1000)
      const updates = liveBodyOf().updates
      expect(updates).toHaveLength(2)
      for (const u of updates) {
        expect(u).not.toHaveProperty('interrupted')
        expect(u).not.toHaveProperty('stale')
      }
      h.stop()
    })

    it('now-update (activity/context) ticks never carry an end reason', async () => {
      const { h, nw } = wire()
      clock = 0
      nw.emit({ nodeId: 'a', activity: 'Editing a.ts', contextPercent: 10, ts: 0 })
      await vi.advanceTimersByTimeAsync(1000)
      const u = liveBodyOf().updates[0]
      expect(u).not.toHaveProperty('interrupted')
      expect(u).not.toHaveProperty('stale')
      h.stop()
    })

    describe('via the real mirror', () => {
      let dir: string
      beforeEach(() => {
        _resetForTest()
        dir = fs.mkdtempSync(path.join(os.tmpdir(), 'push-endreason-'))
        initAgentStatusMirror(path.join(dir, 'agent-status.json'))
      })
      afterEach(() => {
        _resetForTest()
        fs.rmSync(dir, { recursive: true, force: true })
      })

      function ev(p: Partial<NormalizedAgentEvent>): NormalizedAgentEvent {
        return { nodeId: 'n1', agentId: 'claude', kind: 'state', ...p } as NormalizedAgentEvent
      }

      it("an interrupted turn rides as interrupted:true — and its message is the sweep's own 'Stopped'", async () => {
        const h = createLiveUpdatePush(
          liveDeps({ subscribeStateChange: onNodeStateChange, subscribeNowChange: onNodeNowChange })
        )
        recordAgentEvent(ev({ state: 'working', newTurn: true }))
        recordAgentEvent(ev({ state: 'done', interrupted: true }))
        await vi.advanceTimersByTimeAsync(1000)
        const end = liveBodyOf().updates.find((u: Record<string, unknown>) => u.event === 'end')!
        expect(end.interrupted).toBe(true)
        expect(end).not.toHaveProperty('stale')
        // The very collision this feature exists for: the string is the SAME as the sweep's.
        expect(end.message).toBe('Stopped')
        h.stop()
      })

      it('a sweep-presumed-gone session rides as stale:true under that same message', async () => {
        const h = createLiveUpdatePush(
          liveDeps({ subscribeStateChange: onNodeStateChange, subscribeNowChange: onNodeNowChange })
        )
        recordAgentEvent(ev({ state: 'working', newTurn: true }))
        // Nobody heard from it for the stale window → the sweep fires the synthetic end.
        expect(sweepStaleWorking(Date.now() + 60 * 60_000, 20 * 60_000)).toEqual(['n1'])
        await vi.advanceTimersByTimeAsync(1000)
        const end = liveBodyOf().updates.find((u: Record<string, unknown>) => u.event === 'end')!
        expect(end.stale).toBe(true)
        expect(end).not.toHaveProperty('interrupted')
        expect(end.message).toBe('Stopped')
        h.stop()
      })

      it('a real completion carries neither flag', async () => {
        const h = createLiveUpdatePush(
          liveDeps({ subscribeStateChange: onNodeStateChange, subscribeNowChange: onNodeNowChange })
        )
        recordAgentEvent(ev({ state: 'working', newTurn: true }))
        recordAgentEvent(ev({ state: 'done', lastMessage: 'Done' }))
        await vi.advanceTimersByTimeAsync(1000)
        const end = liveBodyOf().updates.find((u: Record<string, unknown>) => u.event === 'end')!
        expect(end.message).toBe('Finished')
        expect(end).not.toHaveProperty('interrupted')
        expect(end).not.toHaveProperty('stale')
        h.stop()
      })
    })
  })

  describe('state-edge marking (edge flag)', () => {
    it('marks every state edge (start/needsYou/end) with edge:true', async () => {
      const { h, st } = wire()
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      st.emit({ nodeId: 'b', event: 'update', state: 'needsYou', message: 'Approve', ts: 2 })
      st.emit({ nodeId: 'c', event: 'end', state: 'done', message: 'Finished', ts: 3 })
      await vi.advanceTimersByTimeAsync(1000)
      for (const u of liveBodyOf().updates) expect(u.edge).toBe(true)
      h.stop()
    })

    it('never marks a now-tick (activity/context) with edge', async () => {
      const { h, nw } = wire()
      clock = 0
      nw.emit({ nodeId: 'a', activity: 'Editing a.ts', contextPercent: 10, ts: 0 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(liveBodyOf().updates[0]).not.toHaveProperty('edge')
      h.stop()
    })

    // Wire the live-update push to the REAL mirror seams so the synthetic answered blocked→working
    // transition (built exactly as the held hook's second POST) is exercised end-to-end.
    describe('via the real mirror', () => {
      let dir: string
      beforeEach(() => {
        _resetForTest()
        dir = fs.mkdtempSync(path.join(os.tmpdir(), 'push-edge-'))
        initAgentStatusMirror(path.join(dir, 'agent-status.json'))
      })
      afterEach(() => {
        _resetForTest()
        fs.rmSync(dir, { recursive: true, force: true })
      })

      function ev(p: Partial<NormalizedAgentEvent>): NormalizedAgentEvent {
        return { nodeId: 'n1', agentId: 'claude', kind: 'state', ...p } as NormalizedAgentEvent
      }

      it('the answered blocked→working synthetic transition flows through onNodeStateChange as an edge', async () => {
        const h = createLiveUpdatePush(
          liveDeps({ subscribeStateChange: onNodeStateChange, subscribeNowChange: onNodeNowChange })
        )
        recordAgentEvent(ev({ state: 'working', newTurn: true })) // start edge
        recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write', pendingId: 'n1-1-1' })) // needsYou edge
        // The answered signal (allow) → synthetic working, i.e. a blocked→working state edge.
        recordAgentEvent(syntheticAnsweredEvent('n1', 'n1-1-1', 'allow')!)
        recordAgentEvent(ev({ state: 'done', lastMessage: 'Done' })) // end edge
        await vi.advanceTimersByTimeAsync(1000)
        const updates = liveBodyOf().updates
        // Four state edges, and every one is marked.
        expect(updates.map((u: Record<string, unknown>) => [u.event, u.state])).toEqual([
          ['start', 'working'],
          ['update', 'needsYou'],
          ['start', 'working'],
          ['end', 'done']
        ])
        for (const u of updates) expect(u.edge).toBe(true)
        h.stop()
      })

      it('activity ticks interleaved with edges stay unmarked while edges are marked', async () => {
        const h = createLiveUpdatePush(
          liveDeps({ subscribeStateChange: onNodeStateChange, subscribeNowChange: onNodeNowChange })
        )
        recordAgentEvent(ev({ state: 'working', newTurn: true })) // start edge
        recordRawToolEvent('n1', { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls' } }) // now-tick
        await vi.advanceTimersByTimeAsync(1000)
        const updates = liveBodyOf().updates
        const start = updates.find((u: Record<string, unknown>) => u.event === 'start')!
        const tick = updates.find((u: Record<string, unknown>) => u.activity === 'Running ls')!
        expect(start.edge).toBe(true)
        expect(tick).not.toHaveProperty('edge')
        h.stop()
      })
    })
  })

  describe('granted mode (SSH-possession push grants)', () => {
    const GRANTS = [
      { deviceId: 'dev-A', grant: 'tok-A' },
      { deviceId: 'dev-B', grant: 'tok-B' }
    ]

    it('fans a state edge out per grant: Bearer auth + hostLabel, no host identity fields', async () => {
      const { h, st } = wire({ getHostIdentity: () => null, getGrants: () => GRANTS, hostLabel: () => 'niova' })
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).toHaveBeenCalledTimes(2)
      const calls = fetchMock.mock.calls
      expect(calls.map((c) => c[1].headers.authorization)).toEqual(['Bearer tok-A', 'Bearer tok-B'])
      for (const c of calls) {
        expect(c[0]).toBe('https://api.nodeterm.dev/v1/push/live-update')
        const body = JSON.parse(c[1].body)
        expect(body.hostLabel).toBe('niova')
        expect(body).not.toHaveProperty('hostDeviceId')
        expect(body).not.toHaveProperty('hostPublicKeyB64')
        expect(body.updates[0]).toMatchObject({ nodeId: 'a', event: 'start', state: 'working', edge: true })
      }
      h.stop()
    })

    it('marks a grant dead on a 401/403', async () => {
      const dead: string[] = []
      fetchMock.mockImplementation(async (_url: string, init: { headers: Record<string, string> }) => ({
        status: init.headers.authorization === 'Bearer tok-B' ? 401 : 200
      }))
      const { h, st } = wire({
        getHostIdentity: () => null,
        getGrants: () => GRANTS,
        hostLabel: () => 'niova',
        markGrantDead: (g) => dead.push(g)
      })
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(dead).toEqual(['tok-B'])
      h.stop()
    })

    // 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()
    })

    // Same per-host routing as notify (issue #435): a Live Activity update about a node on host h2
    // goes ONLY under h2's grant — never under another host's, whose connectionId names a host the
    // phone may have muted, and whose card the phone would then attribute to the wrong connection.
    it('PER-HOST: an update routes ONLY to the grants swept from the host its node lives on', async () => {
      const { h, st } = wire({
        getHostIdentity: () => null,
        getGrants: () => [
          { deviceId: 'dev-A', grant: 'tok-local' },
          { deviceId: 'dev-A', grant: 'tok-h1', host: 'u@h1' },
          { deviceId: 'dev-A', grant: 'tok-h2', host: 'u@h2' }
        ],
        grantHostFor: (nodeId) => ({ a: 'u@h2' })[nodeId],
        hostLabel: () => 'niova'
      })
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      st.emit({ nodeId: 'c', event: 'start', state: 'working', ts: 2 }) // unattributed → local
      await vi.advanceTimersByTimeAsync(1000)
      const sent = fetchMock.mock.calls.map((c) => [
        c[1].headers.authorization,
        JSON.parse(c[1].body).updates.map((u: { nodeId: string }) => u.nodeId)
      ])
      expect(sent).toEqual(expect.arrayContaining([['Bearer tok-h2', ['a']], ['Bearer tok-local', ['c']]]))
      expect(sent).toHaveLength(2)
      h.stop()
    })

    it('is inert when no host identity AND no grants', async () => {
      const { h, st } = wire({ getHostIdentity: () => null, getGrants: () => [] })
      st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
      await vi.advanceTimersByTimeAsync(1000)
      expect(fetchMock).not.toHaveBeenCalled()
      h.stop()
    })
  })

  it('stop() unsubscribes both seams so later events are ignored', async () => {
    const { h, st, nw } = wire()
    h.stop()
    st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
    nw.emit({ nodeId: 'a', activity: 'x', ts: 1 })
    await vi.advanceTimersByTimeAsync(2000)
    expect(fetchMock).not.toHaveBeenCalled()
  })
})


describe('live-update: the You: prompt line', () => {
  it('rides the working start edge only', async () => {
    const posts: any[] = []
    let emit: ((c: any) => void) | null = null
    const h = createLiveUpdatePush({
      subscribeStateChange: (cb) => {
        emit = cb
        return () => {}
      },
      subscribeNowChange: () => () => {},
      getHostIdentity: () => ({ hostDeviceId: 'h', hostToken: 't', hasPairedPhone: true }) as never,
      mobilePushEnabled: () => true,
      mobileLiveActivities: () => true,
      isPackaged: () => true,
      apiBase: 'https://example.invalid',
      fetchImpl: (async (_u: string, init: any) => {
        posts.push(JSON.parse(init.body))
        return { ok: true, status: 200, json: async () => ({}) } as never
      }) as never
    })
    emit!({ nodeId: 'n1', event: 'start', state: 'working', prompt: 'fix the login bug', ts: 1 })
    emit!({ nodeId: 'n1', event: 'end', state: 'done', prompt: 'should be dropped', ts: 2 })
    await h._flushNow()
    const items = posts.flatMap((p) => p.updates)
    expect(items.find((i: any) => i.state === 'working')?.prompt).toBe('fix the login bug')
    // An end edge never carries a stale You: line.
    expect(items.find((i: any) => i.state === 'done')?.prompt).toBeUndefined()
    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 })
    }
  })
})

// ---- host key proof-of-possession: the hostAuth session (relay-pop.ts) ----------------------
// A PoP-enabled backend latches a host once it has proven possession of its key, and from then on
// refuses an unproven host-mode send (403 pop_required). The host proves once through
// /v1/push/host-auth and attaches the session it gets (`hostAuth`) to notify and live-update.
// Without a prover nothing changes: no challenge, no field (every test above runs that way).
describe('host-mode push proves possession of the host key (hostAuth session)', () => {
  const MIN = 60_000
  const keys = nacl.box.keyPair()
  const PUB = Buffer.from(keys.publicKey).toString('base64')
  const PROVEN: PushHostIdentity = { ...IDENTITY, hostPublicKeyB64: PUB, prove: popProverFor(keys) }

  type Init = { body: string; signal?: AbortSignal; headers: Record<string, string> }
  type Answer = unknown | Promise<unknown>
  type Route = (init: Init) => Answer
  /** A real Response: the only kind a key-proof refusal check may read. */
  const json = (status: number, body: unknown): Response => new Response(JSON.stringify(body), { status })
  /** A bare answer with no clone()/json(): reading it throws, so a test using it pins "not read". */
  const bare = (status: number): { ok: boolean; status: number } => ({ ok: status >= 200 && status < 300, status })

  let pop: ReturnType<typeof createTestPopServer>
  let sessions: number
  const challengeOk: Route = (init) => json(200, pop.issue(JSON.parse(init.body).hostPublicKeyB64, 'push'))
  /** The backend's /v1/push/host-auth: verify with purpose push + subject hostDeviceId, then a new session. */
  const hostAuthOk: Route = (init) => {
    const b = JSON.parse(init.body)
    const proven = pop.verify({
      hostPublicKeyB64: b.hostPublicKeyB64,
      purpose: 'push',
      subject: IDENTITY.hostDeviceId,
      popChallenge: b.popChallenge,
      popProof: b.popProof
    })
    return proven ? json(200, { hostAuth: `HA-${++sessions}`, exp: 0 }) : json(403, { error: 'pop_invalid' })
  }

  function route(r: { challenge?: Route; hostAuth?: Route; notify?: Route; live?: Route } = {}): void {
    fetchMock = vi.fn(async (url: string, init: Init) => {
      if (url.endsWith('/v1/relay/challenge')) return (r.challenge ?? challengeOk)(init)
      if (url.endsWith('/v1/push/host-auth')) return (r.hostAuth ?? hostAuthOk)(init)
      if (url.endsWith('/v1/push/notify')) return (r.notify ?? (() => bare(200)))(init)
      if (url.endsWith('/v1/push/live-update')) return (r.live ?? (() => bare(200)))(init)
      throw new Error(`unexpected fetch ${url}`)
    })
  }
  const paths = (): string[] => fetchMock.mock.calls.map((c) => String(c[0]).replace('https://api.nodeterm.dev', ''))
  const callsTo = (suffix: string): Array<[string, Init]> =>
    fetchMock.mock.calls.filter((c) => String(c[0]).endsWith(suffix)) as Array<[string, Init]>
  const bodyTo = (suffix: string, i = -1): Record<string, unknown> => JSON.parse(callsTo(suffix).at(i)![1].body)

  beforeEach(() => {
    vi.useFakeTimers()
    clock = 0
    sessions = 0
    pop = createTestPopServer()
    route()
  })
  afterEach(() => {
    vi.useRealTimers()
  })

  /** A notify service over PROVEN with a manual event source; `send` emits one event on a fresh node. */
  function notify(over: Partial<PushNotifyDeps> = {}): { h: PushNotifyHandle; send: () => Promise<void> } {
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getHostIdentity: () => PROVEN, ...over }))
    let n = 0
    return {
      h,
      async send() {
        em.emit(iev({ nodeId: `n${++n}`, title: `t${n}` }))
        await vi.advanceTimersByTimeAsync(2000)
      }
    }
  }

  it('first flush: challenge, host-auth, then the notify carrying the session', async () => {
    const { h, send } = notify()
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    expect(bodyTo('/v1/relay/challenge')).toEqual({ hostPublicKeyB64: PUB, purpose: 'push' })
    const auth = bodyTo('/v1/push/host-auth')
    expect(Object.keys(auth).sort()).toEqual(['hostDeviceId', 'hostPublicKeyB64', 'popChallenge', 'popProof'])
    expect(auth).toMatchObject({ hostDeviceId: 'host-device-1', hostPublicKeyB64: PUB })
    const body = bodyTo('/v1/push/notify')
    expect(body).toMatchObject({ hostDeviceId: 'host-device-1', hostPublicKeyB64: PUB, hostLabel: 'niova', hostAuth: 'HA-1' })
    expect(body.events).toHaveLength(1)
    h.stop()
  })

  it('a second flush inside 10 minutes reuses the session: ONE call, the notify', async () => {
    const { h, send } = notify()
    await send()
    fetchMock.mockClear()
    clock = 10 * MIN - 1
    await send()
    expect(paths()).toEqual(['/v1/push/notify'])
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
    h.stop()
  })

  it('after 10 minutes on our own clock the flush proves again', async () => {
    const { h, send } = notify()
    await send()
    fetchMock.mockClear()
    clock = 10 * MIN
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-2')
    h.stop()
  })

  it.each(['pop_invalid', 'pop_required'])(
    'a notify answered 403 %s clears the session: the next flush proves again',
    async (error) => {
      let n = 0
      route({ notify: () => (++n === 1 ? json(403, { error }) : bare(200)) })
      const { h, send } = notify()
      await send()
      fetchMock.mockClear()
      clock = 6000
      await send()
      expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
      expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-2')
      h.stop()
    }
  )

  it('a 403 that is not a key-proof refusal (forbidden) keeps the session', async () => {
    let n = 0
    route({ notify: () => (++n === 1 ? json(403, { error: 'forbidden' }) : bare(200)) })
    const { h, send } = notify()
    await send()
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/push/notify'])
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
    h.stop()
  })

  it.each<[string, { challenge?: Route; hostAuth?: Route }]>([
    ['the challenge answering 503', { challenge: () => bare(503) }],
    ['the challenge answering 500', { challenge: () => bare(500) }],
    ['the challenge answering 429', { challenge: () => bare(429) }],
    ['a challenge network error', { challenge: () => Promise.reject(new TypeError('fetch failed')) }],
    ['a malformed challenge 200', { challenge: () => json(200, { nope: true }) }],
    // A server key the proof cannot use: the all-zero key gives a degenerate shared secret.
    ['a challenge with an unusable server key', { challenge: () => json(200, { challenge: 'c.x', serverPublicKeyB64: 'A'.repeat(43) + '=' }) }],
    ['host-auth answering 503', { hostAuth: () => bare(503) }],
    ['host-auth answering 429', { hostAuth: () => bare(429) }],
    ['host-auth refusing the proof (403 pop_invalid)', { hostAuth: () => json(403, { error: 'pop_invalid' }) }],
    ['host-auth refusing the host (403 forbidden)', { hostAuth: () => json(403, { error: 'forbidden' }) }],
    ['a host-auth network error', { hostAuth: () => Promise.reject(new TypeError('fetch failed')) }],
    ['a malformed host-auth 200', { hostAuth: () => json(200, { nope: true }) }],
    // The backend reads an EMPTY hostAuth as present-but-invalid: it must never be sent.
    ['a host-auth 200 with an empty session', { hostAuth: () => json(200, { hostAuth: '', exp: 0 }) }]
  ])('%s drops the host notify for that batch (never an unproven send) and throws nothing', async (_label, r) => {
    route(r)
    const { h, send } = notify()
    await expect(send()).resolves.toBeUndefined()
    expect(callsTo('/v1/push/notify')).toHaveLength(0)
    h.stop()
  })

  it('a dropped host leg does not drop the granted leg of the same flush', async () => {
    route({ challenge: () => bare(503) })
    const { h, send } = notify({ getGrants: () => [{ deviceId: 'dev-A', grant: 'tok-A' }] })
    await send()
    const sent = callsTo('/v1/push/notify')
    expect(sent).toHaveLength(1)
    expect(sent[0][1].headers.authorization).toBe('Bearer tok-A')
    expect(JSON.parse(sent[0][1].body)).not.toHaveProperty('hostAuth')
    h.stop()
  })

  it.each([404, 405])('an old backend (challenge %i) gets the legacy notify: no hostAuth field', async (status) => {
    route({ challenge: () => bare(status) })
    const { h, send } = notify()
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])
    expect(Object.keys(bodyTo('/v1/push/notify'))).toEqual(['hostDeviceId', 'hostPublicKeyB64', 'hostLabel', 'events'])
    h.stop()
  })

  it('host-auth answering 404 (no session route) sends the legacy notify', async () => {
    route({ hostAuth: () => bare(404) })
    const { h, send } = notify()
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    expect(bodyTo('/v1/push/notify')).not.toHaveProperty('hostAuth')
    h.stop()
  })

  it('an old backend is remembered: the next flush inside 10 minutes asks no challenge', async () => {
    route({ challenge: () => bare(404) })
    const { h, send } = notify()
    await send()
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/push/notify'])
    expect(bodyTo('/v1/push/notify')).not.toHaveProperty('hostAuth')
    fetchMock.mockClear()
    clock = 10 * MIN
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])
    h.stop()
  })

  it('a legacy notify answered 403 forgets the old-backend verdict: the next flush asks again and proves', async () => {
    // A proxy answers the challenge 404 while the backend redeploys; the unproven notify lands on the
    // fresh backend, which requires a proof from this latched host. That batch is only dropped, and
    // the 403 is judged by its status alone (an unproven send's body is never read).
    let redeploying = true
    let n = 0
    route({
      challenge: (init) => (redeploying ? bare(404) : challengeOk(init)),
      notify: () => (++n === 1 ? bare(403) : bare(200))
    })
    const { h, send } = notify()
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])
    redeploying = false
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
    h.stop()
  })

  it('without a prover nothing changes: no challenge, no hostAuth (byte-identical legacy)', async () => {
    const { h, send } = notify({ getHostIdentity: () => ({ ...PROVEN, prove: undefined }) })
    await send()
    expect(paths()).toEqual(['/v1/push/notify'])
    expect(Object.keys(bodyTo('/v1/push/notify'))).toEqual(['hostDeviceId', 'hostPublicKeyB64', 'hostLabel', 'events'])
    h.stop()
  })

  it('a new host key (or device id) proves again instead of reusing the old session', async () => {
    let id: PushHostIdentity = PROVEN
    const { h, send } = notify({ getHostIdentity: () => id })
    await send()
    const rotated = nacl.box.keyPair()
    id = { ...IDENTITY, hostPublicKeyB64: Buffer.from(rotated.publicKey).toString('base64'), prove: popProverFor(rotated) }
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-2')
    h.stop()
  })

  it('a challenge that never answers is aborted by the 8 s post timeout: that batch is dropped', async () => {
    route({
      challenge: (init) =>
        new Promise((_resolve, reject) => init.signal?.addEventListener('abort', () => reject(new Error('aborted'))))
    })
    const { h, send } = notify()
    await send() // the flush starts at 2 s and waits on the challenge
    await vi.advanceTimersByTimeAsync(7999)
    expect(callsTo('/v1/relay/challenge')[0][1].signal?.aborted).toBe(false)
    await vi.advanceTimersByTimeAsync(1)
    expect(callsTo('/v1/relay/challenge')[0][1].signal?.aborted).toBe(true)
    await vi.advanceTimersByTimeAsync(0)
    expect(callsTo('/v1/push/host-auth')).toHaveLength(0)
    expect(callsTo('/v1/push/notify')).toHaveLength(0)
    h.stop()
  })

  it('ONE 8 s timer covers the challenge and the host-auth post (a slow challenge leaves it the rest)', async () => {
    route({
      challenge: (init) => new Promise((resolve) => setTimeout(() => resolve(challengeOk(init)), 5000)),
      hostAuth: (init) =>
        new Promise((_resolve, reject) => init.signal?.addEventListener('abort', () => reject(new Error('aborted'))))
    })
    const { h, send } = notify()
    await send()
    await vi.advanceTimersByTimeAsync(5000) // the challenge answers; host-auth now hangs
    expect(callsTo('/v1/push/host-auth')).toHaveLength(1)
    const signal = callsTo('/v1/push/host-auth')[0][1].signal
    expect(signal).toBe(callsTo('/v1/relay/challenge')[0][1].signal)
    await vi.advanceTimersByTimeAsync(2999)
    expect(signal?.aborted).toBe(false)
    await vi.advanceTimersByTimeAsync(1) // 8 s after the challenge went out, not 8 s after host-auth
    expect(signal?.aborted).toBe(true)
    await vi.advanceTimersByTimeAsync(0)
    expect(callsTo('/v1/push/notify')).toHaveLength(0)
    h.stop()
  })

  it('failing proofs back off: a second failure in a row holds the next attempt for 5 s', async () => {
    // Each attempt is a /v1/relay/challenge, whose per-IP budget the relay host-token mint shares.
    let up = false
    route({ challenge: (init) => (up ? challengeOk(init) : bare(503)) })
    const { h, send } = notify()
    await send() // t=2 s: failure 1, the next batch may try again at once
    await send() // t=4 s: failure 2, nothing before t=9 s
    expect(callsTo('/v1/relay/challenge')).toHaveLength(2)
    up = true
    clock = 4000
    await send() // t=6 s: held — dropped without a request
    expect(callsTo('/v1/relay/challenge')).toHaveLength(2)
    expect(callsTo('/v1/push/notify')).toHaveLength(0)
    clock = 9000
    await send() // t=8 s on the timers, 9 s on the clock: tries, proves, sends
    expect(callsTo('/v1/relay/challenge')).toHaveLength(3)
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
    h.stop()
  })

  it('overlapping flushes share ONE proof in flight', async () => {
    let answer: (() => void) | null = null
    route({
      challenge: (init) =>
        new Promise((resolve) => {
          answer = () => resolve(challengeOk(init))
        })
    })
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getHostIdentity: () => PROVEN }))
    for (let i = 0; i < 12; i++) em.emit(iev({ nodeId: `m${i}`, title: `t${i}` }))
    await vi.advanceTimersByTimeAsync(2000) // flush A (10 events) waits on the challenge
    await vi.advanceTimersByTimeAsync(2000) // flush B (2 events) starts while A still waits
    expect(callsTo('/v1/relay/challenge')).toHaveLength(1)
    answer!()
    await vi.advanceTimersByTimeAsync(0)
    expect(callsTo('/v1/relay/challenge')).toHaveLength(1)
    expect(callsTo('/v1/push/host-auth')).toHaveLength(1)
    expect(callsTo('/v1/push/notify').map((c) => JSON.parse(c[1].body).hostAuth)).toEqual(['HA-1', 'HA-1'])
    h.stop()
  })

  it('a backward wall-clock step never stretches the proof backoff: a healthy backend proves on the next call', async () => {
    // The hold is an absolute wall-clock time. A clock stepped back a day would otherwise keep
    // host-mode push held for that whole day; a hold farther out than the longest step is a clock
    // step, never a backoff we set.
    let up = false
    route({ challenge: (init) => (up ? challengeOk(init) : bare(503)) })
    const { h, send } = notify()
    await send() // failure 1 (clock 0): the next attempt may go at once
    await send() // failure 2: held until 5 s
    clock = 5000
    await send() // failure 3: held until 20 s
    clock = 20_000
    await send() // failure 4: held until 80 s, the longest step
    expect(callsTo('/v1/relay/challenge')).toHaveLength(4)
    up = true
    await send() // same clock: a hold exactly one longest step out is honoured
    expect(callsTo('/v1/relay/challenge')).toHaveLength(4)
    expect(callsTo('/v1/push/notify')).toHaveLength(0)
    clock = 20_000 - 24 * 60 * MIN // the wall clock steps back a day
    await send()
    expect(callsTo('/v1/relay/challenge')).toHaveLength(5)
    expect(callsTo('/v1/push/notify')).toHaveLength(1)
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
    h.stop()
  })

  it.each<[string, { challenge?: Route }, string | undefined, string | undefined]>([
    ['session', {}, 'HA-1', 'HA-2'],
    ['old-backend verdict', { challenge: () => bare(404) }, undefined, undefined]
  ])(
    'a backward wall-clock step expires a cached %s: the next get() proves again',
    async (_label, r, first, second) => {
      // A negative age is no evidence of freshness. Read as "fresh", a clock stepped back an hour kept
      // the same session for that hour PLUS the 10 minutes, past the server's 15-minute TTL.
      route(r)
      const cache = createHostAuthCache({
        apiBase: 'https://api.nodeterm.dev',
        fetchImpl: fetchMock as unknown as typeof fetch,
        now: () => clock
      })
      clock = 60 * MIN
      await expect(cache.get(PROVEN)).resolves.toBe(first)
      expect(cache.onFile(PROVEN)).toBe(true)
      clock = 0 // the wall clock steps back an hour
      expect(cache.onFile(PROVEN)).toBe(false)
      await expect(cache.get(PROVEN)).resolves.toBe(second)
      expect(callsTo('/v1/relay/challenge')).toHaveLength(2)
    }
  )

  it('a cached legacy verdict refused by a host latched elsewhere re-proves and re-posts in the SAME batch', async () => {
    // The backend predated the proof when this sender asked, so it holds "legacy" for 10 minutes.
    // Meanwhile the host latched through another path (the standing host's proven mint, or the
    // other push stream), so the backend now refuses its unproven post (403 pop_required — judged by
    // status alone: `bare` throws if the body is read). Re-proving at once keeps the batch.
    let predates = true
    let latched = false
    route({
      challenge: (init) => (predates ? bare(404) : challengeOk(init)),
      notify: (init) => (latched && !JSON.parse(init.body).hostAuth ? bare(403) : bare(200))
    })
    const { h, send } = notify()
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])
    predates = false
    latched = true
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/push/notify', '/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    const [first, again] = callsTo('/v1/push/notify').map((c) => JSON.parse(c[1].body))
    expect(first).not.toHaveProperty('hostAuth')
    expect(again).toEqual({ ...first, hostAuth: 'HA-1' })
    // The next batch rides the new session: no second proof.
    fetchMock.mockClear()
    clock = 12_000
    await send()
    expect(paths()).toEqual(['/v1/push/notify'])
    expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
    h.stop()
  })

  it('the re-post goes out ONCE: a refused re-post is not retried (never a loop)', async () => {
    let predates = true
    route({
      challenge: (init) => (predates ? bare(404) : challengeOk(init)),
      notify: (init) =>
        predates ? bare(200) : JSON.parse(init.body).hostAuth ? json(403, { error: 'pop_invalid' }) : bare(403)
    })
    const { h, send } = notify()
    await send()
    predates = false
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/push/notify', '/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    // The re-post's pop_invalid clears the session as any proven post's does: the next batch
    // proves again, and a proven post's refusal is never re-posted.
    fetchMock.mockClear()
    clock = 12_000
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])
    h.stop()
  })

  it('a re-proof that fails drops the batch: no unproven re-post', async () => {
    let predates = true
    route({
      challenge: (init) => (predates ? bare(404) : bare(503)),
      notify: (init) => (predates || JSON.parse(init.body).hostAuth ? bare(200) : bare(403))
    })
    const { h, send } = notify()
    await send()
    predates = false
    fetchMock.mockClear()
    clock = 6000
    await send()
    expect(paths()).toEqual(['/v1/push/notify', '/v1/relay/challenge'])
    h.stop()
  })

  it('an old backend that refuses every host notify (403 forbidden) costs challenge + notify per batch, never a third request', async () => {
    // The verdict each batch posts under was asked for in that same batch, so a 403 is no sign the
    // host latched since: nothing is re-asked, and the batch stays at two requests. That is one more
    // than before the proof existed (notify alone), because each refused post forgets the verdict.
    route({ challenge: () => bare(404), notify: () => bare(403) })
    const { h, send } = notify()
    for (let i = 1; i <= 3; i++) {
      fetchMock.mockClear()
      clock = i * 6000
      await send()
      expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])
    }
    h.stop()
  })

  it('a cached legacy verdict refused while the backend still predates the proof: one re-ask, no re-post', async () => {
    let n = 0
    route({ challenge: () => bare(404), notify: () => (++n === 1 ? bare(200) : bare(403)) })
    const { h, send } = notify()
    await send()
    expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])
    // The re-ask caches the verdict again, so each later batch is the notify plus one challenge:
    // the two requests a batch cost before, in the other order.
    for (let i = 1; i <= 2; i++) {
      fetchMock.mockClear()
      clock = i * 6000
      await send()
      expect(paths()).toEqual(['/v1/push/notify', '/v1/relay/challenge'])
    }
    h.stop()
  })

  it.each(['challenge', 'host-auth'] as const)(
    'a %s answer that throws when read: get() resolves drop (never rejects) and backs off like any failure',
    async (leg) => {
      let fail = true
      // `bare` has no json(): reading it throws inside the proof.
      const broken = (ok: Route): Route => (init) => (fail ? bare(200) : ok(init))
      route(leg === 'challenge' ? { challenge: broken(challengeOk) } : { hostAuth: broken(hostAuthOk) })
      const cache = createHostAuthCache({
        apiBase: 'https://api.nodeterm.dev',
        fetchImpl: fetchMock as unknown as typeof fetch,
        now: () => clock
      })
      await expect(cache.get(PROVEN)).resolves.toBe('drop') // failure 1: the next may go at once
      await expect(cache.get(PROVEN)).resolves.toBe('drop') // failure 2: nothing before 5 s
      fail = false
      const asked = callsTo('/v1/relay/challenge').length
      await expect(cache.get(PROVEN)).resolves.toBe('drop') // held: no request
      expect(callsTo('/v1/relay/challenge')).toHaveLength(asked)
      clock = 5000
      await expect(cache.get(PROVEN)).resolves.toBe('HA-1')
    }
  )

  it('a proof that throws resolves drop for EVERY caller sharing it', async () => {
    let answer: (() => void) | null = null
    route({
      hostAuth: () =>
        new Promise((resolve) => {
          answer = () => resolve(bare(200)) // no json(): reading it throws
        })
    })
    const cache = createHostAuthCache({
      apiBase: 'https://api.nodeterm.dev',
      fetchImpl: fetchMock as unknown as typeof fetch,
      now: () => clock
    })
    const first = cache.get(PROVEN)
    const joined = cache.get(PROVEN)
    await vi.advanceTimersByTimeAsync(0)
    expect(callsTo('/v1/push/host-auth')).toHaveLength(1)
    answer!()
    await expect(Promise.all([first, joined])).resolves.toEqual(['drop', 'drop'])
  })

  it('a throwing proof inside a flush drops only that batch: the flush resolves', async () => {
    route({ hostAuth: () => bare(200) })
    const em = makeEmitter()
    const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getHostIdentity: () => PROVEN }))
    em.emit(iev({ nodeId: 'x', title: 'x' }))
    await expect(h._flushNow()).resolves.toBeUndefined()
    expect(callsTo('/v1/push/host-auth')).toHaveLength(1)
    expect(callsTo('/v1/push/notify')).toHaveLength(0)
    h.stop()
  })

  describe('live-update', () => {
    function live(): { h: LiveUpdateHandle; edge: (nodeId: string) => Promise<void> } {
      const st = emitter<NodeStateChange>()
      const h = createLiveUpdatePush({
        subscribeStateChange: st.subscribe,
        subscribeNowChange: () => () => {},
        getHostIdentity: () => PROVEN,
        mobilePushEnabled: () => true,
        mobileLiveActivities: () => true,
        isPackaged: () => true,
        env: {},
        fetchImpl: fetchMock as unknown as typeof fetch,
        now: () => clock,
        batchWindowMs: 1000
      })
      return {
        h,
        async edge(nodeId) {
          st.emit({ nodeId, event: 'start', state: 'working', ts: clock })
          await vi.advanceTimersByTimeAsync(1000)
        }
      }
    }

    it('proves once and carries the cached session on every post', async () => {
      const { h, edge } = live()
      await edge('a')
      expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/live-update'])
      expect(bodyTo('/v1/push/live-update')).toMatchObject({ hostPublicKeyB64: PUB, hostAuth: 'HA-1' })
      fetchMock.mockClear()
      clock = 9 * MIN
      await edge('b')
      expect(paths()).toEqual(['/v1/push/live-update'])
      expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-1')
      h.stop()
    })

    it('a live-update answered 403 pop_invalid clears the session; a transient challenge drops the batch', async () => {
      let n = 0
      let challengeUp = true
      route({
        challenge: (init) => (challengeUp ? challengeOk(init) : bare(503)),
        live: () => (++n === 1 ? json(403, { error: 'pop_invalid' }) : bare(200))
      })
      const { h, edge } = live()
      await edge('a')
      challengeUp = false
      fetchMock.mockClear()
      await edge('b') // must prove again, cannot, and so sends nothing
      expect(paths()).toEqual(['/v1/relay/challenge'])
      challengeUp = true
      fetchMock.mockClear()
      await edge('c')
      expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/live-update'])
      expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-2')
      h.stop()
    })

    it('notify proving latches the host; live-update\'s cached legacy verdict re-proves in the same batch', async () => {
      // "Latched elsewhere" through the other push stream: each stream caches its own verdict.
      let predates = true
      let latched = false
      const refuseUnproven: Route = (init) => (latched && !JSON.parse(init.body).hostAuth ? bare(403) : bare(200))
      route({
        challenge: (init) => (predates ? bare(404) : challengeOk(init)),
        hostAuth: (init) => {
          latched = true
          return hostAuthOk(init)
        },
        notify: refuseUnproven,
        live: refuseUnproven
      })
      const n = notify()
      const l = live()
      await n.send() // notify caches "legacy" at 0
      clock = 5 * MIN
      await l.edge('a') // live-update caches "legacy" at 5 min
      predates = false
      clock = 10 * MIN
      await n.send() // notify's verdict has expired: it proves, and the backend latches the host
      expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
      fetchMock.mockClear()
      await l.edge('b') // live-update's 5-minute-old legacy verdict is refused
      expect(paths()).toEqual([
        '/v1/push/live-update',
        '/v1/relay/challenge',
        '/v1/push/host-auth',
        '/v1/push/live-update'
      ])
      expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-2')
      n.h.stop()
      l.h.stop()
    })

    it('its session is its own: notify proving does not stand in for live-update', async () => {
      const n = notify()
      const l = live()
      await n.send()
      await l.edge('a')
      expect(callsTo('/v1/push/host-auth')).toHaveLength(2)
      expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')
      expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-2')
      n.h.stop()
      l.h.stop()
    })
  })
})