Skip to content

The agent that grows with you

37.4 KB
Raw Blame
import path from 'node:path'

import { expect, test, vi } from 'vitest'

import { createLocalGatewayDials, ensureLocalGateway, nativeGrantRoute, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'
import { shortSocketTmpDir } from './local-gateway.test-helpers'

test('the ensure client inherits the caller-scrubbed parent env, not the raw Desktop env', async () => {
  // #68367: a sibling profile's `gateway ensure` must not see the launch profile's dotenv
  // credentials. The parent env passed in IS the environment; only HERMES_HOME and the
  // backend's own entries are layered on top.
  const printEnv = ['-e', 'process.stdout.write(JSON.stringify({ leak: process.env.LEAK ?? null, home: process.env.HERMES_HOME, own: process.env.OWN }))']

  const result = await runGatewayEnsure(
    { command: process.execPath, args: printEnv, env: { OWN: '1' }, shell: false },
    process.cwd(),
    '/home/x/.hermes',
    { PATH: process.env.PATH ?? '', OWN: '0' }
  )

  expect(JSON.parse(result.stdout)).toEqual({ leak: null, home: '/home/x/.hermes', own: '1' })
})

test('a shell-delegated ensure quotes a spaced Windows install path (#74064)', async () => {
  // cmd.exe cuts an unquoted `C:\Users\John Doe\...\hermes.cmd` at the first space.
  const spawned: string[] = []
  vi.resetModules()
  vi.doMock('node:child_process', () => ({
    spawn: (command: string) => {
      spawned.push(command)
      throw new Error('stop after spawn')
    }
  }))
  const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
  Object.defineProperty(process, 'platform', { value: 'win32' })

  try {
    const { runGatewayEnsure: ensure } = await import('./local-gateway')
    const command = 'C:\\Users\\John Doe\\AppData\\Local\\hermes\\hermes.cmd'
    await expect(ensure({ command, args: ['gateway', 'ensure'], env: {}, shell: true }, 'C:\\', 'C:\\h')).rejects.toThrow('stop after spawn')
    await expect(ensure({ command, args: [], env: {}, shell: false }, 'C:\\', 'C:\\h')).rejects.toThrow('stop after spawn')
    expect(spawned).toEqual([`"${command}"`, command])
  } finally {
    Object.defineProperty(process, 'platform', platform)
    vi.doUnmock('node:child_process')
    vi.resetModules()
  }
})

test('canonical ensure cannot cross a rejected update or profile lifecycle gate', async () => {
  let ran = false
  await expect(ensureLocalGateway(async () => { ran = true;

 return { code: 0, stdout: '{}' } }, async () => {
    throw new Error('profile retired during update')
  })).rejects.toThrow('profile retired during update')
  expect(ran).toBe(false)
})

test.skipIf(process.platform === 'win32').each([0o700, 0o750, 0o701])('native HTTP respects supported home mode %o and mints fresh purpose-bound grants', async mode => {
  const fs = await import('node:fs/promises')
  const path = await import('node:path')
  const net = await import('node:net')
  const { nativeGatewayHttpHeaders } = await import('./local-gateway')
  // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises
  // profile_id, so the endpoint must carry the realpath or identities never match.
  const home = await shortSocketTmpDir('desktop-http-')
  await fs.chmod(home, mode)
  const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
  const requests: any[] = []

  const server = net.createServer(socket => socket.once('data', chunk => {
    const request = JSON.parse(chunk.toString())
    requests.push(request)
    socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: request.params?.profile_id ?? home, instance_id: 'owner', runtime_protocol: 1, ticket: `grant-${requests.length}` } }) + '\n')
  }))

  await new Promise<void>(resolve => server.listen(path.join(home, 'gateway.sock'), resolve))
  await fs.chmod(path.join(home, 'gateway.sock'), 0o600)

  try {
    const descriptor = { gatewayEndpoint: endpoint, baseUrl: endpoint.api_origin }
    const a = await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + '/api/config')
    const b = await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + '/api/config')
    expect(a).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-1' })
    expect(b).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-2' })
    expect(requests.map(r => r.params)).toEqual([1, 2].map(() => ({ profile_id: home, instance_id: 'owner', purpose: 'native-http' })))
    await expect(nativeGatewayHttpHeaders(descriptor, 'http://127.0.0.1:4567/api/config')).rejects.toThrow('origin')
    expect(requests).toHaveLength(2)
    // The shared-primary WS socket alone asks for a host-scoped grant (sibling `profile` routing).
    const { mintLocalGatewayTicket } = await import('./local-gateway')
    await mintLocalGatewayTicket(endpoint)
    expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose: 'interactive', scope: 'host' })

    for (const [route, method, purpose] of [
      ['/api/profiles', 'POST', 'native-profile-create'],
      ['/api/profiles?unused=1', 'post', 'native-profile-create'],
      ['/api/profiles', 'GET', 'native-http'],
      ['/api/profiles/import', 'POST', 'native-http'],
      ['/api/config', 'POST', 'native-http'],
      // Rename/delete of the launch profile ride the registry grant (#140345); its SOUL stays native-http.
      ['/api/profiles/default', 'PATCH', 'native-profile-registry'],
      ['/api/profiles/default', 'delete', 'native-profile-registry'],
      ['/api/profiles/default/soul', 'PUT', 'native-http'],
      // The collection routes of these names stay on the endpoint's own profile.
      ['/api/profiles/active', 'GET', 'native-http'],
      ['/api/profiles/active', 'POST', 'native-http'],
      ['/api/profiles/sessions?profile=default', 'GET', 'native-http']
    ]) {
      await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + route, home, method)
      expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose })
    }

    // A profile NAMED active/import/sessions (valid names): its PATCH/DELETE is that profile's own
    // rename/delete (the collection routes are GET/POST only), on the registry grant for its home.
    for (const [name, method] of [['active', 'PATCH'], ['import', 'DELETE'], ['sessions', 'DELETE']]) {
      await fs.mkdir(path.join(home, 'profiles', name), { recursive: true, mode: 0o700 })
      await nativeGatewayHttpHeaders(descriptor, `${endpoint.api_origin}/api/profiles/${name}`, home, method)
      expect(requests.at(-1).params).toEqual({ profile_id: await fs.realpath(path.join(home, 'profiles', name)),
        instance_id: 'owner', purpose: 'native-profile-registry' })
    }
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
    await fs.rm(home, { recursive: true, force: true })
  }
})

test.skipIf(process.platform === 'win32')('a served secondary mints its ticket through the multiplexer control socket, bound to its own profile', async () => {
  const fs = await import('node:fs/promises')
  const path = await import('node:path')
  const net = await import('node:net')
  const { mintLocalGatewayTicket } = await import('./local-gateway')
  const root = await shortSocketTmpDir('desktop-mux-')
  const secondary = path.join(root, 'profiles', 'cold')
  await fs.mkdir(secondary, { recursive: true, mode: 0o700 })
  await fs.chmod(root, 0o700)
  // Only the multiplexer root has a control socket; profiles/cold has none (it is served).
  const requests: any[] = []

  const server = net.createServer(socket => socket.once('data', chunk => {
    requests.push(JSON.parse(chunk.toString()).params)
    socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: secondary, instance_id: 'mux', runtime_protocol: 1, ticket: 'served-grant' } }) + '\n')
  }))

  await new Promise<void>(resolve => server.listen(path.join(root, 'gateway.sock'), resolve))
  await fs.chmod(path.join(root, 'gateway.sock'), 0o600)
  const endpoint = { profile_id: secondary, instance_id: 'mux', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }

  try {
    // Without control_home the secondary's own (absent) socket is probed: stale owner, not a grant.
    await expect(mintLocalGatewayTicket(endpoint, 'native-http')).rejects.toThrow('Gateway ticket control socket missing')
    expect(await mintLocalGatewayTicket({ ...endpoint, control_home: root }, 'native-http')).toBe('served-grant')
    expect(requests).toEqual([{ profile_id: secondary, instance_id: 'mux', purpose: 'native-http' }])
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
    await fs.rm(root, { recursive: true, force: true })
  }
})

test('ensure consumes structured readiness without acquiring a child owner', async () => {
  const endpoint = { profile_id: '/private/profile', instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
  const connection = await ensureLocalGateway(async () => ({ code: 0, stdout: JSON.stringify({ state: 'ready', endpoint }) }))
  expect(connection.baseUrl).toBe(endpoint.api_origin)
  expect(connection.gatewayEndpoint).toEqual(endpoint)
  expect(connection).not.toHaveProperty('process')
  expect(connection.token).toBe('')
  await expect(ensureLocalGateway(async () => ({ code: 5, stdout: JSON.stringify({ state: 'starting', reason_code: 'deadline' }) }))).rejects.toThrow('starting')
})

test('a restart-wait owner is attached to answer a parked prompt; a plain drain stays refused (#139041)', async () => {
  const endpoint = { profile_id: '/private/profile', instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none', code_sha: 'old' }
  const restartStale = vi.fn(async () => ({ done: Promise.resolve() }))
  const wait = { code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'restart_wait', endpoint, client_code_sha: 'new' }) }
  const connection = await ensureLocalGateway(async () => wait, undefined, restartStale)
  expect(connection.gatewayEndpoint).toEqual(endpoint)
  expect(restartStale).not.toHaveBeenCalled() // already restarting: never a second restart
  await expect(ensureLocalGateway(async () => ({ code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'update_paused', endpoint: null }) }))).rejects.toThrow('Gateway draining (update_paused)')
})

test('a stale owner this window restarts is attached in its restart wait before the restart finishes (#139041)', async () => {
  // `hermes gateway restart` waits for the old owner to exit; a turn parked on approval/clarify
  // there waits for an answer only this window can give. Awaiting the restart first deadlocked both.
  const { createStaleGatewayRestarter } = await import('./local-gateway')
  const endpoint = { profile_id: '/h', instance_id: 'old', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none', code_sha: 'old' }
  let finishRestart = () => {}
  const restarted: string[] = []
  const restartStale = createStaleGatewayRestarter(owner => { restarted.push(owner)

 return new Promise<void>(resolve => { finishRestart = resolve }) }, () => undefined)
  const answers = [
    { code: 0, stdout: JSON.stringify({ state: 'ready', endpoint, client_code_sha: 'new' }) },
    { code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'restart_wait', endpoint, client_code_sha: 'new' }) }
  ]
  const attached = ensureLocalGateway(async () => answers.shift()!, undefined, restartStale)
  const outcome = await Promise.race([attached, new Promise(resolve => setTimeout(() => resolve('blocked on the restart'), 500))])
  finishRestart()
  expect(outcome).toMatchObject({ gatewayEndpoint: { instance_id: 'old' } })
  expect(restarted).toEqual(['default'])
})

test('an ensure child that never reached the protocol boundary is diagnosed from stderr, not as a JSON parse error', async () => {
  // `main`'s hermes has no `gateway ensure` subcommand: argparse usage on stderr, nothing on stdout.
  const legacy = { code: 2, stdout: '', stderr: "usage: hermes gateway [-h] ...\nhermes gateway: 'ensure' is not a `hermes gateway` command.\nRun `hermes gateway --help` to see all commands.\n" }
  await expect(ensureLocalGateway(async () => legacy)).rejects.toThrow(/produced no result \(exit 2\): Run `hermes gateway --help`/)
  // A missing profile: the CLI exits 1 before the ensure command runs.
  await expect(ensureLocalGateway(async () => ({ code: 1, stdout: '', stderr: "Error: Profile 'gone' does not exist.\n" }))).rejects.toThrow(/exit 1\): Error: Profile 'gone' does not exist\./)
  // A protocol outcome is never re-diagnosed: `incompatible` stays the gateway's own verdict.
  await expect(ensureLocalGateway(async () => ({ code: 3, stdout: '{"endpoint":null,"reason_code":"runtime_protocol","state":"incompatible"}', stderr: 'noise' }))).rejects.toThrow('Gateway incompatible (runtime_protocol)')
  await expect(ensureLocalGateway(async () => ({ code: 0, stdout: '', stderr: '' }))).rejects.toThrow(/produced no result \(exit 0\)\. Update Hermes/)
})

test('private dial credential is one-use and bound to the requesting native window', () => {
  const dials = createLocalGatewayDials()
  const dial = new URL(dials.prepare('http://127.0.0.1:1234', 'private-ticket', 7))
  expect(dial.searchParams.get('ticket')).toBe('private-ticket')
  dial.searchParams.delete('ticket')
  const url = dial.toString()
  expect(url).not.toContain('private-ticket')
  const details = { url, webContentsId: 8, resourceType: 'webSocket', requestHeaders: { Origin: 'http://renderer', 'Sec-WebSocket-Protocol': 'hermes-gateway-v1, hermes-gateway-ticket.private-ticket' } }
  expect(dials.headers(details)).toBeNull()
  // The dial may cross a loopback proxy that rewrites host:port but keeps the nonce.
  const proxied = url.replace('127.0.0.1:1234', '127.0.0.1:4321')
  const headers = dials.headers({ ...details, url: proxied, webContentsId: 7 })!
  expect(headers).not.toHaveProperty('Origin')
  expect(headers['Sec-WebSocket-Protocol']).toBe('hermes-gateway-v1, hermes-gateway-ticket.private-ticket')
  expect(dials.headers({ ...details, webContentsId: 7 })).toBeNull()
})

test('a voice socket dialed on its own /api/ws reservation drops Origin; other paths do not', () => {
  const dial = (path: string, dials = createLocalGatewayDials()) => {
    const url = new URL(dials.prepare('http://127.0.0.1:1234', 'voice-ticket', 7))
    url.searchParams.delete('ticket')
    url.pathname = path

    return dials.headers({ url: url.toString(), webContentsId: 7, resourceType: 'webSocket', requestHeaders: { Origin: 'http://renderer' } })
  }

  expect(dial('/api/audio/speak-stream')).toEqual({})
  expect(dial('/api/audio/transcribe-stream')).toEqual({})
  expect(dial('/api/pty')).toBeNull()
})

test('a dial against a replaced local gateway forgets the cached endpoint once and re-ensures', async () => {
  const { redialLocalGateway } = await import('./local-gateway')
  const endpoints = [{ instance_id: 'dead' }, { instance_id: 'alive' }]
  const forgotten: string[] = []
  let ensures = 0

  const result = await redialLocalGateway({
    ensure: async () => endpoints[Math.min(ensures++, 1)],
    forget: async () => { forgotten.push('primary') },
    use: async endpoint => {
      if (endpoint.instance_id === 'dead') {throw new Error('Gateway ticket bootstrap failed')}

      return `ticket-for-${endpoint.instance_id}`
    }
  })

  expect(result).toBe('ticket-for-alive')
  expect(forgotten).toEqual(['primary'])
  expect(ensures).toBe(2)
})

test('a redial whose re-ensure comes back without a gateway endpoint names that, not a TypeError', async () => {
  const { localGatewayDial } = await import('./local-gateway')
  const endpoint = { profile_id: '/h', control_home: null, instance_id: 'dead', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
  const mint = vi.fn(async () => { throw new Error('Gateway ticket control socket missing') })
  const ensure = vi.fn()
    .mockResolvedValueOnce({ baseUrl: 'http://127.0.0.1:1234', gatewayEndpoint: endpoint })
    .mockResolvedValueOnce({ baseUrl: 'http://127.0.0.1:1234' })

  await expect(localGatewayDial({ ensure, forget: vi.fn(), launchHome: '/h', mint, prepare: () => 'unused', profile: '' }))
    .rejects.toThrow('Local gateway connection has no gateway endpoint')
  expect(mint).toHaveBeenCalledTimes(1)
})

test('a ready owner running other code than this Hermes is restarted once, then re-ensured', async () => {
  // After `hermes update` the live gateway still serves the old code and answers model calls
  // 503 "Restart required"; attaching to it on every dial pinned the user to it forever.
  const { createStaleGatewayRestarter } = await import('./local-gateway')
  const endpoint = { profile_id: '/h/profiles/w', control_home: '/h', instance_id: 'old', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none', code_sha: 'OLD' }
  const answers = [{ ...endpoint, code_sha: 'old' }, { ...endpoint, instance_id: 'new', code_sha: 'new' }, endpoint, endpoint]
  const restarted: string[] = []
  const restartStale = createStaleGatewayRestarter(async owner => { restarted.push(owner) }, () => undefined)
  const ensure = () => ensureLocalGateway(async () => ({ code: 0, stdout: JSON.stringify({ state: 'ready', endpoint: answers.shift(), client_code_sha: 'new' }) }), undefined, restartStale)

  expect((await ensure()).gatewayEndpoint.instance_id).toBe('new')
  // A served secondary is replaced through the multiplexer that owns its process, not `-p w`.
  expect(restarted).toEqual(['default'])
  // A restart that cannot move the owner (a unit pinned to another checkout) is not repeated per dial.
  expect((await ensure()).gatewayEndpoint.instance_id).toBe('old')
  expect(restarted).toEqual(['default'])
})

test('a dial that keeps failing after one re-ensure surfaces the error instead of looping', async () => {
  const { redialLocalGateway } = await import('./local-gateway')
  let ensures = 0
  let forgets = 0
  await expect(redialLocalGateway({
    ensure: async () => { ensures++;

 return { instance_id: 'still-dead' } },
    forget: async () => { forgets++ },
    use: async () => { throw new Error('Invalid gateway ticket response') }
  })).rejects.toThrow('Invalid gateway ticket response')
  expect(ensures).toBe(2)
  expect(forgets).toBe(1)
})

test.skipIf(process.platform === 'win32')('a stopped gateway that unlinked its control socket is a stale owner, not a raw filesystem error', async () => {
  const fs = await import('node:fs/promises')
  const path = await import('node:path')
  const net = await import('node:net')
  const { mintLocalGatewayTicket, redialLocalGateway } = await import('./local-gateway')
  // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises
  // profile_id, so the endpoint must carry the realpath or identities never match.
  const home = await shortSocketTmpDir('desktop-redial-')
  const socketPath = path.join(home, 'gateway.sock')
  const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }

  const serve = async (ticket: string) => {
    const server = net.createServer(socket => socket.once('data', () => {
      socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', runtime_protocol: 1, ticket } }) + '\n')
    }))

    await new Promise<void>(resolve => server.listen(socketPath, resolve))
    await fs.chmod(socketPath, 0o600)

    return server
  }

  const stop = async (server: ReturnType<typeof net.createServer>) => {
    await new Promise<void>(resolve => server.close(() => resolve()))
    await fs.rm(socketPath, { force: true })
  }

  let replacement: ReturnType<typeof net.createServer> | null = null
  const original = await serve('grant-original')

  try {
    expect(await mintLocalGatewayTicket(endpoint)).toBe('grant-original')
    await stop(original)

    let ensures = 0
    let forgets = 0

    const result = await redialLocalGateway({
      ensure: async () => {
        ensures += 1

        if (ensures === 2) {replacement = await serve('grant-replacement')}

        return endpoint
      },
      forget: () => { forgets += 1 },
      use: e => mintLocalGatewayTicket(e)
    })

    expect(result).toBe('grant-replacement')
    expect(forgets).toBe(1)
    expect(ensures).toBe(2)
  } finally {
    if (replacement) {await stop(replacement)}
    await fs.rm(home, { recursive: true, force: true })
  }
})

// The owner rewrites `gateway.sock.path` (O_TRUNC, then write) when it rebinds its fallback socket:
// a dial landing mid-rewrite, or on a pointer an earlier owner left, must re-ensure like any other
// stale owner instead of surfacing a raw error the renderer's reconnect backoff repeats forever.
test.skipIf(process.platform === 'win32')('a corrupt control pointer is a stale owner: the redial re-ensures and attaches to the republished socket', async () => {
  const crypto = await import('node:crypto')
  const fs = await import('node:fs/promises')
  const path = await import('node:path')
  const net = await import('node:net')
  const { isStaleLocalGatewayError, mintLocalGatewayTicket, redialLocalGateway } = await import('./local-gateway')
  const home = await shortSocketTmpDir('desktop-pointer-')
  const runtime = await shortSocketTmpDir('desktop-gw-')
  const hash = crypto.createHash('sha256').update(home).digest('hex').slice(0, 16)
  const socketPath = path.join(runtime, `hermes-gw-${hash}`, 'control.sock')
  const pointer = path.join(home, 'gateway.sock.path')
  const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
  await fs.mkdir(path.dirname(socketPath), { mode: 0o700 })

  const server = net.createServer(socket => socket.once('data', () => {
    socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', ticket: 'grant-republished' } }) + '\n')
  }))

  await new Promise<void>(resolve => server.listen(socketPath, resolve))
  await fs.chmod(socketPath, 0o600)
  await fs.writeFile(pointer, '', { mode: 0o600 })

  try {
    const failure = await mintLocalGatewayTicket(endpoint).catch(error => error)
    expect(failure.message).toBe('Invalid gateway control pointer')
    expect(isStaleLocalGatewayError(failure)).toBe(true)
    expect(isStaleLocalGatewayError(new Error('Noncanonical gateway profile'))).toBe(true)

    let ensures = 0
    let forgets = 0

    const ticket = await redialLocalGateway({
      ensure: async () => {
        ensures += 1

        if (ensures === 2) {await fs.writeFile(pointer, socketPath, { mode: 0o600 })}

        return endpoint
      },
      forget: () => { forgets += 1 },
      use: e => mintLocalGatewayTicket(e)
    })

    expect(ticket).toBe('grant-republished')
    expect([ensures, forgets]).toEqual([2, 1])
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
    await fs.rm(home, { recursive: true, force: true })
    await fs.rm(runtime, { recursive: true, force: true })
  }
})

test.skipIf(process.platform === 'win32')('a group-accessible control socket is refused as unsafe, and unrelated errors are never stale', async () => {
  const fs = await import('node:fs/promises')
  const path = await import('node:path')
  const net = await import('node:net')
  const { isStaleLocalGatewayError, mintLocalGatewayTicket } = await import('./local-gateway')
  // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises
  // profile_id, so the endpoint must carry the realpath or identities never match.
  const home = await shortSocketTmpDir('desktop-unsafe-')
  const socketPath = path.join(home, 'gateway.sock')
  const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
  const server = net.createServer(socket => socket.end())
  await new Promise<void>(resolve => server.listen(socketPath, resolve))
  await fs.chmod(socketPath, 0o660)

  try {
    const failure = await mintLocalGatewayTicket(endpoint).catch(error => error)
    expect(failure).toBeInstanceOf(Error)
    expect(failure.message).toBe(`Unsafe gateway control path: '${socketPath}' is accessible to other users (mode 660): run chmod go-rwx '${socketPath}'`)
    expect(isStaleLocalGatewayError(failure)).toBe(false)
    expect(isStaleLocalGatewayError(new Error('EACCES: permission denied'))).toBe(false)
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
    await fs.rm(home, { recursive: true, force: true })
  }
})

// R7: the profile home keeps the operator's mode (Python `home_mode_unsafe`: HERMES_HOME_MODE
// 0750/0701, a 0755 home); only write by another user can swap the socket. The socket stays 0600.
test.skipIf(process.platform === 'win32')('a supported home mode mints its ticket; a home others can write is refused', async () => {
  const fs = await import('node:fs/promises')
  const path = await import('node:path')
  const net = await import('node:net')
  const { mintLocalGatewayTicket } = await import('./local-gateway')
  const home = await shortSocketTmpDir('desktop-home-mode-')
  const socketPath = path.join(home, 'gateway.sock')
  const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }

  const server = net.createServer(socket => socket.once('data', () => {
    socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', ticket: 'grant' } }) + '\n')
  }))

  await new Promise<void>(resolve => server.listen(socketPath, resolve))
  await fs.chmod(socketPath, 0o600)

  try {
    for (const mode of [0o700, 0o755, 0o750, 0o701]) {
      await fs.chmod(home, mode)
      expect(await mintLocalGatewayTicket(endpoint)).toBe('grant')
    }

    for (const mode of [0o757, 0o703, 0o775]) {
      await fs.chmod(home, mode)
      // 0775 with no Python client configured: group-write Node cannot prove private is refused.
      await expect(mintLocalGatewayTicket(endpoint)).rejects.toThrow('Unsafe gateway control path')
    }
  } finally {
    await fs.chmod(home, 0o700)
    await new Promise<void>(resolve => server.close(() => resolve()))
    await fs.rm(home, { recursive: true, force: true })
  }
})

test('a ?profile= request on the shared host descriptor mints for the sibling profile home', () => {
  const endpoint = { profile_id: path.resolve('hermes-home'), instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: null }
  expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/sessions?profile=p2', path.resolve('hermes-home'))).toMatchObject({ profile_id: path.resolve('hermes-home', 'profiles', 'p2'), control_home: path.resolve('hermes-home') })
  expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/sessions?profile=default', path.resolve('hermes-home'))).toBe(endpoint)
  expect(routedGatewayEndpoint({ ...endpoint, profile_id: path.resolve('hermes-home', 'profiles', 'p2'), control_home: path.resolve('hermes-home') }, 'http://127.0.0.1:1/x?profile=default', path.resolve('hermes-home'))).toMatchObject({ profile_id: path.resolve('hermes-home') })
  expect(() => routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/x?profile=../evil', path.resolve('hermes-home'))).toThrow('Invalid profile route')
})

test('a profile SOUL route mints for the profile named in its path', () => {
  const endpoint = { profile_id: path.resolve('hermes-home'), instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: null }

  expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/p2/soul', path.resolve('hermes-home'))).toMatchObject({
    profile_id: path.resolve('hermes-home', 'profiles', 'p2'),
    control_home: path.resolve('hermes-home')
  })
})

// Every /api/profiles/<name>/* route the Profiles screen calls is checked against the path's
// profile (native_http._check_profile_scope); collection routes beneath it stay on their selector.
test('every named Profiles-screen route mints for its profile; collection routes do not', () => {
  const endpoint = { profile_id: path.resolve('hermes-home'), instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: null }
  const route = (p: string) => routedGatewayEndpoint(endpoint, `http://127.0.0.1:1${p}`, endpoint.profile_id).profile_id

  for (const p of ['/api/profiles/p2', '/api/profiles/p2/soul', '/api/profiles/p2/setup-command', '/api/profiles/p2/export']) {
    expect(route(p)).toBe(path.resolve('hermes-home', 'profiles', 'p2'))
  }

  expect(route('/api/profiles/default/soul')).toBe(endpoint.profile_id)

  for (const p of ['/api/profiles/active', '/api/profiles/import', '/api/profiles/projects/tree', '/api/profiles/sessions']) {
    expect(route(p)).toBe(endpoint.profile_id)
  }

  expect(route('/api/profiles/sessions?profile=p2')).toBe(path.resolve('hermes-home', 'profiles', 'p2'))
})

// A profile may be NAMED like a collection route: only the exact collection paths stay on their
// selector, so `/api/profiles/projects/soul` still mints for the `projects` profile.
test('a profile named like a collection route still gets its own ticket', () => {
  const endpoint = { profile_id: path.resolve('hermes-home'), instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: null }
  const route = (p: string) => routedGatewayEndpoint(endpoint, `http://127.0.0.1:1${p}`, endpoint.profile_id).profile_id

  for (const name of ['projects', 'sessions', 'active', 'import']) {
    expect(route(`/api/profiles/${name}/soul`)).toBe(path.resolve('hermes-home', 'profiles', name))
  }

  expect(route('/api/profiles/sessions/sidebar?recents_profile=p2')).toBe(path.resolve('hermes-home', 'profiles', 'p2'))
  expect(route('/api/profiles/sessions/pull-requests?profile=p2')).toBe(path.resolve('hermes-home', 'profiles', 'p2'))
})

// The batched sidebar names its owner in `recents_profile`; a grant for the window's own profile
// is refused there (profile_scope_mismatch) and the sidebar drops that profile's sessions.
test('a sidebar read mints for the profile its recents_profile names', () => {
  const endpoint = { profile_id: path.resolve('hermes-home', 'profiles', 'p2'), instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: path.resolve('hermes-home') }
  expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/sessions/sidebar?recents_profile=default&recents_limit=40', path.resolve('hermes-home'))).toMatchObject({ profile_id: path.resolve('hermes-home') })
  expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/sessions/sidebar?recents_profile=p2', path.resolve('hermes-home'))).toBe(endpoint)
  // `profile` is not the sidebar's selector.
  expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/sessions/sidebar?profile=default&recents_profile=p2', path.resolve('hermes-home'))).toBe(endpoint)
})

// A native gateway grant is minted only by main's shared transport (fetchJsonForBackend), which
// also carries the descriptor's configured headers; a call site that hands fetchJson a
// gatewayDescriptor itself silently drops them. Source guard over the one module that issues them.
test('main issues native-gateway REST calls only through the shared descriptor transport', async () => {
  const fs = await import('node:fs/promises')
  const source = await fs.readFile(new URL('./main.ts', import.meta.url), 'utf8')
  const transport = source.indexOf('async function fetchJsonForBackend(')
  const transportEnd = source.indexOf('\n}\n', transport)
  const outside = source.slice(0, transport) + source.slice(transportEnd)

  expect(transport).toBeGreaterThan(0)
  expect(source.slice(transport, transportEnd)).toContain('headers: descriptor.headers')
  expect(outside.match(/fetchJson\([^)]*\{[^}]*gatewayDescriptor\b/g) ?? []).toEqual([])
})

// A group-writable home (umask-002 user-private-group default) is decided by the runtime's own
// home policy, which Node cannot evaluate: the mint goes through the Python ticket client, and a
// refusal there names the fix instead of failing as a stale gateway.
test.skipIf(process.platform === 'win32')('a group-writable home mints through the Python policy; a shared group names the fix', async () => {
  const fs = await import('node:fs/promises')
  const os = await import('node:os')
  const path = await import('node:path')
  const { configurePythonGatewayTicketClient, isStaleLocalGatewayError, mintLocalGatewayTicket } = await import('./local-gateway')
  const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-group-home-')))
  const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
  const calls: string[] = []
  let verdict: 'grant' | 'shared' = 'grant'

  configurePythonGatewayTicketClient(async (ep, purpose) => {
    calls.push(`${ep.profile_id}:${purpose}`)

    if (verdict === 'shared') {throw Object.assign(new Error('Gateway ticket bootstrap failed'), { reason: 'unsafe_control_permissions' })}

    return 'python-grant'
  })

  try {
    await fs.chmod(home, 0o775)
    expect(await mintLocalGatewayTicket(endpoint, 'native-http')).toBe('python-grant')
    expect(calls).toEqual([`${home}:native-http`])

    verdict = 'shared'
    const failure = await mintLocalGatewayTicket(endpoint).catch(error => error)
    expect(failure.message).toBe(`Profile home is writable by a group other accounts share: run chmod g-w '${home}'`)
    expect(isStaleLocalGatewayError(failure)).toBe(false)

    await fs.chmod(home, 0o757)
    await expect(mintLocalGatewayTicket(endpoint)).rejects.toThrow('Unsafe gateway control path')
    expect(calls).toHaveLength(2)
  } finally {
    configurePythonGatewayTicketClient(undefined as never)
    await fs.chmod(home, 0o700)
    await fs.rm(home, { recursive: true, force: true })
  }
})

test('a session write that names its owner only in the body gets a grant for that profile', () => {
  const url = 'http://127.0.0.1:1/api/sessions/s1'
  expect(nativeGrantRoute(url, { hidden: true, profile: 'p2' })).toBe('p2')
  // The URL's own selector wins; the gateway refuses a body that disagrees with it.
  expect(nativeGrantRoute(url + '?profile=p3', { profile: 'p2' })).toBe(url + '?profile=p3')
  // The profile NAMED `active` is the ticket's profile for its own rename; the collection GET is not.
  expect(nativeGrantRoute('http://127.0.0.1:1/api/profiles/active', { profile: 'p2' }, 'PATCH')).toBe('http://127.0.0.1:1/api/profiles/active')
  expect(nativeGrantRoute('http://127.0.0.1:1/api/profiles/active', { profile: 'p2' }, 'GET')).toBe('p2')
  expect(nativeGrantRoute('http://127.0.0.1:1/api/profiles/sessions/sidebar?recents_profile=p3', { profile: 'p2' })).toContain('recents_profile=p3')

  for (const body of [undefined, null, {}, { profile: '' }, { profile: 7 }, [{ profile: 'p2' }]]) {
    expect(nativeGrantRoute(url, body)).toBe(url)
  }
})

test('an ensure refusal names its remedy instead of only a status pointer', async () => {
  // A gateway another install owns is refused, not replaced; ensure says what to do in `detail`.
  const detail = "another Hermes install's gateway owns this profile; stop it there: hermes gateway stop"

  await expect(ensureLocalGateway(async () => ({
    code: 3, stdout: JSON.stringify({ state: 'incompatible', reason_code: 'runtime_protocol', detail, endpoint: null })
  }))).rejects.toThrow(`Gateway incompatible (runtime_protocol). ${detail}. Use hermes gateway status for recovery.`)
})

test('an elevated or other-session gateway is named with its remedy, not as authorization (#139845, #140252)', async () => {
  const cases = [
    ['gateway_elevated', 'The running gateway (PID 23460) was started as administrator, so this non-elevated app cannot reach it. Stop it from an administrator prompt (hermes gateway stop), then start Hermes without elevation'],
    ['gateway_other_session', 'The running gateway (PID 23460) runs in another Windows logon session (session 0, e.g. a boot-time scheduled task), so this app cannot reach it. Stop it (hermes gateway stop from an administrator prompt) and let only one auto-start task launch the gateway']
  ]

  for (const [reason_code, detail] of cases) {
    const failure = ensureLocalGateway(async () => ({
      code: 4, stdout: JSON.stringify({ state: 'inaccessible', reason_code, detail, endpoint: null })
    }))

    await expect(failure).rejects.toThrow(`Gateway inaccessible (${reason_code}). ${detail}.`)
    await expect(failure).rejects.not.toThrow('authorization')
  }
})

test('an update-paused ensure refusal points to the restart that completes its tail', async () => {
  await expect(ensureLocalGateway(async () => ({
    code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'update_paused', endpoint: null })
  }))).rejects.toThrow('Gateway draining (update_paused). Use hermes gateway restart for recovery.')
})