종료 보완: DB 를 닫은 뒤 온 변환 성공 응답도 버림 · 트레이와 갱신 타이머를 TrayShell 로 묶어 종료 · 없어진 트레이 처리 회귀 시험

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 23:29:24 +09:00
parent cd4b7cb16f
commit 37c898cd73
4 changed files with 134 additions and 15 deletions

View File

@@ -340,6 +340,8 @@ export class SttPipeline {
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
// 종료 중에 결과가 왔으면 버린다 (DB 가 이미 닫혔을 수 있다. 발화는 다음 시작 때 다시 처리)
if (this.stopped) return;
// 변환하는 동안 사이트에서 지운 발화: 결과를 버린다
if (!this.store.getUtterance(u.id)) return;
// 사이트에서 "잡음이라 삭제"한 문장과 같으면 잡음으로 (v1.4.0)

View File

@@ -12,6 +12,7 @@ import { Finetuner } from './finetune.js';
import type { AuthView } from './api-types.js';
import { buildState, registerIpc } from './ipc.js';
import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
import { TrayShell } from './tray-shell.js';
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
hardenTlsEnv();
@@ -33,9 +34,7 @@ let ft: Finetuner | null = null;
let settings: SettingsStore | null = null;
let auth: AppAuth | null = null;
let win: BrowserWindow | null = null;
let tray: Tray | null = null;
/** 트레이 · 상태 갱신 타이머 (종료할 때 멈춘다) */
const timers: NodeJS.Timeout[] = [];
const trayShell = new TrayShell<Tray>();
let quitting = false;
const dataDir = resolveDataDir(opt('data-dir'));
@@ -150,8 +149,8 @@ function closeSplash(): void {
}
function updateTray(): void {
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우에도 오류 창이 뜨지 않게
if (!tray || tray.isDestroyed()) return;
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setImage(trayImage('off'));
tray.setToolTip(`겜녹이\n${auth?.state.status === 'not_registered' ? '등록되지 않은 아이디' : '로그인이 필요합니다'}`);
@@ -171,7 +170,8 @@ function updateTray(): void {
}
function buildTrayMenu(): void {
if (!tray || tray.isDestroyed()) return;
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setContextMenu(
Menu.buildFromTemplate([
@@ -207,10 +207,7 @@ async function quit(): Promise<void> {
log.error('종료 중 오류', e);
}
// 트레이 갱신 타이머가 app.exit 사이에 한 번 더 돌면 'Tray is destroyed' 오류 창이 뜬다
for (const t of timers) clearInterval(t);
const tr = tray;
tray = null;
tr?.destroy();
trayShell.dispose();
app.exit(0);
}
@@ -383,25 +380,26 @@ app.whenReady().then(async () => {
if (starting) await starting;
},
});
tray = new Tray(trayImage('off'));
const tray = new Tray(trayImage('off'));
tray.on('click', () => openWindow());
trayShell.set(tray);
refreshShell();
a.on('change', onAuthChange);
// 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도
let lastCheck = Date.now();
const first = a.check();
timers.push(setInterval(() => {
trayShell.every(15000, () => {
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));
timers.push(setInterval(() => {
});
trayShell.every(1500, () => {
updateTray();
buildTrayMenu();
pushState();
}, 1500));
});
splashText('로그인 확인 중…');
await first;
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');

View File

@@ -0,0 +1,31 @@
/** 트레이 아이콘과 그 갱신 타이머. 종료할 때 타이머를 먼저 멈추고 트레이를 없앤다 (v1.8.2: 'Tray is destroyed' 오류 창) */
export interface TrayLike {
isDestroyed(): boolean;
destroy(): void;
}
export class TrayShell<T extends TrayLike> {
private tray: T | null = null;
private timers: NodeJS.Timeout[] = [];
set(tray: T): void {
this.tray = tray;
}
/** 쓸 수 있는 트레이 (없거나, 종료했거나, Windows 로그오프 등으로 Electron 이 먼저 없앴으면 null) */
get(): T | null {
return this.tray && !this.tray.isDestroyed() ? this.tray : null;
}
every(ms: number, fn: () => void): void {
this.timers.push(setInterval(fn, ms));
}
dispose(): void {
for (const t of this.timers) clearInterval(t);
this.timers = [];
const tray = this.get();
this.tray = null;
tray?.destroy();
}
}

View File

@@ -9,6 +9,7 @@ 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';
import { TrayShell } from '../src/main/tray-shell.ts';
test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫힌 DB 를 건드리지 않고, 남은 작업을 꺼내지 않는다', async () => {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
@@ -52,3 +53,90 @@ test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫
assert.deepEqual(transcribing, ['s1']);
assert.equal(stt.status.queue, 1, '종료 중에는 다음 작업을 꺼내지 않는다 (다음 시작 때 다시 처리)');
});
test('앱 종료: DB 를 닫은 뒤 변환 성공 응답이 와도 닫힌 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 });
const f = path.join(dir, 's1.ogg');
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id: 's1', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
let ok: ((r: unknown) => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string) => {
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op !== 'transcribe') return {};
return new Promise((res) => (ok = res));
},
});
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 errors: unknown[] = [];
const done: string[] = [];
stt.onDone = (id) => done.push(id);
// run() 의 오류는 pump 의 catch 가 log.error 로만 남기므로, DB 접근을 감시한다
const prepare = (store as any).db.prepare.bind((store as any).db);
(store as any).db.prepare = (sql: string) => {
try {
return prepare(sql);
} catch (e) {
errors.push(e);
throw e;
}
};
stt.enqueue('s1', 'realtime');
stt.stop();
store.close();
ok!({ text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 });
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(errors, [], '닫힌 DB 에 접근하지 않는다');
assert.deepEqual(done, []);
});
test('트레이: 종료하면 갱신 타이머가 멈추고 트레이를 한 번만 없앤다 · 이미 없어진 트레이는 건드리지 않는다', (t) => {
t.mock.timers.enable({ apis: ['setInterval'] });
const fake = () => {
const tr = { destroyed: false, destroys: 0, updates: 0, isDestroyed: () => tr.destroyed, destroy: () => ((tr.destroyed = true), tr.destroys++) };
return tr;
};
// 갱신 함수는 main.ts 의 updateTray 처럼 shell.get() 으로 트레이를 얻는다 (없어진 트레이에 쓰면 Electron 이 던지는 것을 흉내)
const shell = new TrayShell<ReturnType<typeof fake>>();
let ticks = 0;
const update = () => {
ticks++;
const tr = shell.get();
if (!tr) return;
if (tr.destroyed) throw new Error('Tray is destroyed');
tr.updates++;
};
const a = fake();
shell.set(a);
shell.every(1500, update);
t.mock.timers.tick(3000);
assert.equal(a.updates, 2);
shell.dispose();
assert.equal(a.destroys, 1);
assert.equal(shell.get(), null);
t.mock.timers.tick(3000);
assert.equal(a.updates, 2, '종료 뒤에는 갱신하지 않는다');
assert.equal(ticks, 2, '종료하면 갱신 타이머가 멈춘다');
shell.dispose();
assert.equal(a.destroys, 1, '두 번 없애지 않는다');
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우
const b = fake();
const shell2 = new TrayShell<ReturnType<typeof fake>>();
shell2.set(b);
shell2.every(1500, () => {
const tr = shell2.get();
if (tr?.destroyed) throw new Error('Tray is destroyed');
});
b.destroyed = true;
assert.equal(shell2.get(), null);
assert.doesNotThrow(() => t.mock.timers.tick(1500));
shell2.dispose();
assert.equal(b.destroys, 0, '이미 없어진 트레이는 다시 없애지 않는다');
});