종료 시 'Tray is destroyed' 오류 창: 트레이 · 상태 갱신 타이머를 멈추고 트레이를 비운 뒤 없앤다 · Electron 이 먼저 없앤 트레이도 건드리지 않음 · 종료 중 STT 는 새 작업을 꺼내지 않고 워커 종료로 실패한 작업을 닫힌 DB 에 기록하지 않음 (시험 추가)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 23:25:25 +09:00
parent dc36d094e9
commit cd4b7cb16f
4 changed files with 79 additions and 8 deletions

View File

@@ -189,6 +189,7 @@ export async function startCore(opts: CoreOptions) {
relay.stop();
retention.stop();
games.stop();
stt.stop();
await bot.stop();
await worker.stop();
await api.close();

View File

@@ -81,6 +81,8 @@ export class SttPipeline {
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
/** 앱 종료 중: 새 작업을 꺼내지 않고, 워커가 끊겨 실패한 작업은 DB(곧 닫힘)에 기록하지 않는다. 남은 발화는 다음 시작 때 다시 처리 */
private stopped = false;
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
onDone: ((id: string) => void) | null = null;
/** 예전 녹음 고치기가 끝났을 때 */
@@ -238,8 +240,13 @@ export class SttPipeline {
return null;
}
/** 종료 시작 (워커 · DB 를 닫기 전에 부른다) */
stop(): void {
this.stopped = true;
}
private pump(): void {
if (this.busy || !this.worker.ready) return;
if (this.stopped || this.busy || !this.worker.ready) return;
const idx = this.queue.findIndex((j) => this.pickSlot(j) !== null);
if (idx < 0) return;
const job = this.queue.splice(idx, 1)[0];
@@ -254,6 +261,7 @@ export class SttPipeline {
this.busy = false;
this.processing = null;
this.status.processing = null;
if (this.stopped) return;
try {
if (!this.isBusy(job.id)) this.onDone?.(job.id);
} catch (e) {
@@ -320,6 +328,7 @@ export class SttPipeline {
5 * 60000,
);
} catch (e: any) {
if (this.stopped) return;
const attempts = this.store.bumpAttempt(u.id);
this.status.lastError = e.message;
log.warn(`STT 실패 (${u.id}, ${attempts}회): ${e.message}`);

View File

@@ -34,6 +34,8 @@ let settings: SettingsStore | null = null;
let auth: AppAuth | null = null;
let win: BrowserWindow | null = null;
let tray: Tray | null = null;
/** 트레이 · 상태 갱신 타이머 (종료할 때 멈춘다) */
const timers: NodeJS.Timeout[] = [];
let quitting = false;
const dataDir = resolveDataDir(opt('data-dir'));
@@ -148,7 +150,8 @@ function closeSplash(): void {
}
function updateTray(): void {
if (!tray) return;
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우에도 오류 창이 뜨지 않게
if (!tray || tray.isDestroyed()) return;
if (!core) {
tray.setImage(trayImage('off'));
tray.setToolTip(`겜녹이\n${auth?.state.status === 'not_registered' ? '등록되지 않은 아이디' : '로그인이 필요합니다'}`);
@@ -168,7 +171,7 @@ function updateTray(): void {
}
function buildTrayMenu(): void {
if (!tray) return;
if (!tray || tray.isDestroyed()) return;
if (!core) {
tray.setContextMenu(
Menu.buildFromTemplate([
@@ -203,7 +206,11 @@ async function quit(): Promise<void> {
} catch (e) {
log.error('종료 중 오류', e);
}
tray?.destroy();
// 트레이 갱신 타이머가 app.exit 사이에 한 번 더 돌면 'Tray is destroyed' 오류 창이 뜬다
for (const t of timers) clearInterval(t);
const tr = tray;
tray = null;
tr?.destroy();
app.exit(0);
}
@@ -383,18 +390,18 @@ app.whenReady().then(async () => {
// 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도
let lastCheck = Date.now();
const first = a.check();
setInterval(() => {
timers.push(setInterval(() => {
const st = a.state.status;
if ((st === 'ok' && Date.now() - lastCheck > 10 * 60000) || (st === 'error' && Date.now() - lastCheck > 60000) || (st === 'ok' && a.state.offline && Date.now() - lastCheck > 60000)) {
lastCheck = Date.now();
void a.check().then(syncNames);
}
}, 15000);
setInterval(() => {
}, 15000));
timers.push(setInterval(() => {
updateTray();
buildTrayMenu();
pushState();
}, 1500);
}, 1500));
splashText('로그인 확인 중…');
await first;
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');

View File

@@ -0,0 +1,54 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../src/core/db/db.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
import { SttPipeline } from '../src/core/stt/pipeline.ts';
import { WorkerError } from '../src/core/stt/worker.ts';
test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫힌 DB 를 건드리지 않고, 남은 작업을 꺼내지 않는다', async () => {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
for (const id of ['s1', 's2']) {
const f = path.join(dir, `${id}.ogg`);
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
}
const transcribing: string[] = [];
let fail: ((e: Error) => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string, req: any) => {
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op !== 'transcribe') return {};
transcribing.push(path.basename(req.path, '.ogg'));
return new Promise((_, rej) => (fail = rej));
},
});
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
await stt.load('realtime', 'm');
const done: string[] = [];
stt.onDone = (id) => {
done.push(id);
store.getUtterance(id); // 실제 앱의 녹음 파일 이름 맞추기도 DB 를 읽는다
};
stt.enqueue('s1', 'realtime');
stt.enqueue('s2', 'realtime');
assert.deepEqual(transcribing, ['s1']);
// core.stop 순서: stt.stop → 워커 종료 → DB 닫기 → (워커 프로세스 종료 이벤트로) 변환 요청 실패
stt.stop();
store.close();
fail!(new WorkerError('worker_exit', '워커 종료'));
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(done, [], '종료 중에는 변환 뒤 처리를 하지 않는다');
assert.deepEqual(transcribing, ['s1']);
assert.equal(stt.status.queue, 1, '종료 중에는 다음 작업을 꺼내지 않는다 (다음 시작 때 다시 처리)');
});