Skip to content

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

TypeScript
15.6 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RpcProxyClient, parseSessionsListResult } from '../src/rpcProxyClient.js'

// ── Mocks ─────────────────────────────────────────────────────────────────────

const mockRequestJson = vi.fn()

vi.mock('../src/httpClient.js', () => ({
  requestJson: (...args: unknown[]) => mockRequestJson(...args),
  // §4.5-6: the raw-fetch methods wrap their signal with `withTimeout`; the mock
  // passes the (optional) signal through — the stubbed `fetch` ignores it.
  withTimeout: (signal?: AbortSignal) => signal,
  ApiError: class extends Error {
    status: number
    bodyText: string
    constructor(message?: string, status = 0, bodyText = '') {
      super(message)
      this.status = status
      this.bodyText = bodyText
    }
  },
}))

vi.mock('../src/config.js', () => ({
  config: {
    rpcProxyBaseUrl: 'http://localhost:8094',
    requestTimeoutMs: 5000,
  },
}))

// ── Setup ─────────────────────────────────────────────────────────────────────

beforeEach(() => {
  mockRequestJson.mockReset()
})

afterEach(() => {
  vi.unstubAllGlobals()
})

// ── Tests ─────────────────────────────────────────────────────────────────────

describe('RpcProxyClient — health()', () => {
  it('calls GET /health on rpc-proxy base URL', async () => {
    mockRequestJson.mockResolvedValueOnce({ status: 'ok' })

    const client = new RpcProxyClient()
    const result = await client.health()

    expect(mockRequestJson).toHaveBeenCalledWith('GET', 'http://localhost:8094/health')
    expect(result.status).toBe('ok')
  })
})

describe('RpcProxyClient — invokeHostMessage()', () => {
  it('posts to /api/v1/rpc/hosts/:hostRef/messages with message payload', async () => {
    mockRequestJson.mockResolvedValueOnce({ response: 'Done', status: 'completed' })

    const client = new RpcProxyClient()
    const payload = { content: 'Hello agent', messageId: 'm1', channelType: 'telegram' as const }
    await client.invokeHostMessage('rpc-token', 'chatllm', payload)

    const [method, url, opts] = mockRequestJson.mock.calls[0] as [
      string,
      string,
      { token: string; body: unknown },
    ]
    expect(method).toBe('POST')
    expect(url).toContain('chatllm/messages')
    expect(opts.token).toBe('rpc-token')
    expect(opts.body).toEqual(payload)
  })
})

describe('RpcProxyClient — loadSessionMessages()', () => {
  it('throws an exact 404 error for missing sessions', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('not found', { status: 404 })))

    const client = new RpcProxyClient()

    await expect(
      client.loadSessionMessages('rpc-token', 'chatllm', 'agent', 'missing-chat')
    ).rejects.toThrow('Session not found (404)')
  })

  // F5: this is a RUNTIME check that the bridge forwards the recovery fields the
  // renderer reconcile reads (`state`/`activeTaskId`/`pendingApproval`/per-turn
  // `tool_steps`). NOTE: this file is under `test/`, which the project's tsconfig
  // `include` excludes and no `typecheck` script covers, so a TYPE regression would
  // NOT be caught here. The compile-time guard lives in `src/types.ts`
  // (`_RecoveryFields`), enforced by `build:main`.
  it('exposes state/activeTaskId/pendingApproval/tool_steps on the declared type', async () => {
    const body = JSON.stringify({
      agent: 'agent',
      chatId: 'c1',
      state: 'awaiting_approval',
      activeTaskId: 'task-1',
      pendingApproval: { requestId: 'req-1', displayName: 'Run shell' },
      turns: [
        {
          number: 1,
          user_input: 'hi',
          response: 'ok',
          started_at: '2026-06-18T00:00:00Z',
          tool_steps: [{ toolName: 'shell', displayName: 'Run shell', state: 'completed' }],
        },
      ],
    })
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body, { status: 200 })))

    const client = new RpcProxyClient()
    const result = await client.loadSessionMessages('rpc-token', 'chatllm', 'agent', 'c1')

    // Type-enforced reads (no `as` cast / re-declaration): these would not compile
    // if the return type omitted the fields.
    const state: 'idle' | 'processing' | 'awaiting_approval' | undefined = result.state
    const activeTaskId: string | undefined = result.activeTaskId
    const approvalName: string | undefined = result.pendingApproval?.displayName
    const firstToolStep = result.turns[0]?.tool_steps?.[0]

    expect(state).toBe('awaiting_approval')
    expect(activeTaskId).toBe('task-1')
    expect(approvalName).toBe('Run shell')
    expect(firstToolStep?.toolName).toBe('shell')
  })
})

describe('RpcProxyClient — getContextBreakdown()', () => {
  it('GETs the context-breakdown endpoint and parses the wire shape', async () => {
    const breakdown = {
      buckets: { messages: 537, systemTools: 306, metaContext: 115, systemPrompt: 17 },
      totalInputTokens: 32_900,
      maxTokens: 100_000,
      fillRatio: 0.329,
      cacheHitRate: 0.82,
      capturedAtTurn: 4,
    }
    const fetchMock = vi
      .fn()
      .mockResolvedValue(new Response(JSON.stringify({ breakdown }), { status: 200 }))
    vi.stubGlobal('fetch', fetchMock)

    const client = new RpcProxyClient()
    const result = await client.getContextBreakdown('rpc-token', 'chatllm', 'agent', 'c1')

    const calledUrl = String(fetchMock.mock.calls[0]?.[0])
    expect(calledUrl).toBe(
      'http://localhost:8094/api/v1/rpc/hosts/chatllm/sessions/agent/c1/context-breakdown'
    )
    expect(result.breakdown).toEqual(breakdown)
  })

  it('returns { breakdown: null } on the anti-enumeration 404 (no snapshot / not owned)', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue(new Response('session not found', { status: 404 }))
    )

    const client = new RpcProxyClient()
    const result = await client.getContextBreakdown('rpc-token', 'chatllm', 'agent', 'missing')

    expect(result.breakdown).toBeNull()
  })

  it('throws on non-404 error statuses', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('boom', { status: 500 })))

    const client = new RpcProxyClient()
    await expect(client.getContextBreakdown('rpc-token', 'chatllm', 'agent', 'c1')).rejects.toThrow(
      'Get context breakdown failed (500)'
    )
  })
})

describe('RpcProxyClient — openTaskProgressStream()', () => {
  it('surfaces `: keepalive` SSE comments as heartbeat events', async () => {
    // A stream that opens, sends a keepalive comment, then a real terminal.
    const body = [
      'event: open\ndata: {"taskId":"t1"}\n\n',
      ': keepalive\n\n',
      'event: done\ndata: {}\n\n',
    ]
    const stream = new ReadableStream<Uint8Array>({
      start(controller) {
        const enc = new TextEncoder()
        for (const chunk of body) controller.enqueue(enc.encode(chunk))
        controller.close()
      },
    })
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(stream, { status: 200 })))

    const client = new RpcProxyClient()
    const events: string[] = []
    await client.openTaskProgressStream(
      'rpc-token',
      'chatllm',
      't1',
      ({ event }) => events.push(event),
      new AbortController().signal
    )

    // The comment must not be dropped — it arrives as a heartbeat so the
    // renderer's watchdog can reset on it.
    expect(events).toContain('heartbeat')
    expect(events).toEqual(['open', 'heartbeat', 'done'])
  })
})

describe('RpcProxyClient — renameSession() (spec 15 Fase B)', () => {
  it.each([
    {
      status: 403,
      body: JSON.stringify({
        error: 'Forbidden: user cannot access this host',
        code: 'host_access_revoked',
      }),
      marked: true,
    },
    {
      status: 403,
      body: JSON.stringify({
        error: 'Forbidden: user cannot access this host',
        code: 'host_access_denied',
      }),
      marked: false,
    },
    {
      status: 403,
      body: JSON.stringify({ error: 'Forbidden: user cannot access this host' }),
      marked: false,
    },
    { status: 403, body: JSON.stringify({ error: 'host_access_revoked' }), marked: false },
    {
      status: 403,
      body: JSON.stringify({ error: 'Forbidden: missing rename scope' }),
      marked: false,
    },
    { status: 403, body: 'Forbidden: user cannot access this host', marked: false },
    {
      status: 503,
      body: JSON.stringify({
        error: 'Forbidden: user cannot access this host',
        code: 'host_access_revoked',
      }),
      marked: false,
    },
  ])(
    'marks Host-wide revocation only for a 403 whose body carries code host_access_revoked ($status, $marked)',
    async ({ status, body, marked }) => {
      vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body, { status })))
      const client = new RpcProxyClient()
      const error = await client
        .renameSession('rpc-token', 'chatllm', 'chatllm', 'chat-1', 'name')
        .catch((caught: Error) => caught)
      expect(error).toBeInstanceOf(Error)
      // Liveness witness: the request reached the HTTP-error path and reported its status.
      expect((error as Error).message).toContain(String(status))
      expect((error as Error).message.includes('host_access_revoked')).toBe(marked)
    }
  )

  it('PATCHes the name route with the title and returns the (re-sanitized) server title', async () => {
    const fetchMock = vi
      .fn()
      .mockResolvedValue(
        new Response(JSON.stringify({ ok: true, title: 'Clean name' }), { status: 200 })
      )
    vi.stubGlobal('fetch', fetchMock)

    const client = new RpcProxyClient()
    const result = await client.renameSession(
      'rpc-token',
      'chatllm',
      'chatllm',
      'chat-1',
      'Clean name'
    )

    expect(result).toEqual({ title: 'Clean name' })
    const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]
    expect(String(requestUrl)).toContain('/hosts/chatllm/sessions/chatllm/chat-1/name')
    expect(init.method).toBe('PATCH')
    expect(JSON.parse(String(init.body))).toEqual({ title: 'Clean name' })
  })

  it('re-sanitizes a hostile echoed title on read (bidi override stripped)', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValue(
          new Response(JSON.stringify({ ok: true, title: 'Safe‮name' }), { status: 200 })
        )
    )
    const client = new RpcProxyClient()
    const result = await client.renameSession(
      'rpc-token',
      'chatllm',
      'chatllm',
      'chat-1',
      'Safe name'
    )
    expect(result.title).toBe('Safename')
    expect(result.title).not.toContain('‮')
  })

  it('preserves the HTTP status in the thrown error message (404 / 400 / 403 / 5xx)', async () => {
    const client = new RpcProxyClient()
    for (const status of [404, 400, 403, 502]) {
      vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('nope', { status })))
      await expect(
        client.renameSession('rpc-token', 'chatllm', 'chatllm', 'chat-1', 'x')
      ).rejects.toThrow(`(${status})`)
    }
  })

  it('never puts the raw title in the error message', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('bad', { status: 400 })))
    const client = new RpcProxyClient()
    await expect(
      client.renameSession('rpc-token', 'chatllm', 'chatllm', 'chat-1', 'super-secret-title')
    ).rejects.toThrow(/^Rename session failed \(400\)$/)
  })

  it('rejects an unsafe chatId segment before any fetch', async () => {
    const fetchMock = vi.fn()
    vi.stubGlobal('fetch', fetchMock)
    const client = new RpcProxyClient()
    await expect(
      client.renameSession('rpc-token', 'chatllm', 'chatllm', '../evil', 'x')
    ).rejects.toThrow(/unsafe path segment/)
    expect(fetchMock).not.toHaveBeenCalled()
  })
})

describe('parseSessionsListResult — title parse + sanitize on read (spec 15 §2.2/A14)', () => {
  const baseItem = {
    agent: 'chatllm',
    chatId: 'c1',
    turnCount: 1,
    lastActivityAt: '2026-09-12T00:00:00.000Z',
  }

  it('parses a clean server title verbatim', () => {
    const result = parseSessionsListResult({
      items: [{ ...baseItem, title: 'Deploy the staging cluster' }],
    })
    expect(result.items[0]?.title).toBe('Deploy the staging cluster')
  })

  it('omits the title when the host does not report one', () => {
    const result = parseSessionsListResult({ items: [baseItem] })
    expect(result.items[0]).not.toHaveProperty('title')
  })

  it('strips bidi-override and zero-width characters (spoofing defense)', () => {
    // A title crafted to spoof the destructive rename dialog with an RLO
    // override + zero-width joiner. The client must not trust it.
    const hostile = 'Safe‮erongi​ name'
    const result = parseSessionsListResult({ items: [{ ...baseItem, title: hostile }] })
    expect(result.items[0]?.title).toBe('Safeerongi name')
    expect(result.items[0]?.title).not.toContain('‮')
    expect(result.items[0]?.title).not.toContain('​')
  })

  it('strips control characters (newlines, tabs, NUL)', () => {
    const result = parseSessionsListResult({
      items: [{ ...baseItem, title: 'line1\n\tline2' }],
    })
    expect(result.items[0]?.title).toBe('line1line2')
  })

  it('drops a title that is empty after sanitization', () => {
    const result = parseSessionsListResult({
      items: [{ ...baseItem, title: '‮​' }],
    })
    expect(result.items[0]).not.toHaveProperty('title')
  })

  it('keeps a session whose optional title is a non-string, just untitled (not dropped)', () => {
    // A malformed cosmetic field must not make a real conversation disappear.
    // T4: assert the resulting item (present, untitled), not a drop count.
    const result = parseSessionsListResult({
      items: [{ ...baseItem, chatId: 'keep', title: 123 }],
    })
    expect(result.items).toHaveLength(1)
    expect(result.items[0]?.chatId).toBe('keep')
    expect(result.items[0]).not.toHaveProperty('title')
    expect(result.droppedItemCount).toBeUndefined()
  })

  it('still drops an item whose MANDATORY field is malformed (title fix does not mask this)', () => {
    const result = parseSessionsListResult({
      items: [
        { ...baseItem, chatId: 'good', title: 'fine' },
        { ...baseItem, chatId: 'bad', lastActivityAt: 123 },
      ],
    })
    expect(result.items).toHaveLength(1)
    expect(result.items[0]?.chatId).toBe('good')
    expect(result.droppedItemCount).toBe(1)
  })

  it('truncates an oversized title from a stale/hostile host to the server cap (120 code points)', () => {
    // The server rejects >120 code points with a 400, so a legit stored title is
    // always within the cap; a host that returns more is not trusted. Emoji so a
    // naive .length (UTF-16 units) would miscount vs the code-point cap.
    const oversized = '😀'.repeat(200)
    const result = parseSessionsListResult({ items: [{ ...baseItem, title: oversized }] })
    const title = result.items[0]?.title as string
    expect(Array.from(title)).toHaveLength(120)
    expect(title).toBe('😀'.repeat(120))
  })

  it('strips line/paragraph separators (U+2028/U+2029) — single-line title', () => {
    const result = parseSessionsListResult({
      items: [{ ...baseItem, title: 'line1\u2028line2\u2029end' }],
    })
    expect(result.items[0]?.title).toBe('line1line2end')
    expect(result.items[0]?.title).not.toContain('\u2028')
    expect(result.items[0]?.title).not.toContain('\u2029')
  })
})