Skip to content

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

TypeScript
8.0 KB
Raw Blame
/**
 * Proves that normal Telegram chat can receive files generated by mcp-host
 * internal tools without going through workflow_result or workflow grants.
 */
import { type Page, expect, test } from '@playwright/test'
import { execFileSync } from 'node:child_process'
import {
  CHANNELS_NS,
  applyTelegramCommunicationChannel,
  configureChannelReaderTelegramApiRoot,
  expectChannelReaderCanReachMcpHost,
  expectChannelReaderHasNoProviderHttpIngress,
  fakeTelegramPollingCount,
  installFakeTelegramProvider,
  removeFakeTelegramProvider,
  removeTelegramCommunicationChannel,
  restoreChannelReaderTelegramApiRoot,
  waitForChannelReader,
} from './third-party-authn-first-party-mcphost/fakeTelegramProvider'
import {
  HOST_REF,
  openTelegramClient,
  sendTelegramClientMessage,
  setTelegramClientIdentity,
  telegramReplyItems,
  waitForTelegramFinalReplyTextAfter,
} from './third-party-authn-first-party-mcphost/telegramE2eClient'
import { verifyTelegramMediumWithFakeProvider } from './third-party-authn-first-party-mcphost/telegramMediumChallengeSetup'
import { cleanupTelegramMediumBinding } from './third-party-authn-first-party-mcphost/workflowApprovalJourney'
import { E2E_EMAIL, K8S_CONTEXT, clearSession, loginAs } from './workflowUi'

function kubectlOutput(args: string[], timeout = 30_000): string {
  return execFileSync('kubectl', ['--context', K8S_CONTEXT, ...args], {
    encoding: 'utf-8',
    timeout,
  })
}

function kubectl(args: string[], timeout = 30_000): void {
  kubectlOutput(args, timeout)
}

function sleepOneSecond(): void {
  execFileSync('sleep', ['1'])
}

function waitForStableFakeTelegramReader(hostName: string): void {
  const labelSelector = `app=channel-reader,clerum.io/host=${hostName}`
  let lastState = ''
  let stableChecks = 0
  for (let attempt = 0; attempt < 120; attempt += 1) {
    const raw = kubectlOutput(
      [
        '-n',
        CHANNELS_NS,
        'get',
        'pod',
        '-l',
        labelSelector,
        '--field-selector=status.phase=Running',
        '-o',
        'json',
      ],
      10_000
    )
    const list = JSON.parse(raw) as {
      items?: Array<{
        metadata?: { name?: string; deletionTimestamp?: string }
        status?: { containerStatuses?: Array<{ ready?: boolean }> }
      }>
    }
    const pods = list.items ?? []
    const readyPods = pods.filter(item => {
      const statuses = item.status?.containerStatuses ?? []
      return (
        !item.metadata?.deletionTimestamp &&
        Boolean(item.metadata?.name) &&
        statuses.length > 0 &&
        statuses.every(status => status.ready)
      )
    })
    if (readyPods.length === 1) {
      const podName = readyPods[0].metadata!.name!
      const logs = kubectlOutput(
        ['-n', CHANNELS_NS, 'logs', `pod/${podName}`, '--tail=220'],
        15_000
      )
      if (logs.includes('[Telegram] Connected as @clerum_e2e_bot')) {
        stableChecks += 1
        if (stableChecks >= 5) return
      } else {
        stableChecks = 0
      }
      lastState = logs
    } else {
      stableChecks = 0
      lastState = `expected exactly one channel-reader pod and one ready pod, found pods=${pods.length}, ready=${readyPods.length}`
    }
    sleepOneSecond()
  }
  expect(
    lastState,
    'channel-reader must have exactly one ready pod connected to fake Telegram'
  ).toContain('[Telegram] Connected as @clerum_e2e_bot')
}

test.describe('fake Telegram internal generated artifacts through first-party mcp-host', () => {
  test('Telegram normal chat delivers an internal generated markdown artifact as a document', async ({
    browser,
  }) => {
    test.setTimeout(420_000)

    const uniqueId = Date.now()
    const marker = `telegram-internal-artifact-${uniqueId}`
    const filename = `${marker}.md`
    const telegramMessageBase = uniqueId
    const telegramPrivateChatId = String(4_000_000_000_000 + uniqueId)
    const telegramIdentity = {
      providerChannelId: telegramPrivateChatId,
      providerUserId: telegramPrivateChatId,
      conversationLabel: `Telegram artifact ${marker}`,
    }
    let telegramPage: Page | null = null
    let telegramPortForward: { stop: () => void } | null = null

    try {
      await test.step('prepare fake Telegram and channel-reader transport', async () => {
        await clearSession()
        cleanupTelegramMediumBinding(telegramIdentity)
        const { userId, userToken } = await loginAs(E2E_EMAIL)
        installFakeTelegramProvider()
        configureChannelReaderTelegramApiRoot()
        applyTelegramCommunicationChannel(HOST_REF, [telegramIdentity], [userId])
        waitForChannelReader(HOST_REF)
        waitForStableFakeTelegramReader(HOST_REF)
        expectChannelReaderHasNoProviderHttpIngress(HOST_REF)
        expectChannelReaderCanReachMcpHost(HOST_REF)
        await expect
          .poll(() => fakeTelegramPollingCount(), {
            timeout: 30_000,
            intervals: [500, 1_000, 2_000],
            message: 'channel-reader should poll fake Telegram before user messages are pushed',
          })
          .toBeGreaterThan(0)

        const telegram = await openTelegramClient(browser)
        telegramPage = telegram.page
        telegramPortForward = telegram.portForward
        await verifyTelegramMediumWithFakeProvider(
          telegramPage,
          userToken,
          telegramMessageBase,
          telegramIdentity
        )
      })

      await test.step('open the visible fake Telegram client', async () => {
        if (!telegramPage) throw new Error('Telegram user client was not initialized')
        await setTelegramClientIdentity(telegramPage, telegramIdentity)
        await expect(telegramPage.getByTestId('telegram-form')).toBeVisible()
        await expect(telegramPage.getByTestId('telegram-message-text')).toBeVisible()
      })

      await test.step('send a normal chat request that generates a markdown file', async () => {
        waitForStableFakeTelegramReader(HOST_REF)
        const previousReplyCount = await telegramReplyItems(telegramPage!).count()
        const escapedFilename = filename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
        await sendTelegramClientMessage(
          telegramPage!,
          [
            `Use clerum__generate_markdown to create a Markdown file named ${filename}.`,
            `The file content must include this exact line: TELEGRAM_INTERNAL_ARTIFACT_MARKER=${marker}.`,
            'Reply briefly after the file is generated.',
          ].join(' '),
          telegramMessageBase + 1
        )
        await waitForTelegramFinalReplyTextAfter(
          telegramPage!,
          previousReplyCount,
          new RegExp(escapedFilename),
          240_000
        )
        await expect(telegramPage!.getByTestId('telegram-bot-replies')).not.toContainText(
          /requires approval|Reply \/approve or \/deny/i
        )
      })

      await test.step('see the delivered document in Telegram with safe metadata', async () => {
        const documentReply = telegramPage!.locator(
          `[data-testid="telegram-bot-reply"][data-document-filename="${filename}"]`
        )
        await expect(documentReply).toBeVisible({ timeout: 240_000 })
        await expect(documentReply).toHaveAttribute('data-document-mime', 'text/markdown')
        await expect(documentReply).toHaveAttribute('data-document-size', /^[1-9][0-9]*$/)
        await expect(documentReply).toHaveAttribute('data-document-sample', new RegExp(marker))
        await expect(documentReply).toHaveAttribute('data-document-sha256', /^[a-f0-9]{64}$/)
        await expect(telegramPage!.getByTestId('telegram-bot-replies')).not.toContainText(
          'Could not verify this Telegram conversation for workflow access'
        )
        await expect(telegramPage!.getByTestId('telegram-approval-card')).toBeHidden()
      })
    } finally {
      if (telegramPage) await telegramPage.close().catch(() => undefined)
      telegramPortForward?.stop()
      removeTelegramCommunicationChannel()
      restoreChannelReaderTelegramApiRoot()
      removeFakeTelegramProvider()
      cleanupTelegramMediumBinding(telegramIdentity)
    }
  })
})