// 범인찾기 화면 확인: 실제 앱 코어(범인찾기 · 기록 DB) + 실제 사이트 서버 + 헤드리스 브라우저. // AI 는 부르지 않는다: CULPRIT_ANSWER(JSON 파일)를 AI 답으로 돌려준다 (없으면 기본 답 생성). // [SCALE=2] node --import tsx scripts/culprit-shots.mts [답.json] [스크린샷 폴더] import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import type { CulpritInput } from '@gvr/shared'; import { makeDemoLol } from '../test/fixtures/demo-matches.ts'; import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts'; const answerFile = process.argv[2]; const shotDir = process.argv[3] || path.join(os.homedir(), '.tmp', 'culprit-shots'); const root = path.resolve(import.meta.dirname, '..', '..'); const core = setup(); await core.assets.refresh(true); const { id: valId } = seedValorant(core); // 롤 경기 (음성 2명) const LS = Date.now() - 80 * MIN; const lol = makeDemoLol(); core.store.setMeta('riot_self_puuid', 'l-sh'); core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]); core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]); core.store.startSession('s2', 'g', 'c', '음성', LS - MIN); core.games.matchStarted({ id: 'lol-demo', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } }); core.games.matchEnded('lol-demo', LS + lol.durationMs); (core.games.adapters[1] as any).applyHistory('lol-demo', lol.game, lol.timeline, LS); for (const [uid, min, text] of [['u2', 8.1, '용 같이 하자 바텀 밀었어'], ['u1', 8.3, '아니 탑 갱 각이야 잠깐만']] as const) { const ts = LS + min * MIN; const id = `lol-${uid}-${min}`; core.store.insertUtterance({ id, session_id: 's2', user_id: uid, started_at: ts, ended_at: ts + 1500, audio_path: null, match_id: 'lol-demo' }); core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'small', status: 'precise' }); } core.store.endSession('s2', LS + lol.durationMs + MIN); // 녹음이 늦게 시작한 경기 (기록 부족 표시용) core.store.upsertMatch({ id: 'val-late', game: 'valorant', started_at: Date.now() - 30 * 3600_000, ended_at: Date.now() - 29.3 * 3600_000, status: 'complete', map: '/Game/Maps/Bonsai/Bonsai', queue: 'competitive', mode: 'competitive', result: JSON.stringify({ win: true, score: { ally: 13, enemy: 10 } }), detail: JSON.stringify({ players: [{}, {}], roundsDetail: [{}] }) }); core.store.startSession('s3', 'g', 'c', null, Date.now() - 30 * 3600_000 + 12 * MIN); core.store.endSession('s3', Date.now() - 29 * 3600_000); const local = await culpritApi(core); const saved = answerFile && fs.existsSync(answerFile) ? JSON.parse(fs.readFileSync(answerFile, 'utf8')) : null; const fakeAnswer = (input: CulpritInput) => ({ summary: '초반 드래곤 세 개를 내줘 끌려갔지만 바론 앞 한타를 뒤집어 이겼다.', confidence: 'medium', confidence_note: '시연 데이터라 기록이 단순하다.', teams: [ { team: 'ally', culprit: 'P2', reason: '드래곤 앞 교전에서 시야 없이 싸우다 내줬고, 용 콜이 있었는데 탑 갱을 고집했다.', evidence: Object.keys(input.refs).filter((k) => k.startsWith('u') || k === 'e3').slice(0, 3).map((ref) => ({ ref, note: '근거' })).concat([{ ref: 's:P2', note: '킬 관여 낮음' }]) }, { team: 'enemy', culprit: 'P10', reason: '레오나로 이니시를 열지 못하고 한타 직전에 먼저 잡혔다.', evidence: [{ ref: 's:P10', note: '데스 많음' }] }, ], players: input.players.map((p, i) => ({ id: p.id, score: p.id === 'P2' ? 4 : p.id === 'P10' ? 3 : 6 + (i % 4), tag: p.id === 'P2' || p.id === 'P10' ? '범인' : i === 0 ? '캐리' : '무난', comment: '한 줄 평 예시.', evidence: [] })), }); const { buildServer } = await import('../../site/server/src/app.ts'); const { KnowledgeAuto } = await import('../../site/server/src/culprit-prompt.ts'); const port = 18960; const site = await buildServer( { port, host: '127.0.0.1', publicUrl: `http://127.0.0.1:${port}`, clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: ['u1'], superAdmins: ['u1'], sessionSecret: 'demo-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-cs-')), webDir: path.join(root, 'site', 'web', 'dist'), version: 't', discordApi: 'http://127.0.0.1:1', assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' }, culprit: { apiKey: 'x', model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' }, }, { culpritKnowledge: new KnowledgeAuto(async () => { throw new Error('offline'); }), culpritCall: async (req) => { await new Promise((r) => setTimeout(r, 2500)); const isVal = req.user.includes('# 경기 발로란트'); const input = (await local.inject({ url: `/api/culprit/internal/${isVal ? valId : 'lol-demo'}/input`, headers: { 'x-gvr-internal': '1' } })).json().input; return { text: JSON.stringify(isVal && saved ? saved : fakeAnswer(input)), stopReason: 'end_turn', usages: [{ model: 'claude-opus-5-5', input: 26077, output: 13997, cacheRead: 0, cacheWrite: 0 }], fallback: false }; }, }, ); site.app.log.level = 'warn'; await site.app.listen({ host: '127.0.0.1', port }); const base = `http://127.0.0.1:${port}`; const code = site.store.createCode('demo'); const reg = site.store.redeem(code.code, 'GAME-PC')!; const { RelayClient } = await import('../src/core/relay/client.ts'); const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: 'g' })); rc.start(); // 사이트 화면은 /api/overview · /api/users 도 부른다 while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100)); const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null }); const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base }; const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default; const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox', '--lang=ko-KR'] }); const page = await browser.newPage(); await page.setCookie(cookie); const errs: string[] = []; page.on('pageerror', (e: any) => errs.push(e.message)); page.on('console', (m: any) => m.type() === 'error' && errs.push(m.text())); const csp: string[] = []; await page.exposeFunction('__csp', (v: string) => csp.push(v)); await page.evaluateOnNewDocument(() => document.addEventListener('securitypolicyviolation', (e) => (window as any).__csp(`${e.violatedDirective} ${e.blockedURI}`))); fs.mkdirSync(shotDir, { recursive: true }); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const SCALE = Number(process.env.SCALE || 1); const shot = async (name: string, w = 1440, h = 900, full = false) => { await page.setViewport({ width: w, height: h, deviceScaleFactor: SCALE }); await sleep(600); await page.screenshot({ path: path.join(shotDir, name), fullPage: full }); console.log('screenshot', name); }; await page.setViewport({ width: 1440, height: 900 }); await page.goto(`${base}/culprit/${valId}`, { waitUntil: 'networkidle2' }); await sleep(1500); await shot('1-list.png', 1440, 1100); await page.click('.cu-btn'); await sleep(1200); await shot('2-progress.png'); await page.waitForSelector('.cu-card', { timeout: 20000 }); await sleep(1200); await shot('3-result-val.png', 1440, 1900); await shot('4-result-mobile.png', 390, 3200); await page.setViewport({ width: 1440, height: 900 }); await page.goto(`${base}/culprit/lol-demo`, { waitUntil: 'networkidle2' }); await sleep(1200); await page.click('.cu-btn'); await page.waitForSelector('.cu-card', { timeout: 20000 }); await sleep(1200); await shot('5-result-lol.png', 1440, 1900); await page.goto(`${base}/culprit/val-late`, { waitUntil: 'networkidle2' }); await sleep(1200); await shot('6-blocked.png'); await page.goto(`${base}/matches/${valId}`, { waitUntil: 'networkidle2' }); await sleep(800); const hasBtn = await page.evaluate(() => [...document.querySelectorAll('.crumbs a')].some((a) => a.textContent?.includes('범인 보기'))); console.log('경기 화면 범인 보기 버튼', hasBtn); console.log('브라우저 오류:', errs.filter((e) => !/favicon/.test(e))); console.log('CSP 위반:', csp.length ? csp : '없음'); await browser.close(); rc.stop(); await site.app.close(); await local.close(); process.exit(0);