From 37c898cd73c69c9ef4352dac01e6cdccebfb91c9 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 18 Oct 2026 23:29:24 +0900 Subject: [PATCH] =?UTF-8?q?=EC=A2=85=EB=A3=8C=20=EB=B3=B4=EC=99=84:=20DB?= =?UTF-8?q?=20=EB=A5=BC=20=EB=8B=AB=EC=9D=80=20=EB=92=A4=20=EC=98=A8=20?= =?UTF-8?q?=EB=B3=80=ED=99=98=20=EC=84=B1=EA=B3=B5=20=EC=9D=91=EB=8B=B5?= =?UTF-8?q?=EB=8F=84=20=EB=B2=84=EB=A6=BC=20=C2=B7=20=ED=8A=B8=EB=A0=88?= =?UTF-8?q?=EC=9D=B4=EC=99=80=20=EA=B0=B1=EC=8B=A0=20=ED=83=80=EC=9D=B4?= =?UTF-8?q?=EB=A8=B8=EB=A5=BC=20TrayShell=20=EB=A1=9C=20=EB=AC=B6=EC=96=B4?= =?UTF-8?q?=20=EC=A2=85=EB=A3=8C=20=C2=B7=20=EC=97=86=EC=96=B4=EC=A7=84=20?= =?UTF-8?q?=ED=8A=B8=EB=A0=88=EC=9D=B4=20=EC=B2=98=EB=A6=AC=20=ED=9A=8C?= =?UTF-8?q?=EA=B7=80=20=EC=8B=9C=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/core/stt/pipeline.ts | 2 + app/src/main/main.ts | 28 ++++++----- app/src/main/tray-shell.ts | 31 ++++++++++++ app/test/stt-shutdown.test.ts | 88 +++++++++++++++++++++++++++++++++++ 4 files changed, 134 insertions(+), 15 deletions(-) create mode 100644 app/src/main/tray-shell.ts diff --git a/app/src/core/stt/pipeline.ts b/app/src/core/stt/pipeline.ts index 7a7e927..17f5e74 100644 --- a/app/src/core/stt/pipeline.ts +++ b/app/src/core/stt/pipeline.ts @@ -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) diff --git a/app/src/main/main.ts b/app/src/main/main.ts index b1e1eb7..763b303 100644 --- a/app/src/main/main.ts +++ b/app/src/main/main.ts @@ -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(); 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 { 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('녹음 · 음성 인식 엔진 시작 중…'); diff --git a/app/src/main/tray-shell.ts b/app/src/main/tray-shell.ts new file mode 100644 index 0000000..5b36f23 --- /dev/null +++ b/app/src/main/tray-shell.ts @@ -0,0 +1,31 @@ +/** 트레이 아이콘과 그 갱신 타이머. 종료할 때 타이머를 먼저 멈추고 트레이를 없앤다 (v1.8.2: 'Tray is destroyed' 오류 창) */ +export interface TrayLike { + isDestroyed(): boolean; + destroy(): void; +} + +export class TrayShell { + 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(); + } +} diff --git a/app/test/stt-shutdown.test.ts b/app/test/stt-shutdown.test.ts index 8404eeb..a732daa 100644 --- a/app/test/stt-shutdown.test.ts +++ b/app/test/stt-shutdown.test.ts @@ -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>(); + 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>(); + 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, '이미 없어진 트레이는 다시 없애지 않는다'); +});