Skip to content

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

TypeScript
5.6 KB
Raw Blame
import {
  type ElectronApplication,
  type Page,
  test as base,
  expect as baseExpect,
  _electron as electron,
} from '@playwright/test'
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { E2E_DESKTOP_PASSWORD, awaitPasswordPace, seedPasswordForEmail } from './workflowUi'

const E2E_EMAIL = process.env.E2E_DEV_LOGIN_EMAIL || '[email protected]'

type Fixtures = {
  electronApp: ElectronApplication
  appPage: Page
}

async function launchIsolatedElectron(): Promise<ElectronApplication> {
  const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-e2e-electron-'))
  let app: ElectronApplication
  try {
    app = await electron.launch({
      args: [`--user-data-dir=${userDataDir}`, path.resolve(__dirname, '../../dist/main.js')],
      env: {
        ...process.env,
        EXTERNAL_REST_API_BASE_URL:
          process.env.EXTERNAL_REST_API_BASE_URL || 'http://127.0.0.1:8091',
        RPC_PROXY_BASE_URL: process.env.RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094',
        CLERUM_DESKTOP_CONFIG_PATH:
          process.env.CLERUM_DESKTOP_CONFIG_PATH ||
          path.join(userDataDir, 'e2e-runtime-config.json'),
      },
    })
  } catch (error) {
    fs.rmSync(userDataDir, { recursive: true, force: true })
    throw error
  }
  app.on('close', () => fs.rmSync(userDataDir, { recursive: true, force: true }))
  return app
}

export const test = base.extend<Fixtures>({
  electronApp: async ({}, use) => {
    clearStoredSession()
    const app = await launchIsolatedElectron()
    try {
      await use(app)
    } finally {
      await app.close()
    }
  },

  appPage: async ({ electronApp }, use) => {
    // Seed the password without an API login: control-api charges every
    // attempt, successful ones included, against a 5-per-15-minutes budget
    // (control-api/src/services/auth/passwordAdmissionState.ts).
    seedPasswordForEmail(E2E_EMAIL)

    const page = await electronApp.firstWindow()
    await page.waitForLoadState('domcontentloaded')

    const dashboard = page.locator('[data-testid="user-display-name"]')
    const emailInput = page.locator('#email-input')
    const passwordInput = page.locator('#password-input')
    const authenticatedShell = page.getByRole('textbox', { name: 'Agent message composer' })

    await Promise.race([
      emailInput.waitFor({ state: 'visible', timeout: 20_000 }).catch(() => {}),
      dashboard.waitFor({ state: 'visible', timeout: 20_000 }).catch(() => {}),
      authenticatedShell.waitFor({ state: 'visible', timeout: 20_000 }).catch(() => {}),
    ])

    if (await emailInput.isVisible()) {
      await emailInput.fill(E2E_EMAIL)
      await passwordInput.fill(E2E_DESKTOP_PASSWORD)
      await awaitPasswordPace()
      await page.click('button:has-text("Sign in")')
    }

    await Promise.race([
      dashboard.waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {}),
      authenticatedShell.waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {}),
    ])
    if (await dashboard.isVisible()) {
      const displayName = await dashboard.textContent()
      baseExpect(displayName, `Expected logged-in user to be ${E2E_EMAIL}`).toContain(
        E2E_EMAIL.split('@')[0]
      )
    } else {
      await baseExpect(authenticatedShell).toBeVisible()
    }

    await use(page)
  },
})

export { expect } from '@playwright/test'

export async function wipeChatsDir(): Promise<void> {
  const chatsDir = path.join(os.homedir(), '.clerum', 'chats')
  try {
    await (await import('node:fs/promises')).rm(chatsDir, { recursive: true, force: true })
  } catch {
    /* already absent — ok */
  }
}

export function clearStoredSession(): void {
  try {
    execFileSync('security', ['delete-generic-password', '-s', 'Evenfire', '-a', 'session-token'], {
      stdio: 'ignore',
    })
  } catch {
    /* no stored session — OK */
  }
  const sessionFile = path.join(os.homedir(), '.evenfire', 'session-token.json')
  try {
    fs.unlinkSync(sessionFile)
  } catch {
    /* not present — OK */
  }
  const sessionEncFile = path.join(os.homedir(), '.clerum-desktop', 'session-token.enc')
  try {
    fs.unlinkSync(sessionEncFile)
  } catch {
    /* not present — OK */
  }
}

export async function launchFreshElectron(): Promise<ElectronApplication> {
  clearStoredSession()
  return launchIsolatedElectron()
}

export async function loginAs(page: Page, email: string): Promise<void> {
  seedPasswordForEmail(email)

  const emailInput = page.locator('#email-input')
  const passwordInput = page.locator('#password-input')
  const dashboard = page.locator('[data-testid="user-display-name"]')
  const authenticatedShell = page.getByRole('textbox', { name: 'Agent message composer' })

  await Promise.race([
    emailInput.waitFor({ state: 'visible', timeout: 20_000 }).catch(() => {}),
    dashboard.waitFor({ state: 'visible', timeout: 20_000 }).catch(() => {}),
    authenticatedShell.waitFor({ state: 'visible', timeout: 20_000 }).catch(() => {}),
  ])

  if (await emailInput.isVisible()) {
    await emailInput.fill(email)
    await passwordInput.fill(E2E_DESKTOP_PASSWORD)
    await awaitPasswordPace()
    await page.click('button:has-text("Sign in")')
  }

  await Promise.race([
    dashboard.waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {}),
    authenticatedShell.waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {}),
  ])
  if (await dashboard.isVisible()) {
    const displayName = await dashboard.textContent()
    if (!displayName?.includes(email.split('@')[0])) {
      throw new Error(`Expected logged-in user to be ${email}, saw ${displayName}`)
    }
  } else {
    await baseExpect(authenticatedShell).toBeVisible()
  }
}