/** * E2E (docs/06 §12.1): computers with the real local model on the GPU. Skipped unless AI_URL is set. * 1) 오목 연습: "생각 중…" shows while the computer chooses; a person asks it something by name → "입력 중…", then an * answer written by the model appears in the room chat. * 2) 마피아 연습: the computers' greetings/lines come out of the model (not only the built-in lines). * Run: AI_URL=http://localhost:11434 E2E_PORT=4545 bun e2e/ai.e2e.ts (needs apps/web/dist built) */ import { chromium, type Page } from 'playwright-core'; import { mkdirSync, mkdtempSync } from 'node:fs'; import { join } from 'node:path'; import { loadConfig } from '../apps/server/src/config'; import { startServer } from '../apps/server/src/server'; if (!process.env.AI_URL) { console.log('AI_URL not set: skipped'); process.exit(0); } const PORT = Number(process.env.E2E_PORT ?? 4545); const ORIGIN = `http://localhost:${PORT}`; const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results'); mkdirSync(SHOTS, { recursive: true }); const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-')); const app = startServer({ config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN, AI_URL: process.env.AI_URL, AI_MODEL: process.env.AI_MODEL }), log: (level, msg, extra) => { if (level !== 'info' || msg.startsWith('ai')) console.log(` [${level}] ${msg} ${JSON.stringify(extra ?? {})}`); }, staticDir: join(import.meta.dir, '../apps/web/dist'), }); const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true }); let failed = false; const step = async (name: string, fn: () => Promise) => { const t0 = performance.now(); try { await fn(); console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`); } catch (e) { failed = true; console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`); throw e; } }; const BUILT_IN = /^(ㅎㅇㅎㅇ|안녕ㅋㅋ|하이~ 나 시민임ㅋㅋ|ㅎㅇ 마피아 누구냐|오 재밌겠다ㅋㅋ|안녕하세요! 잘 부탁드려요|반가워요~ 이번 판 재밌게 해요|안녕하세요\. 차분하게 찾아봐요|다들 반가워요! 마피아 꼭 찾아요)$/; try { const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' }); await ctx.addInitScript(() => { for (const g of ['omok', 'mafia']) localStorage.setItem(`bg:qs:${g}`, '1'); }); const a = await ctx.newPage(); const errors: string[] = []; a.on('pageerror', (e) => errors.push(e.message)); // Warm the model first (the first load takes ~20 s). for (let i = 0; i < 60 && !(await (await fetch(`${ORIGIN}/healthz`)).json()).ai?.ok; i++) await Bun.sleep(1000); await step('오목 연습: 생각 중… → 이름을 불러 물으면 입력 중… → 모델이 쓴 대답', async () => { await a.goto(`${ORIGIN}/g/omok`); await a.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click(); await a.getByLabel('내 이름(닉네임)').fill('사람'); await a.getByRole('button', { name: '이 이름으로 시작하기' }).click(); await a.waitForURL(/\/r\/\d{6}$/); await a.getByLabel('자리').getByText('컴퓨터 1').waitFor(); await a.getByRole('button', { name: '▶ 게임 시작' }).click(); await a.locator('svg[role="grid"]').waitFor(); const before = await a.locator('.chat-line').count(); await a.getByPlaceholder(/메시지/).fill('컴퓨터 1 너 오목 잘해?'); await a.getByPlaceholder(/메시지/).press('Enter'); await a.locator('.bot-activity [data-activity="typing"]').first().waitFor({ timeout: 20_000 }); await a.screenshot({ path: join(SHOTS, 'ai-1-typing.png') }); await a.waitForFunction((n) => [...document.querySelectorAll('.chat-line')].slice(n).some((l) => l.querySelector('strong')?.textContent === '컴퓨터 1'), before + 1, { timeout: 30_000 }); const lines = await a.locator('.chat-line').allInnerTexts(); console.log(' omok chat:', lines.map((l) => l.replace(/\n/g, ' ')).join(' | ')); await a.screenshot({ path: join(SHOTS, 'ai-2-answer.png') }); }); await step('마피아 연습: 컴퓨터 말이 모델에서 나온다', async () => { await a.goto(`${ORIGIN}/g/mafia`); await a.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click(); await a.waitForURL(/\/r\/\d{6}$/); await a.getByLabel('자리').getByText('컴퓨터 5').waitFor(); await a.getByRole('button', { name: '▶ 게임 시작' }).click(); await a.waitForFunction(() => document.querySelectorAll('.mf-msgs .mf-msg:not(.sys)').length >= 3, null, { timeout: 60_000 }); const lines = (await a.locator('.mf-msgs .mf-msg:not(.sys)').allInnerTexts()).map((l) => l.replace(/\n/g, ' ')); console.log(' mafia chat:', lines.join(' | ')); const texts = lines.map((l) => l.replace(/^컴퓨터 \d\s*/, '')); if (texts.every((t) => BUILT_IN.test(t))) throw new Error('only built-in lines'); await a.screenshot({ path: join(SHOTS, 'ai-3-mafia.png') }); }); console.log(' ai stats:', JSON.stringify((await (await fetch(`${ORIGIN}/healthz`)).json()).ai)); if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`); } catch (e) { failed = true; console.error(e); } finally { await browser.close(); app.stop?.(); console.log(failed ? 'E2E FAILED' : 'E2E PASSED'); process.exit(failed ? 1 : 0); }