- 따라갈 사람: 봇이 서버를 지켜보기 전 멤버 요청을 사이트 서버가 forbidden 으로 거절하고 앱이 오류를 숨겨 빈 목록이 됐다 → 가입한 서버면 지켜보기 전에도 응답(source.members 가 멤버 확인), 앱은 오류 · 다시 불러오기 표시 → 내 계정 → 관리자(GET /app/admins) → 이름순, 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜봄 - 롤 채팅 OCR 제거: 앱 설정 · 마법사 · 진단 · lol.ts · 워커 ocr.py/ocr_* op · pywinrt/mss/Pillow · win-ci ocr_lang 롤은 게임 중 전체/팀 채팅 API 가 없어 LCU(챔피언 선택 · 게임 후) + r3dlog(남아 있을 때, LCU 채팅을 지우지 않고 추가) - 표시 이름: 서버 store.displayNames (세션 · 앱 유저 · 접속 기록 이름까지 바꿈), GET /app/names, PUT /app/admin/names, cli name. 앱은 받아서 users · 지난 범인 분석 이름을 바꾸고 이후 디스코드 이름 대신 저장. 관리자 탭에 편집 UI - 저장소 시연 · 테스트 데이터 · 화면 캡처 · 계획서 PDF 의 실제 이름을 가짜 이름으로 교체 - 테스트: 앱 41 · 서버 16 · 워커 39 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
149 lines
8.6 KiB
TypeScript
149 lines
8.6 KiB
TypeScript
// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 헤드리스 브라우저.
|
|
// 외부 전적 사이트에는 접속하지 않는다 (기록 점수는 OP.GG 계산법을 따라 경기 기록으로 계산).
|
|
// 1) 발로란트 시연 경기 (22라운드 · 대화) 2) 롤 시연 경기 (10 · 15분 라인전 · 대화)
|
|
// 비용이 든다 (경기당 약 $0.1~0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
|
|
// node --import tsx scripts/culprit-real-e2e.mts [결과 폴더]
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import type { CulpritInput, CulpritMatchInfo } from '@gvr/shared';
|
|
import { makeDemoLol } from '../test/fixtures/demo-matches.ts';
|
|
import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts';
|
|
|
|
const outDir = process.argv[2] || path.join(os.homedir(), '.tmp', 'culprit-real');
|
|
fs.mkdirSync(outDir, { recursive: true });
|
|
const root = path.resolve(import.meta.dirname, '..', '..');
|
|
const apiKey = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.config/ejclaw/secrets.json'), 'utf8')).credentials['anthropic.api/game-voice-recorder'].token as string;
|
|
|
|
const core = setup();
|
|
await core.assets.refresh(true).catch(() => undefined);
|
|
const { id: valId } = seedValorant(core);
|
|
|
|
// ---------------------------------------------------------------- 롤 시연 경기 + 우리 팀 2명 대화
|
|
const LS = Date.now() - 80 * MIN;
|
|
const lol = makeDemoLol();
|
|
const lolId = 'lol-demo';
|
|
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('s-lol', 'g', 'c', '음성', LS - MIN);
|
|
core.games.matchStarted({ id: lolId, game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
|
|
core.games.matchEnded(lolId, LS + lol.durationMs);
|
|
(core.games.adapters[1] as any).applyHistory(lolId, lol.game, lol.timeline, LS);
|
|
const talk: [string, number, string][] = [
|
|
['u1', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
|
|
['u2', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
|
|
['u1', 8.1, '용 같이 하자 바텀 밀었어'],
|
|
['u2', 8.3, '아니 탑 갱 각이야 잠깐만'],
|
|
['u1', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
|
|
['u2', 15.1, '아 들어갔다 아 죽었다 미안'],
|
|
['u1', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
|
|
];
|
|
for (const [uid, min, text] of talk) {
|
|
const ts = LS + min * MIN;
|
|
const id = `lol-${uid}-${min}`;
|
|
core.store.insertUtterance({ id, session_id: 's-lol', user_id: uid, started_at: ts, ended_at: ts + 1800, audio_path: null, match_id: lolId });
|
|
core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'large-v3', status: 'precise' });
|
|
}
|
|
core.store.endSession('s-lol', LS + lol.durationMs + MIN);
|
|
|
|
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude)
|
|
const local = await culpritApi(core);
|
|
const { buildServer } = await import('../../site/server/src/app.ts');
|
|
const port = 18961;
|
|
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: 'real-e2e-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-real-')), 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, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' },
|
|
});
|
|
site.app.log.level = 'info';
|
|
await site.app.listen({ host: '127.0.0.1', port });
|
|
const base = `http://127.0.0.1:${port}`;
|
|
const code = site.store.createCode('real');
|
|
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();
|
|
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
|
|
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
|
|
const cookieHeader = `gvr_sid=${encodeURIComponent(site.app.signCookie(sess.token))}`;
|
|
|
|
const stages: Record<string, string[]> = {};
|
|
// 진행 단계 기록 (실시간 알림을 가로챈다)
|
|
const pub = site.hub.publish.bind(site.hub);
|
|
site.hub.publish = (e: any) => {
|
|
if (e.type === 'culprit.progress') (stages[e.data.matchId] ||= []).push(`${e.data.stage}${e.data.message ? `(${e.data.message})` : ''}`);
|
|
pub(e);
|
|
};
|
|
|
|
async function analyze(matchId: string) {
|
|
const input = (await local.inject({ url: `/api/culprit/internal/${matchId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
|
|
fs.writeFileSync(path.join(outDir, `${matchId}.input.txt`), input.text);
|
|
const t0 = Date.now();
|
|
const r = await fetch(`${base}/api/culprit/matches/${matchId}/analyze`, { method: 'POST', headers: { cookie: cookieHeader, 'content-type': 'application/json' }, body: '{}' });
|
|
if (r.status !== 202) throw new Error(`analyze ${r.status} ${await r.text()}`);
|
|
for (;;) {
|
|
await new Promise((res) => setTimeout(res, 3000));
|
|
const info = (await (await fetch(`${base}/api/culprit/matches/${matchId}`, { headers: { cookie: cookieHeader } })).json()) as CulpritMatchInfo;
|
|
if (info.analysis) return { info, ms: Date.now() - t0 };
|
|
if (Date.now() - t0 > 10 * MIN) throw new Error('10분 안에 끝나지 않음');
|
|
const b = await (await fetch(`${base}/api/culprit/budget`, { headers: { cookie: cookieHeader } })).json();
|
|
if (!b.running.includes(matchId)) {
|
|
// 실패
|
|
throw new Error(`분석 실패: ${JSON.stringify(stages[matchId] ?? [])}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const report: any = {};
|
|
for (const id of [valId, lolId]) {
|
|
console.log(`\n=== ${id} 분석 시작`);
|
|
const { info, ms } = await analyze(id);
|
|
const a = info.analysis!;
|
|
fs.writeFileSync(path.join(outDir, `${id}.result.json`), JSON.stringify(a, null, 1));
|
|
const ref = (pid: string) => a.players.find((p) => p.id === pid)!;
|
|
const rows = a.result.players.map((p) => {
|
|
const pl = ref(p.id);
|
|
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, lane: pl.rating?.lane ?? null, tag: p.tag, comment: p.comment };
|
|
});
|
|
const teamLowest = (team: string, key: 'rating') => {
|
|
const ps = rows.filter((r) => r.team === team && r[key] !== null);
|
|
return ps.length ? ps.reduce((x, y) => ((x[key] as number) <= (y[key] as number) ? x : y)).id : null;
|
|
};
|
|
report[id] = {
|
|
seconds: Math.round(ms / 1000),
|
|
model: a.model,
|
|
costUsd: a.meta.costUsd,
|
|
usage: a.meta.usage,
|
|
stages: stages[id],
|
|
summary: a.result.summary,
|
|
confidence: a.result.confidence,
|
|
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating') })),
|
|
players: rows,
|
|
};
|
|
console.log(JSON.stringify(report[id], null, 1));
|
|
}
|
|
fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(report, null, 1));
|
|
|
|
// ---------------------------------------------------------------- 화면
|
|
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({ name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base });
|
|
const errs: string[] = [];
|
|
page.on('pageerror', (e: any) => errs.push(e.message));
|
|
for (const [id, name] of [[valId, 'real-val.png'], [lolId, 'real-lol.png']] as const) {
|
|
await page.setViewport({ width: 1440, height: 2000 });
|
|
await page.goto(`${base}/culprit/${id}`, { waitUntil: 'networkidle2' });
|
|
await page.waitForSelector('.cu-card', { timeout: 20000 });
|
|
await new Promise((r) => setTimeout(r, 1500));
|
|
await page.screenshot({ path: path.join(outDir, name), fullPage: true });
|
|
}
|
|
console.log('\n화면 오류:', errs);
|
|
await browser.close();
|
|
rc.stop();
|
|
await site.app.close();
|
|
await local.close();
|
|
console.log('결과:', outDir);
|