Files
game_voice_recorder/app/src/renderer/mock-gvr.ts

641 lines
28 KiB
TypeScript

// 브라우저 개발/스크린샷용 가짜 GvrApi. window.gvr 가 없을 때만 쓴다.
// URL 옵션: ?first=1 (첫 실행 · 마법사), ?nogpu=1 (GPU 없음), ?empty=1 (봇 토큰 없음), ?dl=0.6 (다운로드 시작 위치 비율)
// ?login=signed_out|not_registered|error (로그인 화면), ?role=superadmin|admin|user (기본 superadmin)
import type { AppRole, AppUserRow, User } from '@gvr/shared';
import type { DiagItem } from '../core/diagnostics';
import type { Settings } from '../core/settings';
import type { AppState, AuthView, DownloadProgress, FinetuneStatus, GvrApi, ModelsInfo } from '../main/api-types';
import { MODEL_META } from './models-meta';
import { deepMerge, sleep } from './util';
const MB = 1024 * 1024;
function defaults(): Settings {
return {
version: 1,
firstRunDone: false,
discord: {
botMode: 'builtin',
guildId: null,
followUserId: null,
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
ttsRate: 1,
},
games: { valorant: true, lol: true, lolLogsDir: null },
stt: {
realtimeModel: 'large-v3-turbo',
preciseModel: 'large-v3',
device: 'cuda',
computeType: 'float16',
modelsDir: null,
reprocessAfterMatch: true,
gameVramReserveMb: 3072,
gameSaver: true,
},
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
dictionary: {
packs: { valorant: true, valorant_callouts: true, lol: true, lol_skills: true, game: true, daily: true, university: true, slang20s: true },
applySiteCorrections: true,
},
storage: { audioDir: null, retentionDays: 7 },
site: { serverUrl: 'https://gvr.tkrmagid.kr', deviceId: null, deviceName: 'GAME-PC' },
general: { autoStart: false, sfx: true },
finetune: { schedule: 'off', activeModel: null, previousModel: null },
};
}
/** 0.6초짜리 "띵-동" WAV (미리듣기 대용) */
function beepWav(): string {
const rate = 16000;
const n = Math.floor(rate * 0.6);
const buf = new DataView(new ArrayBuffer(44 + n * 2));
const str = (o: number, s: string) => [...s].forEach((c, i) => buf.setUint8(o + i, c.charCodeAt(0)));
str(0, 'RIFF');
buf.setUint32(4, 36 + n * 2, true);
str(8, 'WAVEfmt ');
buf.setUint32(16, 16, true);
buf.setUint16(20, 1, true);
buf.setUint16(22, 1, true);
buf.setUint32(24, rate, true);
buf.setUint32(28, rate * 2, true);
buf.setUint16(32, 2, true);
buf.setUint16(34, 16, true);
str(36, 'data');
buf.setUint32(40, n * 2, true);
for (let i = 0; i < n; i++) {
const f = i < n / 2 ? 880 : 660;
const env = Math.sin((Math.PI * (i % (n / 2))) / (n / 2));
buf.setInt16(44 + i * 2, Math.sin((2 * Math.PI * f * i) / rate) * 9000 * env, true);
}
let bin = '';
const bytes = new Uint8Array(buf.buffer);
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
return 'data:audio/wav;base64,' + btoa(bin);
}
export function createMockGvr(): GvrApi {
const q = new URLSearchParams(location.search);
const first = q.has('first');
const noToken = first || q.has('empty');
const noGpu = q.has('nogpu');
const dlStart = Math.min(0.95, Math.max(0, Number(q.get('dl') ?? 0) || 0));
const now = Date.now();
const settings = defaults();
settings.firstRunDone = !first;
if (q.has('custom')) settings.discord.botMode = 'custom';
if (!noToken) {
settings.discord.guildId = 'g1';
settings.discord.followUserId = 'u1';
settings.site.deviceId = 'dev_8f2c';
}
const role = (q.get('role') as AppRole) || 'superadmin';
const me = { id: '293719842274541579', name: role === 'user' ? '민준' : '사금향', avatar: null };
const login = q.get('login');
const auth: AuthView = {
status: login === 'signed_out' || login === 'not_registered' || login === 'error' ? login : 'ok',
user: login === 'not_registered' ? { id: '987654321098765432', name: '모르는사람', avatar: null } : login ? null : me,
role: login ? null : role,
offline: false,
error: login === 'error' ? '사이트 서버에 연결할 수 없습니다 (fetch failed)' : null,
loginUrl: null,
verifiedAt: login ? null : now,
appReady: !login,
appError: null,
version: '1.2.0',
serverUrl: 'https://gvr.tkrmagid.kr',
};
const authListeners = new Set<(s: AuthView) => void>();
const emitAuth = () => authListeners.forEach((l) => l(structuredClone(auth)));
const displayNames: Record<string, string> = { '100000000000000003': '지호' };
let adminRows: AppUserRow[] = [
{ id: '293719842274541579', name: '사금향', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 60000, lastVersion: '1.2.0' },
{ id: '1352267557213573160', name: '두번째관리자', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 3 * 86400000, lastVersion: '1.2.0' },
{ id: '401234567890123456', name: '서연', avatar: null, role: 'admin', fixed: false, addedBy: '293719842274541579', addedAt: now - 5 * 86400000, lastSeenAt: now - 2 * 3600000, lastVersion: '1.2.0' },
{ id: '402345678901234567', name: '민준', avatar: null, role: 'user', fixed: false, addedBy: '293719842274541579', addedAt: now - 4 * 86400000, lastSeenAt: now - 20 * 60000, lastVersion: '1.2.0' },
{ id: '403456789012345678', name: '지호', avatar: null, role: 'user', fixed: false, addedBy: '293719842274541579', addedAt: now - 86400000, lastSeenAt: null, lastVersion: null },
];
const adminCheck = (lvl: 'admin' | 'superadmin') => {
if (lvl === 'superadmin' ? role !== 'superadmin' : role === 'user') throw new Error(lvl === 'superadmin' ? '유저 등록은 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다');
};
const state: AppState = {
account: { user: me, role, offline: false },
version: '1.2.0',
dataDir: 'D:\\겜녹이\\GVR-Data',
portable: true,
settings,
builtinBot: !q.has('nobuiltin'),
secrets: { botToken: !noToken, riotApiKey: false, deviceKey: !noToken },
secretCodec: 'dpapi',
bot: noToken
? { status: 'off', error: null, user: null, guild: null, guilds: [], recording: { active: false, channel: null, channelId: null, since: null, participants: [], reason: null } }
: {
status: 'ready',
error: null,
user: { id: 'b1', name: '겜녹이#4821', avatar: null },
guild: { id: 'g1', name: '우리 겜방', icon: null },
guilds: [{ id: 'g1', name: '우리 겜방' }],
recording: { active: true, channel: '🎮 발로란트', channelId: 'c1', since: now - 23 * 60000, participants: ['민준', '서연', '지호'], reason: 'follow' },
},
worker: { ready: true, lastError: null },
stt: {
worker: 'ready',
slots: { realtime: { model: 'large-v3-turbo', state: first ? 'missing' : 'loaded' }, precise: { model: 'large-v3', state: 'empty' } },
queue: 0,
processing: null,
device: 'cuda:0',
lastError: null,
},
relay: noToken
? { state: 'off', error: null, since: null, serverUrl: null }
: { state: 'online', error: null, since: now - 3600000, serverUrl: 'https://gvr.tkrmagid.kr' },
games: {
valorant: { connected: true, inMatch: false, detail: 'Riot Client 연결됨 · 대기실' },
lol: { connected: false, inMatch: false, detail: '클라이언트 꺼짐' },
},
liveGames: [
{
game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null,
startedAt: now - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null,
self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: now,
},
{
game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null,
startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null,
history: q.has('nohistory') ? null : { phase: 'fetch', first: true, scanned: 140, done: 37, total: 120, startedAt: now - 40000, etaMs: 90000 }, updatedAt: now,
},
],
counts: { utterances: 1824, matches: 37 },
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
autoStart: false,
};
const models: ModelsInfo = {
models: Object.entries(MODEL_META).map(([name, m]) => ({
name,
repo: name,
size_mb: m.sizeMb,
installed: !first && name === 'large-v3-turbo',
})),
cuda_runtime: { installed: !first, size_mb: 1210 },
};
const users: User[] = [
{ id: 'u1', name: '민준', color: '#3987e5', avatar: null, excluded: false, riot: [{ puuid: 'p1', riotId: '민준#KR1' }] },
{ id: 'u2', name: '서연', color: '#e5743f', avatar: null, excluded: false, riot: [{ puuid: 'p2', riotId: '서연이#0505' }, { puuid: 'p2b', riotId: '서연부캐#KR2' }] },
{ id: 'u3', name: '지호', color: '#1fb383', avatar: null, excluded: false, riot: [] },
{ id: 'u4', name: '현우', color: '#c98500', avatar: null, excluded: true, riot: [{ puuid: 'p4', riotId: 'HW#7777' }] },
];
let dictId = 100;
const dict = {
labels: { site: '사이트 교정', user: '사용자 단어', valorant: '발로란트', lol: '리그 오브 레전드' } as Record<string, string>,
packs: [
{ key: 'valorant', label: '발로란트', count: 288 },
{ key: 'valorant_callouts', label: '발로란트 콜아웃', count: 101 },
{ key: 'lol', label: '리그 오브 레전드', count: 412 },
{ key: 'lol_skills', label: '롤 스킬 이름', count: 850 },
{ key: 'game', label: '게임 공통', count: 104 },
{ key: 'daily', label: '일상', count: 93 },
{ key: 'university', label: '대학생', count: 76 },
{ key: 'slang20s', label: '20대 말투', count: 69 },
],
entries: [
{ id: 1, word: '레이즈', from: '레이저', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: true, hits: 41 },
{ id: 2, word: 'B 사이트', from: '비 싸이트', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: true, hits: 17 },
{ id: 3, word: '제트', from: '젯트', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: true, hits: 9 },
{ id: 4, word: '바론', from: '바롱', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: false, hits: 0 },
{ id: 5, word: '민준', from: '민중', kind: 'correction' as const, pack: 'site', source: 'site', enabled: true, hits: 12 },
{ id: 6, word: '서연이', from: '서여니', kind: 'correction' as const, pack: 'site', source: 'site', enabled: true, hits: 5 },
{ id: 7, word: '한타', from: '한따', kind: 'correction' as const, pack: 'user', source: 'user', enabled: true, hits: 3 },
{ id: 8, word: '민준', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
{ id: 9, word: '서연이', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
{ id: 10, word: '헤드 원탭', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
{ id: 11, word: '조별과제', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
],
};
const ft: FinetuneStatus = first
? { toolsInstalled: false, installing: false, running: false, stage: null, step: null, total: null, samples: 0, lastResult: null, activeModel: null, previousModel: null, log: [] }
: {
toolsInstalled: true,
installing: false,
running: false,
stage: null,
step: null,
total: null,
samples: 342,
lastResult: { cer_before: 0.142, cer_after: 0.097, adopt: true, model: 'turbo-ft-1012', at: now - 2 * 86400000 },
activeModel: 'turbo-ft-1012',
previousModel: 'large-v3-turbo',
log: [
'[03:00:02] 학습 데이터 342문장 (교정 118 + 합성 224)',
'[03:00:40] LoRA r=32 · lr 1e-4 · 3 epoch',
'[03:41:15] 검증 CER 14.2% → 9.7%',
'[03:43:02] CTranslate2 변환 완료 → turbo-ft-1012',
'[03:43:03] 새 모델 채택 (이전 모델 보관)',
],
};
const listeners = new Set<(s: AppState) => void>();
const progressL = new Set<(p: DownloadProgress) => void>();
const diagL = new Set<(it: DiagItem) => void>();
const emit = () => {
const snap = structuredClone(state);
listeners.forEach((l) => l(snap));
};
// 녹음 참가자/대기열이 조금씩 바뀌는 흉내
setInterval(() => {
state.stt.queue = Math.random() < 0.7 ? 0 : Math.floor(Math.random() * 3);
emit();
}, 4000);
const api: GvrApi = {
async authState() {
await sleep(60);
return structuredClone(auth);
},
onAuth(cb) {
authListeners.add(cb);
return () => authListeners.delete(cb);
},
async authLogin() {
Object.assign(auth, { status: 'waiting', loginUrl: 'https://gvr.tkrmagid.kr/auth/app/start/mock', error: null });
emitAuth();
await sleep(2500);
if (auth.status !== 'waiting') return structuredClone(auth);
Object.assign(auth, { status: 'ok', user: me, role, loginUrl: null, appReady: true, verifiedAt: Date.now() });
emitAuth();
return structuredClone(auth);
},
async authCancel() {
Object.assign(auth, { status: 'signed_out', loginUrl: null });
emitAuth();
},
async authLogout() {
Object.assign(auth, { status: 'signed_out', user: null, role: null, appReady: false, error: null });
emitAuth();
},
async authRecheck() {
await sleep(600);
return structuredClone(auth);
},
async adminUsers() {
await sleep(200);
adminCheck('admin');
return { users: structuredClone(adminRows) };
},
async adminAddUser(id, r) {
await sleep(400);
adminCheck('superadmin');
if (!/^\d{17,20}$/.test(id.trim())) throw new Error('디스코드 아이디는 17~20자리 숫자입니다');
if (adminRows.some((u) => u.id === id.trim())) adminRows = adminRows.map((u) => (u.id === id.trim() && !u.fixed ? { ...u, role: r } : u));
else adminRows.push({ id: id.trim(), name: `새유저${adminRows.length}`, avatar: null, role: r, fixed: false, addedBy: me.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null });
return { users: structuredClone(adminRows) };
},
async adminSetRole(id, r) {
await sleep(200);
adminCheck('superadmin');
adminRows = adminRows.map((u) => (u.id === id && !u.fixed ? { ...u, role: r } : u));
return { users: structuredClone(adminRows) };
},
async adminDisplayNames() {
await sleep(150);
return { ...displayNames };
},
async adminSetDisplayName(id, name) {
await sleep(150);
adminCheck('superadmin');
if (name.trim()) displayNames[id] = name.trim();
else delete displayNames[id];
return { ...displayNames };
},
async adminRemoveUser(id) {
await sleep(200);
adminCheck('superadmin');
adminRows = adminRows.filter((u) => u.id !== id || u.fixed);
return { users: structuredClone(adminRows) };
},
async getState() {
await sleep(80);
return structuredClone(state);
},
onState(cb) {
listeners.add(cb);
return () => listeners.delete(cb);
},
async updateSettings(patch) {
state.settings = deepMerge(state.settings, patch);
emit();
return structuredClone(state.settings);
},
async setSecret(key, value) {
await sleep(150);
state.secrets[key] = !!value;
emit();
},
async testBotToken(token) {
// 실제 IPC 처럼 부를 때의 모드로 토큰을 고른다 (응답은 늦게 온다)
const noSaved = state.settings.discord.botMode === 'builtin' ? !state.builtinBot : !state.secrets.botToken;
await sleep(900);
if (token !== undefined && token.length < 20) return { ok: false, error: '토큰이 올바르지 않습니다 (401 Unauthorized)' };
if (token === undefined && noSaved) return { ok: false, error: '저장된 토큰이 없습니다' };
return {
ok: true,
bot: { id: 'b1', name: '겜녹이#4821', avatar: null },
guilds: [
{ id: 'g1', name: '우리 겜방' },
{ id: 'g2', name: '과제 스터디' },
],
};
},
async restartBot() {
if (state.settings.discord.botMode === 'builtin' ? !state.builtinBot : !state.secrets.botToken) {
state.bot = { ...state.bot, status: 'off', error: null, user: null, guild: null, guilds: [] };
emit();
return { ok: false, error: '봇 토큰이 없습니다' };
}
state.bot.status = 'connecting';
emit();
await sleep(900);
state.bot = {
...state.bot,
status: 'ready',
error: null,
user: { id: 'b1', name: '겜녹이#4821', avatar: null },
guilds: [
{ id: 'g1', name: '우리 겜방' },
{ id: 'g2', name: '과제 스터디' },
],
guild: state.settings.discord.guildId === 'g2' ? { id: 'g2', name: '과제 스터디', icon: null } : { id: 'g1', name: '우리 겜방', icon: null },
};
emit();
return { ok: true };
},
async guildMembers() {
await sleep(300);
return [
{ id: 'u1', name: '민준', avatar: null, bot: false, me: true, admin: true },
{ id: 'u3', name: '지호', avatar: null, bot: false, me: false, admin: true },
{ id: 'u2', name: '서연', avatar: null, bot: false, me: false, admin: false },
{ id: 'u4', name: '현우', avatar: null, bot: false, me: false, admin: false },
{ id: 'b1', name: '겜녹이', avatar: null, bot: true, me: false, admin: false },
{ id: 'b2', name: 'MEE6', avatar: null, bot: true, me: false, admin: false },
];
},
async previewTts() {
await sleep(500);
return { ok: true, dataUrl: beepWav() };
},
async gpuInfo() {
await sleep(250);
if (noGpu) return null;
return {
gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070 Ti', vram_total_mb: 16303, vram_used_mb: 1180, driver: '581.42', cuda_driver: '13.0', compute_capability: '12.0' }],
recommend: {
realtime: 'large-v3-turbo',
precise: 'large-v3',
compute_type: 'float16',
budget_mb: 13231,
reason: 'VRAM 16GB에서 게임 예약 3GB를 빼도 실시간·정밀 모델을 함께 둘 수 있습니다',
supported: true,
warning: null,
precise_after_match: true,
},
};
},
async models() {
await sleep(150);
return structuredClone(models);
},
async download(target, name) {
const key = target === 'cuda_runtime' ? 'cuda_runtime' : `model:${name}`;
const total = target === 'cuda_runtime' ? 1210 : (models.models.find((m) => m.name === name)?.size_mb ?? 1000);
let done = total * dlStart;
while (done < total) {
await sleep(250);
const speed = 34 + Math.random() * 8;
done = Math.min(total, done + speed * 0.25);
const p: DownloadProgress = { key, done_mb: done, total_mb: total, speed_mbps: speed, eta_s: (total - done) / speed, state: 'running', stage: target === 'cuda_runtime' ? 'cuBLAS · cuDNN' : 'model.bin' };
progressL.forEach((l) => l(p));
}
if (target === 'cuda_runtime') models.cuda_runtime.installed = true;
else {
const m = models.models.find((x) => x.name === name);
if (m) m.installed = true;
}
progressL.forEach((l) => l({ key, done_mb: total, total_mb: total, state: 'done' }));
return { ok: true };
},
onProgress(cb) {
progressL.add(cb);
return () => progressL.delete(cb);
},
async deleteModel(name) {
await sleep(300);
const m = models.models.find((x) => x.name === name);
if (m) m.installed = false;
return { ok: true };
},
async applyModels() {
state.stt.slots.realtime = { model: state.settings.stt.realtimeModel, state: 'loading' };
emit();
await sleep(1200);
state.stt.slots.realtime.state = 'loaded';
state.stt.slots.precise = { model: state.settings.stt.preciseModel, state: 'empty' };
emit();
},
async chooseFolder(_title, defaultPath) {
await sleep(200);
return defaultPath ? defaultPath.replace(/[^\\]*$/, '') + '새 폴더' : 'D:\\GameVoiceRecorder\\models';
},
async registerDevice(code) {
await sleep(800);
if (code.trim().length < 6) return { ok: false, error: '코드가 맞지 않거나 만료되었습니다' };
state.settings.site.deviceId = 'dev_' + Math.random().toString(16).slice(2, 6);
state.secrets.deviceKey = true;
state.relay = { state: 'connecting', error: null, since: null, serverUrl: state.settings.site.serverUrl };
emit();
setTimeout(() => {
state.relay = { state: 'online', error: null, since: Date.now(), serverUrl: state.settings.site.serverUrl };
emit();
}, 900);
return { ok: true };
},
async unregisterDevice() {
await sleep(300);
state.settings.site.deviceId = null;
state.secrets.deviceKey = false;
state.relay = { state: 'off', error: null, since: null, serverUrl: null };
emit();
},
async runDiagnostics() {
const items: DiagItem[] = [
{ id: 'os', label: '운영체제', ok: true, detail: 'Windows 11 Pro 24H2 (x64)' },
{ id: 'gpu', label: 'GPU', ok: !noGpu, detail: noGpu ? 'NVIDIA GPU를 찾지 못했습니다' : 'NVIDIA GeForce RTX 5070 Ti · VRAM 16GB · 드라이버 581.42' },
{ id: 'cuda', label: 'CUDA 런타임', ok: models.cuda_runtime.installed, detail: models.cuda_runtime.installed ? 'cuBLAS 12.8 · cuDNN 9.5 로드됨' : '설치되지 않음 (STT 모델 탭에서 다운로드)' },
{ id: 'worker', label: 'STT 엔진', ok: true, detail: 'gvr-worker 1.0.0 · faster-whisper 1.2 · CTranslate2 4.6' },
{ id: 'stt', label: 'STT 속도', ok: true, detail: 'large-v3-turbo · 5초 음성 0.41초 (RTF 0.08)' },
{ id: 'discord', label: '디스코드 봇', ok: state.bot.status === 'ready', detail: state.bot.status === 'ready' ? '겜녹이#4821 · 음성 · 슬래시 명령 권한 정상' : '봇이 연결되지 않았습니다' },
{ id: 'tts', label: 'TTS 안내 음성', ok: true, detail: 'Edge TTS 응답 0.6초' },
{ id: 'valorant', label: '발로란트 로컬 API', ok: true, detail: 'Riot Client 연결됨 (lockfile)' },
{ id: 'lol', label: '롤 Live Client API', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'relay', label: '사이트 서버', ok: state.relay.state === 'online', detail: state.relay.state === 'online' ? 'gvr.tkrmagid.kr 연결됨 · 왕복 38ms' : '등록되지 않음' },
{ id: 'disk', label: '저장 공간', ok: true, detail: 'D: 여유 412GB' },
];
const out: DiagItem[] = [];
for (const it of items) {
await sleep(280);
out.push(it);
diagL.forEach((l) => l(it));
}
return out;
},
onDiag(cb) {
diagL.add(cb);
return () => diagL.delete(cb);
},
async storageUsage() {
await sleep(200);
return { audioBytes: 412 * MB, trainingBytes: 96 * MB, dbBytes: 38 * MB, modelsBytes: 4.6 * 1024 * MB, freeBytes: 412 * 1024 * MB };
},
async runRetention() {
await sleep(900);
return { deleted: 37, freedBytes: 52 * MB };
},
async users() {
await sleep(150);
return structuredClone(users);
},
async setRiotIds(userId, riotIds) {
await sleep(150);
const u = users.find((x) => x.id === userId);
if (u) u.riot = riotIds.map((r, i) => ({ puuid: `${userId}-${i}`, riotId: r }));
},
async cancelHistory(game) {
await sleep(150);
const cancelled: ('valorant' | 'lol')[] = [];
for (const g of state.liveGames ?? []) {
if (g.history && (!game || g.game === game)) {
g.history = null;
cancelled.push(g.game);
}
}
emit();
return { cancelled, resumeAt: cancelled.length ? Date.now() + 30 * 60000 : null };
},
async setExcluded(userId, excluded) {
const u = users.find((x) => x.id === userId);
if (u) u.excluded = excluded;
},
async dictionary() {
await sleep(150);
return structuredClone(dict);
},
async addWord(word) {
dict.entries.push({ id: ++dictId, word, from: null, kind: 'hotword', pack: 'user', source: 'user', enabled: true, hits: 0 });
},
async addCorrection(from, to) {
dict.entries.push({ id: ++dictId, word: to, from, kind: 'correction', pack: 'user', source: 'user', enabled: true, hits: 0 });
},
async deleteDict(id) {
dict.entries = dict.entries.filter((e) => e.id !== id);
},
async setDictEnabled(id, enabled) {
const e = dict.entries.find((x) => x.id === id);
if (e) e.enabled = enabled;
},
async finetuneStatus() {
return structuredClone(ft);
},
async finetuneInstall() {
ft.installing = true;
ft.log.push('[설치] PyTorch · PEFT 내려받는 중');
setTimeout(() => {
ft.installing = false;
ft.toolsInstalled = true;
ft.log.push('[설치] 완료');
}, 4000);
return { ok: true };
},
async finetuneStart() {
if (ft.samples < 50) return { ok: false, error: '학습 문장이 부족합니다 (최소 50문장)' };
ft.running = true;
ft.stage = '학습';
ft.step = 0;
ft.total = 300;
ft.log.push('[학습] 시작');
const t = setInterval(() => {
if (!ft.running) return clearInterval(t);
ft.step = Math.min(300, (ft.step ?? 0) + 12);
if (ft.step >= 300) {
ft.running = false;
ft.stage = null;
ft.log.push('[학습] 완료 · CER 9.7% → 9.1% · 채택');
ft.lastResult = { cer_before: 0.097, cer_after: 0.091, adopt: true, model: 'turbo-ft-1015', at: Date.now() };
clearInterval(t);
}
}, 500);
return { ok: true };
},
async finetuneStop() {
ft.running = false;
ft.stage = null;
ft.log.push('[학습] 중지됨');
},
async finetuneRollback() {
await sleep(400);
if (!ft.previousModel) return { ok: false, error: '되돌릴 이전 모델이 없습니다' };
ft.activeModel = ft.previousModel;
ft.previousModel = null;
return { ok: true };
},
async clearTrainingData() {
await sleep(400);
ft.samples = 0;
},
async openExternal(url) {
window.open(url, '_blank');
},
async openPath(p) {
console.info('[mock] openPath', p);
},
async setAutoStart(on) {
state.autoStart = on;
state.settings.general.autoStart = on;
emit();
},
async finishWizard() {
await sleep(300);
state.settings.firstRunDone = true;
emit();
},
async recentLogs() {
await sleep(150);
return [
'2026-10-15 21:02:11 INFO bot 준비 완료: 겜녹이#4821 (서버 1곳)',
'2026-10-15 21:02:12 INFO worker STT 엔진 시작 · cuda:0 · large-v3-turbo float16',
'2026-10-15 21:02:15 INFO relay 사이트 서버 연결됨 (gvr.tkrmagid.kr)',
'2026-10-15 21:05:40 INFO bot 민준 님을 따라 🎮 발로란트 입장 · TTS 안내',
'2026-10-15 21:05:41 INFO recorder 녹음 시작 (참가자 3명)',
'2026-10-15 21:09:03 INFO bot 현우: /녹음제외',
'2026-10-15 21:12:30 INFO games 발로란트 경기 시작 · 어센트 · 경쟁전',
'2026-10-15 21:14:02 WARN stt 대기열 4건 (경기 중 · 낮은 우선순위)',
'2026-10-15 21:25:44 INFO stt utt_8c1f → "B 사이트 레이즈 둘" (0.38초)',
];
},
async quit() {
console.info('[mock] quit');
},
};
return api;
}