Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
36.0 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '../httpClient.js'
import { RpcProxyClient, SANDBOX_UI_MINT_TIMEOUT_MS } from '../rpcProxyClient.js'

// Mock the config module so default clients use a fixed persisted base URL.
vi.mock('../config.js', () => ({
  config: {
    rpcProxyBaseUrl: 'http://proxy',
    externalRestApiBaseUrl: 'http://rest',
    enableDevLoginUi: false,
    requestTimeoutMs: 60000,
    appName: 'test',
  },
}))

describe('RpcProxyClient endpoint provider', () => {
  it('uses its supplied endpoint provider instead of the persisted configuration', async () => {
    const client = new RpcProxyClient(() => 'https://effective-rpc.example.test/')
    const fetchMock = vi.fn().mockResolvedValue(
      new Response(JSON.stringify({ status: 'ok' }), {
        status: 200,
        headers: { 'content-type': 'application/json' },
      })
    )
    vi.stubGlobal('fetch', fetchMock)

    await expect(client.health()).resolves.toEqual({ status: 'ok' })

    expect(fetchMock).toHaveBeenCalledWith(
      'https://effective-rpc.example.test/health',
      expect.any(Object)
    )
  })

  it('uses its supplied endpoint for a Desktop session exchange', async () => {
    const client = new RpcProxyClient(() => 'https://effective-rpc.example.test/')
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      json: async () => ({ ok: true, hostRef: 'chatllm' }),
      headers: {
        get: (name: string) =>
          name === 'set-cookie'
            ? 'clerum_desktop_session=effective-cookie; Path=/api/v1/desktop/chatllm'
            : null,
      },
    })
    vi.stubGlobal('fetch', fetchMock)

    await expect(client.postDesktopSession('rpc-token', 'chatllm')).resolves.toEqual({
      ok: true,
      hostRef: 'chatllm',
      setCookie: ['clerum_desktop_session=effective-cookie; Path=/api/v1/desktop/chatllm'],
    })

    expect(fetchMock).toHaveBeenCalledWith(
      'https://effective-rpc.example.test/api/v1/desktop/chatllm/session',
      expect.objectContaining({ method: 'POST' })
    )
  })
})

describe('RpcProxyClient.listSessions', () => {
  let client: RpcProxyClient

  beforeEach(() => {
    client = new RpcProxyClient()
    vi.restoreAllMocks()
  })

  it.each(['.', '..', 'host/name', 'host\\name', 'host\nforged', 'x'.repeat(501)])(
    'rejects an unsafe host path before issuing a request: %s',
    async hostRef => {
      const fetchMock = vi.fn()
      vi.stubGlobal('fetch', fetchMock)

      await expect(client.listSessions('rpc-token', hostRef)).rejects.toThrow(/unsafe path segment/)
      expect(fetchMock).not.toHaveBeenCalled()
    }
  )

  it.each(['agent:rpc', 'agent\nforged', 'x'.repeat(201)])(
    'rejects an unsafe session agent before issuing a request: %s',
    async agent => {
      const fetchMock = vi.fn()
      vi.stubGlobal('fetch', fetchMock)

      await expect(client.loadSessionMessages('rpc-token', 'host', agent, 'chat')).rejects.toThrow(
        /unsafe path segment/
      )
      expect(fetchMock).not.toHaveBeenCalled()
    }
  )

  // The rpc-proxy denial bodies exactly as the contract defines them: status 403,
  // the human `error` text, and a machine `code` that says whether access was
  // actually removed (`host_access_revoked`) or merely refused (`host_access_denied`).
  const rpcProxyDenial = (code?: string) =>
    JSON.stringify({ error: 'Forbidden: user cannot access this host', ...(code ? { code } : {}) })

  const stubForbidden = (body: string) => {
    const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 403, text: async () => body })
    vi.stubGlobal('fetch', fetchMock)
    return fetchMock
  }

  it('projects a confirmed revocation (code host_access_revoked) from every raw-fetch site', async () => {
    const fetchMock = stubForbidden(rpcProxyDenial('host_access_revoked'))

    await expect(client.listSessions('token', 'host')).rejects.toThrow(
      '403 Forbidden: host_access_revoked'
    )
    await expect(client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')).rejects.toThrow(
      '403 Forbidden: host_access_revoked'
    )
    await expect(client.renameSession('token', 'host', 'agent-a', 'chat-a', 'T')).rejects.toThrow(
      '403 Forbidden: host_access_revoked'
    )
    expect(fetchMock).toHaveBeenCalledTimes(3)
  })

  it('projects an own-denial without revocation (code host_access_denied) as its own message', async () => {
    const fetchMock = stubForbidden(rpcProxyDenial('host_access_denied'))

    for (const call of [
      () => client.listSessions('token', 'host'),
      () => client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a'),
      () => client.renameSession('token', 'host', 'agent-a', 'chat-a', 'T'),
    ]) {
      const error = await call().then(
        () => null,
        (e: unknown) => e as Error
      )
      expect(error?.message).toBe('403 Forbidden: host_access_denied')
      expect(error?.message).not.toContain('host_access_revoked')
    }
    expect(fetchMock).toHaveBeenCalledTimes(3)
  })

  it.each([
    ['the pre-contract body (error text only, no code)', rpcProxyDenial()],
    [
      'a JSON body whose error is the revoked token but has no code',
      '{"error":"host_access_revoked"}',
    ],
    [
      'a JSON body carrying the revoked token in a non-code field',
      '{"reason":"host_access_revoked"}',
    ],
    ['a text body ending in the revoked token', 'Forbidden: host_access_revoked'],
    ['a code of another kind', '{"code":"missing_scope","error":"host_access_revoked"}'],
  ])('does not forge a confirmed revocation from %s', async (_label, body) => {
    const fetchMock = stubForbidden(body)

    for (const call of [
      () => client.listSessions('token', 'host'),
      () => client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a'),
      () => client.renameSession('token', 'host', 'agent-a', 'chat-a', 'T'),
    ]) {
      const error = await call().then(
        () => null,
        (e: unknown) => e as Error & { status?: number }
      )
      // Liveness witness: the failure path ran and kept the plain 403 text.
      expect(error?.message).toMatch(/failed \(403\)/)
      expect(error?.status).toBe(403)
      expect(error?.message).not.toContain('host_access_revoked')
    }
    expect(fetchMock).toHaveBeenCalledTimes(3)
  })

  it('bounds an oversized upstream body in the message while ApiError keeps it whole', async () => {
    const huge = `{"detail":"${'x'.repeat(100 * 1024)}"}`
    stubForbidden(huge)

    const error = (await client.listSessions('token', 'host').then(
      () => null,
      (e: unknown) => e
    )) as Error & { status?: number; bodyText?: string }
    expect(error).toBeInstanceOf(Error)
    // Status stays first so the renderer's status parsing keeps working.
    expect(error.message.startsWith('List sessions failed (403): ')).toBe(true)
    expect(error.message.length).toBeLessThan(600)
    expect(error.bodyText).toBe(huge)
  })

  it('keeps a generic catalog 403 uncertain', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: false,
        status: 403,
        text: async () => JSON.stringify({ error: 'missing scope' }),
      })
    )

    await expect(client.listSessions('token', 'host')).rejects.toThrow('List sessions failed (403)')
  })

  it('accepts legacy session catalog responses that omit optional metadata', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => ({
          items: [
            {
              agent: 'agent-a',
              chatId: 'chat-a',
              turnCount: 1,
              lastActivityAt: '2026-01-01T00:00:00.000Z',
            },
          ],
        }),
      })
    )

    await expect(client.listSessions('token', 'host')).resolves.toEqual({
      items: [
        {
          agent: 'agent-a',
          chatId: 'chat-a',
          turnCount: 1,
          lastActivityAt: '2026-01-01T00:00:00.000Z',
        },
      ],
    })
  })

  it('treats nullable optional session metadata as absent', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => ({
          items: [
            {
              agent: 'agent-a',
              chatId: 'chat-a',
              turnCount: 1,
              messageCount: null,
              lastActivityAt: '2026-01-01T00:00:00.000Z',
              state: null,
              activeTaskId: null,
              pendingApproval: null,
              tokens: null,
            },
          ],
          nextCursor: null,
        }),
      })
    )

    await expect(client.listSessions('token', 'host')).resolves.toEqual({
      items: [
        {
          agent: 'agent-a',
          chatId: 'chat-a',
          turnCount: 1,
          lastActivityAt: '2026-01-01T00:00:00.000Z',
        },
      ],
    })
  })

  // R3-L10: the `rpc:listSessions` IPC handler refuses a cursor longer than
  // 2048 characters, so a page cursor that long must never reach the renderer.
  it.each([
    [2048, true],
    [3000, false],
  ])('keeps a %s-character nextCursor only within the IPC cursor limit', async (length, kept) => {
    const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
    const nextCursor = 'c'.repeat(length)
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => ({
          items: [
            {
              agent: 'agent-a',
              chatId: 'chat-a',
              turnCount: 1,
              lastActivityAt: '2026-01-01T00:00:00.000Z',
            },
          ],
          nextCursor,
        }),
      })
    )

    const result = await client.listSessions('token', 'host')

    // Witness: the page itself is still delivered in both cases.
    expect(result.items.map(item => item.chatId)).toEqual(['chat-a'])
    expect(result.nextCursor).toBe(kept ? nextCursor : undefined)
    if (kept) {
      expect(warn).not.toHaveBeenCalled()
    } else {
      expect(warn).toHaveBeenCalledTimes(1)
      const logged = warn.mock.calls[0].map(String).join(' ')
      expect(logged).toContain(String(length))
      expect(logged).not.toContain('ccc')
    }
  })

  it('keeps valid catalog entries when one item is malformed and omits unknown states', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => ({
          items: [
            { chatId: 'malformed', turnCount: 1, lastActivityAt: '2026-01-01T00:00:00Z' },
            {
              agent: 'agent-a',
              chatId: 'valid',
              turnCount: 1,
              lastActivityAt: '2026-01-02T00:00:00Z',
              state: 'new_additive_state',
            },
          ],
        }),
      })
    )

    await expect(client.listSessions('token', 'host')).resolves.toEqual({
      items: [
        {
          agent: 'agent-a',
          chatId: 'valid',
          turnCount: 1,
          lastActivityAt: '2026-01-02T00:00:00Z',
        },
      ],
      droppedItemCount: 1,
    })
  })

  it('surfaces a dropped malformed session instead of losing it silently (R1-H1)', async () => {
    // Wire response the server (mcp-host) would send: 3 sessions, the 2nd corrupt
    // (turnCount is a non-integer, which the parser rejects). A silent partial parse
    // would return only the 2 valid ones with no trace — a user's chat vanishing from
    // "Latest sessions" with no way for the renderer to know. The parser must instead
    // keep the valid items AND make the loss observable (warn with the index + a
    // droppedItemCount on the result).
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => ({
          items: [
            {
              agent: 'agent-a',
              chatId: 'chat-a',
              turnCount: 1,
              lastActivityAt: '2026-01-01T00:00:00.000Z',
            },
            {
              agent: 'agent-a',
              chatId: 'chat-corrupt',
              turnCount: 1.5,
              lastActivityAt: '2026-01-02T00:00:00.000Z',
            },
            {
              agent: 'agent-a',
              chatId: 'chat-b',
              turnCount: 2,
              lastActivityAt: '2026-01-03T00:00:00.000Z',
            },
          ],
        }),
      })
    )

    const result = await client.listSessions('token', 'host')

    // Observable result (T4): the two valid chats are returned...
    expect(result.items.map(item => item.chatId)).toEqual(['chat-a', 'chat-b'])
    // ...and the loss is observable — a count on the result the renderer can read...
    expect(result.droppedItemCount).toBe(1)
    // ...and a warn carrying the index of the dropped item in main-process logs.
    expect(warnSpy).toHaveBeenCalledTimes(1)
    expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('index 1'), expect.anything())
  })

  it.each([NaN, Infinity, 1.5, -1, Number.MAX_SAFE_INTEGER + 1])(
    'rejects invalid session catalog counts: %s',
    async invalidCount => {
      vi.stubGlobal(
        'fetch',
        vi.fn().mockResolvedValue({
          ok: true,
          json: async () => ({
            items: [
              {
                agent: 'agent-a',
                chatId: 'chat-a',
                turnCount: invalidCount,
                lastActivityAt: '2026-01-01T00:00:00.000Z',
              },
            ],
          }),
        })
      )

      await expect(client.listSessions('token', 'host')).rejects.toThrow(/turnCount/)
    }
  )

  it('rejects a malformed sessions items container', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({ ok: true, json: async () => ({ items: {} }) })
    )
    await expect(client.listSessions('token', 'host')).rejects.toThrow(/items/)
  })

  it('accepts legacy message responses that omit optional paging metadata', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          turns: [
            {
              number: 1,
              user_input: 'hello',
              started_at: '2026-01-01T00:00:00.000Z',
            },
          ],
        }),
      })
    )

    await expect(
      client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')
    ).resolves.toMatchObject({ agent: 'agent-a', chatId: 'chat-a', turns: [{ number: 1 }] })
  })

  it('treats nullable optional message metadata as absent', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          totalTurns: null,
          oldestTurnNumber: null,
          latestTurnNumber: null,
          hasMoreBefore: null,
          hasMoreAfter: null,
          state: null,
          activeTaskId: null,
          pendingApproval: null,
          tokens: null,
          turns: [
            {
              number: 1,
              user_input: 'hello',
              response: null,
              started_at: '2026-01-01T00:00:00.000Z',
              completed_at: null,
              tokens: null,
              tool_steps: null,
            },
          ],
        }),
      })
    )

    await expect(client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')).resolves.toEqual(
      {
        agent: 'agent-a',
        chatId: 'chat-a',
        turns: [
          {
            number: 1,
            user_input: 'hello',
            started_at: '2026-01-01T00:00:00.000Z',
          },
        ],
      }
    )
  })

  it('accepts zero-based turn metadata emitted by the session service', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          totalTurns: 1,
          oldestTurnNumber: 0,
          latestTurnNumber: 0,
          turns: [
            {
              number: 0,
              user_input: 'hello',
              started_at: '2026-01-01T00:00:00.000Z',
            },
          ],
        }),
      })
    )

    await expect(
      client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')
    ).resolves.toMatchObject({
      oldestTurnNumber: 0,
      latestTurnNumber: 0,
      turns: [{ number: 0 }],
    })
  })

  it('rejects malformed tool_steps before they can reach persisted chat state', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          turns: [
            {
              number: 1,
              user_input: 'hello',
              response: 'world',
              started_at: '2026-01-01T00:00:00.000Z',
              tool_steps: 'PWNED',
            },
          ],
        }),
      })
    )

    await expect(client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')).rejects.toThrow(
      /tool_steps/
    )
  })

  it('accepts producer-shaped tool_steps and validates their optional fields', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          turns: [
            {
              number: 1,
              user_input: 'hello',
              response: 'world',
              started_at: '2026-01-01T00:00:00.000Z',
              tool_steps: [
                {
                  toolName: 'search',
                  displayName: 'Search',
                  state: 'error',
                  durationMs: 12,
                  errorSummary: 'timed out',
                },
              ],
            },
          ],
        }),
      })
    )

    await expect(
      client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')
    ).resolves.toMatchObject({
      turns: [
        {
          tool_steps: [
            {
              toolName: 'search',
              displayName: 'Search',
              state: 'error',
              durationMs: 12,
              errorSummary: 'timed out',
            },
          ],
        },
      ],
    })
  })

  it('surfaces U5 connect_required pendingApproval fields (reason/mcpServerName) and drops a dead provider', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          state: 'awaiting_approval',
          pendingApproval: {
            requestId: 'req-1',
            displayName: 'clickup: create task',
            reason: 'connect_required',
            mcpServerName: 'mcp-clickup',
            // Even if a legacy server still emits `provider`, the parser drops it:
            // under HCC v2 it is always undefined and no renderer/action consumes it.
            provider: 'clickup',
          },
          turns: [],
        }),
      })
    )

    const result = await client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')
    expect(result).toMatchObject({
      pendingApproval: {
        requestId: 'req-1',
        displayName: 'clickup: create task',
        reason: 'connect_required',
        mcpServerName: 'mcp-clickup',
      },
    })
    expect(result.pendingApproval).not.toHaveProperty('provider')
  })

  it('keeps generic pendingApproval byte-identical when the U5 fields are absent (back-compat)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          state: 'awaiting_approval',
          pendingApproval: {
            requestId: 'req-1',
            displayName: 'Search',
          },
          turns: [],
        }),
      })
    )

    const result = await client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')
    expect(result.pendingApproval).toEqual({
      requestId: 'req-1',
      displayName: 'Search',
    })
  })

  it.each([
    ['oldestTurnNumber', -1],
    ['oldestTurnNumber', 0.5],
    ['oldestTurnNumber', Number.MAX_SAFE_INTEGER + 1],
    ['latestTurnNumber', -1],
    ['latestTurnNumber', 0.5],
    ['latestTurnNumber', Number.MAX_SAFE_INTEGER + 1],
    ['turn number', -1],
    ['turn number', 0.5],
    ['turn number', Number.MAX_SAFE_INTEGER + 1],
  ])('rejects invalid %s values: %s', async (field, invalidValue) => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({
          agent: 'agent-a',
          chatId: 'chat-a',
          ...(field === 'oldestTurnNumber' ? { oldestTurnNumber: invalidValue } : {}),
          ...(field === 'latestTurnNumber' ? { latestTurnNumber: invalidValue } : {}),
          turns: [
            {
              number: field === 'turn number' ? invalidValue : 0,
              user_input: 'hello',
              started_at: '2026-01-01T00:00:00.000Z',
            },
          ],
        }),
      })
    )

    await expect(client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')).rejects.toThrow(
      /session messages response/
    )
  })

  it.each([NaN, Infinity, 1.5, -1, Number.MAX_SAFE_INTEGER + 1])(
    'rejects invalid message metadata counts: %s',
    async invalidCount => {
      vi.stubGlobal(
        'fetch',
        vi.fn().mockResolvedValue({
          ok: true,
          status: 200,
          json: async () => ({
            agent: 'agent-a',
            chatId: 'chat-a',
            totalTurns: invalidCount,
            turns: [],
          }),
        })
      )

      await expect(
        client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')
      ).rejects.toThrow(/totalTurns/)
    }
  )

  it('rejects a message response for a different session identity', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({ agent: 'agent-b', chatId: 'chat-a', turns: [] }),
      })
    )
    await expect(client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')).rejects.toThrow(
      /identity/
    )
  })
})

describe('RpcProxyClient.cancelTask', () => {
  let client: RpcProxyClient

  beforeEach(() => {
    client = new RpcProxyClient()
    vi.restoreAllMocks()
  })

  it('POSTs to /api/v1/rpc/hosts/:hostRef/tasks/:taskId/cancel with bearer auth', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 204,
      text: async () => '',
    })
    vi.stubGlobal('fetch', fetchMock)

    await client.cancelTask('rpc-token', 'myhost', 'abc')

    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/rpc/hosts/myhost/tasks/abc/cancel',
      expect.objectContaining({
        method: 'POST',
        headers: expect.objectContaining({
          authorization: 'Bearer rpc-token',
        }),
      })
    )
  })

  it('throws on non-2xx response', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: false,
        status: 500,
        text: async () => 'server error',
      })
    )

    await expect(client.cancelTask('t', 'h', 'abc')).rejects.toThrow()
  })
})

describe('RpcProxyClient.requestSandboxUiOauthAuthorizeUrl', () => {
  let client: RpcProxyClient

  beforeEach(() => {
    client = new RpcProxyClient()
    vi.restoreAllMocks()
  })

  it('POSTs to /sandbox-ui/:ns/:name/oauth/authorize-url with bearer + JSON body', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({ authorizeUrl: 'https://login.salesforce.com/...' }),
    })
    vi.stubGlobal('fetch', fetchMock)

    const result = await client.requestSandboxUiOauthAuthorizeUrl(
      'rpc-token',
      'sandbox-recipes',
      'crm',
      'salesforce'
    )

    expect(result.authorizeUrl).toBe('https://login.salesforce.com/...')
    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/sandbox-ui/sandbox-recipes/crm/oauth/authorize-url',
      expect.objectContaining({
        method: 'POST',
        headers: expect.objectContaining({
          authorization: 'Bearer rpc-token',
          'content-type': 'application/json',
        }),
        body: JSON.stringify({ oauthClientId: 'salesforce', background: false }),
      })
    )
  })

  it('POSTs with background:true when the background flag is set', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({ authorizeUrl: 'https://login.salesforce.com/...' }),
    })
    vi.stubGlobal('fetch', fetchMock)

    await client.requestSandboxUiOauthAuthorizeUrl(
      'rpc-token',
      'sandbox-recipes',
      'crm',
      'salesforce',
      true
    )

    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/sandbox-ui/sandbox-recipes/crm/oauth/authorize-url',
      expect.objectContaining({
        method: 'POST',
        body: JSON.stringify({ oauthClientId: 'salesforce', background: true }),
      })
    )
  })

  it('throws when the response is not ok', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: false,
        status: 404,
        text: async () => '{"error":"recipe_not_found"}',
      })
    )
    const error = await client.requestSandboxUiOauthAuthorizeUrl('t', 'ns', 'r', 'cid').then(
      () => null,
      (e: unknown) => e
    )
    expect(error).toBeInstanceOf(ApiError)
    expect(error).toMatchObject({
      message: 'sandbox-ui authorize-url request failed (404): {"error":"recipe_not_found"}',
      status: 404,
      bodyText: '{"error":"recipe_not_found"}',
    })
  })

  it('throws when the JSON response is missing authorizeUrl', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        status: 200,
        json: async () => ({ wat: 'no key' }),
      })
    )
    await expect(client.requestSandboxUiOauthAuthorizeUrl('t', 'ns', 'r', 'cid')).rejects.toThrow(
      /missing authorizeUrl/
    )
  })

  it('URL-encodes ns / name / clientId path segments', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({ authorizeUrl: 'https://x' }),
    })
    vi.stubGlobal('fetch', fetchMock)

    await client.requestSandboxUiOauthAuthorizeUrl('t', 'weird/ns', 'odd name', 'cid')

    const firstCall = fetchMock.mock.calls[0]!
    const url = firstCall[0] as string
    expect(url).toContain('weird%2Fns')
    expect(url).toContain('odd%20name')
  })
})

// `AbortSignal.timeout` runs on the runtime's own timers, which fake timers do
// not drive. The sandbox-ui bound is shrunk to a few ms instead, keyed on its
// exact value so the app-wide 60 s default is left untouched: a call still
// using that default stays pending and the test fails on its assertion.
function shrinkSandboxUiBound(toMs = 25) {
  const realTimeout = AbortSignal.timeout.bind(AbortSignal)
  return vi
    .spyOn(AbortSignal, 'timeout')
    .mockImplementation(ms => realTimeout(ms === SANDBOX_UI_MINT_TIMEOUT_MS ? toMs : ms))
}

// An rpc-proxy that accepts the request and never answers: the call can only
// settle if the client aborts it.
function fetchThatOnlySettlesOnAbort() {
  return vi.fn(
    (_input: string | URL | Request, init?: RequestInit) =>
      new Promise<Response>((_resolve, reject) => {
        const signal = init?.signal
        signal?.addEventListener('abort', () => reject(signal.reason), { once: true })
      })
  )
}

async function outcomeWithin(promise: Promise<unknown>, ms: number): Promise<unknown> {
  const pending = Symbol('pending')
  const outcome = await Promise.race([
    promise.then(
      () => 'resolved',
      (error: unknown) => error
    ),
    new Promise(resolve => setTimeout(() => resolve(pending), ms)),
  ])
  return outcome === pending ? 'still pending' : outcome
}

describe('RpcProxyClient sandbox-ui calls against a hung rpc-proxy', () => {
  beforeEach(() => {
    vi.restoreAllMocks()
  })

  it('bounds the sandbox-ui calls well under the app-wide request timeout', () => {
    expect(SANDBOX_UI_MINT_TIMEOUT_MS).toBeGreaterThanOrEqual(15_000)
    expect(SANDBOX_UI_MINT_TIMEOUT_MS).toBeLessThanOrEqual(20_000)
  })

  it('rejects a session mint once its bound elapses', async () => {
    shrinkSandboxUiBound()
    vi.stubGlobal('fetch', fetchThatOnlySettlesOnAbort())

    const outcome = await outcomeWithin(
      new RpcProxyClient().mintSandboxUiSession('t', 'sandbox-recipes', 'crm'),
      1_000
    )

    expect(outcome).toMatchObject({ name: 'TimeoutError' })
  })

  it('rejects an authorize-url request once its bound elapses', async () => {
    shrinkSandboxUiBound()
    vi.stubGlobal('fetch', fetchThatOnlySettlesOnAbort())

    const outcome = await outcomeWithin(
      new RpcProxyClient().requestSandboxUiOauthAuthorizeUrl('t', 'sandbox-recipes', 'crm', 'cid'),
      1_000
    )

    expect(outcome).toMatchObject({ name: 'TimeoutError' })
  })
})

describe('RpcProxyClient.listSandboxUiApps', () => {
  let client: RpcProxyClient

  beforeEach(() => {
    client = new RpcProxyClient()
    vi.restoreAllMocks()
  })

  it('GETs the Sandbox UI app catalog with the RPC bearer token', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      statusText: 'OK',
      text: async () =>
        JSON.stringify({
          apps: [
            {
              appRef: 'sandbox-recipes/sales-crm',
              title: "Andy's Sales CRM",
              defaultPath: '/',
              ready: true,
              phase: 'active',
              updatedAt: '2026-05-25T00:00:00Z',
            },
            {
              appRef: 'sandbox-recipes/support-desk',
              title: 'Support Desk',
              defaultPath: '/tickets',
              ready: false,
              phase: 'deploying',
              updatedAt: null,
            },
          ],
        }),
    })
    vi.stubGlobal('fetch', fetchMock)

    const result = await client.listSandboxUiApps('rpc-token')

    expect(result.apps).toHaveLength(2)
    expect(result.apps.map(app => app.title)).toEqual(["Andy's Sales CRM", 'Support Desk'])
    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/sandbox-ui/apps',
      expect.objectContaining({
        method: 'GET',
        headers: expect.objectContaining({
          authorization: 'Bearer rpc-token',
        }),
      })
    )
  })
})

describe('RpcProxyClient.getHostModels', () => {
  let client: RpcProxyClient

  beforeEach(() => {
    client = new RpcProxyClient()
    vi.restoreAllMocks()
  })

  it('GETs /hosts/:hostRef/models with chatId query and bearer auth', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({
        provider: 'claude',
        hostDefault: 'claude-opus-4-8',
        sessionModel: 'claude-haiku-4-5',
        degraded: false,
        models: [
          { name: 'claude-opus-4-8', displayName: 'Opus 4.8' },
          { name: 'claude-haiku-4-5', displayName: 'Haiku 4.5', contextWindowTokens: 200000 },
        ],
      }),
    })
    vi.stubGlobal('fetch', fetchMock)

    const result = await client.getHostModels('rpc-token', 'my host', 'chat-1')

    expect(result).not.toBeNull()
    expect(result?.sessionModel).toBe('claude-haiku-4-5')
    expect(result?.models).toHaveLength(2)
    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/rpc/hosts/my%20host/models?chatId=chat-1',
      expect.objectContaining({
        headers: expect.objectContaining({ authorization: 'Bearer rpc-token' }),
      })
    )
  })

  it('omits the chatId query entirely when no chatId is given (new-chat composer)', async () => {
    // The model LIST is host-level; a brand-new chat has no id, so the request
    // carries no `?chatId=` and the server projects `sessionModel: null`.
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({
        provider: 'claude',
        hostDefault: 'claude-opus-4-8',
        sessionModel: null,
        degraded: false,
        models: [{ name: 'claude-opus-4-8', displayName: 'Opus 4.8' }],
      }),
    })
    vi.stubGlobal('fetch', fetchMock)

    const result = await client.getHostModels('rpc-token', 'my host', '')

    expect(result?.sessionModel).toBeNull()
    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/rpc/hosts/my%20host/models',
      expect.objectContaining({
        headers: expect.objectContaining({ authorization: 'Bearer rpc-token' }),
      })
    )
  })

  it('returns null when the host predates the endpoint (404)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({ ok: false, status: 404, text: async () => 'not found' })
    )
    await expect(client.getHostModels('t', 'h', 'c')).resolves.toBeNull()
  })

  it('returns null when the route is not implemented (501)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({ ok: false, status: 501, text: async () => 'not implemented' })
    )
    await expect(client.getHostModels('t', 'h', 'c')).resolves.toBeNull()
  })

  it('throws on a genuine server error (500)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({ ok: false, status: 500, text: async () => 'boom' })
    )
    await expect(client.getHostModels('t', 'h', 'c')).rejects.toThrow()
  })
})

describe('RpcProxyClient.setHostModel', () => {
  let client: RpcProxyClient

  beforeEach(() => {
    client = new RpcProxyClient()
    vi.restoreAllMocks()
  })

  it('POSTs /hosts/:hostRef/model with the chatId+model body and bearer auth', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({ effective: 'next-task', provider: 'claude', model: 'claude-haiku-4-5' }),
    })
    vi.stubGlobal('fetch', fetchMock)

    const result = await client.setHostModel('rpc-token', 'my host', 'chat-1', 'claude-haiku-4-5')

    expect(result).toEqual({
      effective: 'next-task',
      provider: 'claude',
      model: 'claude-haiku-4-5',
    })
    expect(fetchMock).toHaveBeenCalledWith(
      'http://proxy/api/v1/rpc/hosts/my%20host/model',
      expect.objectContaining({
        method: 'POST',
        headers: expect.objectContaining({
          authorization: 'Bearer rpc-token',
          'content-type': 'application/json',
        }),
        body: JSON.stringify({ chatId: 'chat-1', model: 'claude-haiku-4-5' }),
      })
    )
  })

  it('re-throws a 403 with the model_not_allowed token in the message', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: false,
        status: 403,
        text: async () => JSON.stringify({ error: 'model_not_allowed' }),
      })
    )
    await expect(client.setHostModel('t', 'h', 'c', 'banned')).rejects.toThrow('model_not_allowed')
  })

  it('also detects model_not_allowed when mcp-host answers 400 (fail-closed)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: false,
        status: 400,
        text: async () => JSON.stringify({ error: 'model_not_allowed' }),
      })
    )
    await expect(client.setHostModel('t', 'h', 'c', 'banned')).rejects.toThrow('model_not_allowed')
  })

  it('does NOT map a host-access 403 to model_not_allowed (B3 regression guard)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: false,
        status: 403,
        text: async () => JSON.stringify({ error: 'Forbidden: user cannot access this host' }),
      })
    )
    // An access denial must surface as a generic failure, not a policy rejection:
    // the message must not carry the model_not_allowed token the renderer keys on.
    await expect(client.setHostModel('t', 'h', 'c', 'm')).rejects.toThrow(/Set host model failed/)
    await expect(client.setHostModel('t', 'h', 'c', 'm')).rejects.not.toThrow('model_not_allowed')
  })

  it('throws on a generic non-2xx response', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({ ok: false, status: 500, text: async () => 'boom' })
    )
    await expect(client.setHostModel('t', 'h', 'c', 'm')).rejects.toThrow()
  })
})