refactor(desktop): session-scoped voice runtime, STT/LLM ports, caption ownership and meeting export fixes

This commit is contained in:
Yun Chan 2026-09-28 00:53:43 +09:00
parent 0adedf5e7b
commit 83cf9133ac
39 changed files with 4787 additions and 1061 deletions

View file

@ -53,11 +53,44 @@ const DEFAULT_CONFIG: CaptionConfig = {
audioSource: 'mic',
}
/**
* 자막 세션의 소유자. 회의 모드가 시작한 세션은 사용자 핫키/IPC 가 끌 수 없다
* (예전엔 핫키가 회의의 마이크 캡처를 조용히 끊고 회의 UI 는 계속 '녹음 중'이었다).
*/
export type CaptionOwner = 'user' | 'meeting'
/** 자막 세션 시작 옵션 — 생략하면 기존(사용자 자막) 동작과 같다 */
export interface CaptionStartOptions {
/** 기본 'user' */
owner?: CaptionOwner
/** 이번 세션에만 쓸 오디오 소스. 생략 시 설정값(captionAudioSource). 전역 설정은 건드리지 않는다. */
audioSource?: CaptionConfig['audioSource']
/** 자막 오버레이 표시 여부 (기본 true) */
showOverlay?: boolean
/** 세션을 'caption' 히스토리로 저장하고 session-saved 를 알릴지 (기본 true) */
persistHistory?: boolean
}
/** 종료된 세션 요약 + 저장된 히스토리 행 id (저장하지 않았으면 null) */
export type CaptionSessionResult = CaptionSessionSummary & { historyId: string | null }
interface ResolvedStartOptions {
owner: CaptionOwner
showOverlay: boolean
persistHistory: boolean
}
const DEFAULT_START_OPTIONS: ResolvedStartOptions = {
owner: 'user',
showOverlay: true,
persistHistory: true,
}
interface CaptionServiceEvents {
'state-changed': (state: CaptionState) => void
'segment': (segment: CaptionSegment) => void
'delta': (data: { text: string; isFinal: boolean }) => void
'session-saved': (summary: CaptionSessionSummary) => void
'session-saved': (summary: CaptionSessionResult) => void
'error': (error: D3ROError) => void
}
@ -81,6 +114,8 @@ class CaptionService extends EventEmitter {
private _refining = false
private _audioDataHandler: ((payload: { buffer: Buffer; timestamp: number }) => void) | null = null
/** 현재 세션 옵션(소유자·오버레이·히스토리 저장) — 세션이 없으면 기본값 */
private _session: ResolvedStartOptions = { ...DEFAULT_START_OPTIONS }
// ── 공개 접근자 ──
@ -88,6 +123,11 @@ class CaptionService extends EventEmitter {
return this._state
}
/** 현재 세션 소유자 (세션이 없으면 null) */
getOwner(): CaptionOwner | null {
return this._state === 'inactive' ? null : this._session.owner
}
getConfig(): CaptionConfig {
return { ...this._config }
}
@ -102,7 +142,7 @@ class CaptionService extends EventEmitter {
// ── 시작 ──
async start(): Promise<void> {
async start(options: CaptionStartOptions = {}): Promise<void> {
if (this._disposed) {
throw new D3ROError(
ErrorCode.CaptionStartFailed,
@ -117,12 +157,19 @@ class CaptionService extends EventEmitter {
)
}
this._session = {
owner: options.owner ?? DEFAULT_START_OPTIONS.owner,
showOverlay: options.showOverlay ?? DEFAULT_START_OPTIONS.showOverlay,
persistHistory: options.persistHistory ?? DEFAULT_START_OPTIONS.persistHistory,
}
this._setState('starting')
// 오버레이를 즉시 표시 (로딩 상태)
showCaptionOverlay()
sendToCaptionOverlay('caption:config', this._config)
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.STATE_CHANGED, { state: 'starting' })
// 오버레이를 즉시 표시 (로딩 상태) — 회의 모드처럼 자체 UI 가 있으면 띄우지 않는다
if (this._session.showOverlay) {
showCaptionOverlay()
sendToCaptionOverlay('caption:config', this._config)
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.STATE_CHANGED, { state: 'starting' })
}
try {
// STT 초기화 (모델 로딩 — 시간 소요)
@ -142,13 +189,19 @@ class CaptionService extends EventEmitter {
const lang = configGet('sttLanguage') as string | undefined
const initialContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : ''
// ConfigService에서 저장된 오디오 소스 읽기
const savedSource = configGet('captionAudioSource' as keyof import('@d3ro/core/types').AppConfig) as unknown as string
if (savedSource && (savedSource === 'mic' || savedSource === 'system' || savedSource === 'both')) {
this._config.audioSource = savedSource as 'mic' | 'system' | 'both'
// 오디오 소스: 호출자 지정값(이번 세션 한정) → 저장된 설정 순.
// 호출자 지정값은 this._config 에 쓰지 않는다 — 다음 사용자 세션으로 새지 않게.
let audioSource: CaptionConfig['audioSource']
if (options.audioSource) {
audioSource = options.audioSource
} else {
const savedSource = configGet('captionAudioSource' as keyof import('@d3ro/core/types').AppConfig) as unknown as string
if (savedSource && (savedSource === 'mic' || savedSource === 'system' || savedSource === 'both')) {
this._config.audioSource = savedSource as 'mic' | 'system' | 'both'
}
audioSource = this._config.audioSource
}
const { audioSource } = this._config
logger.info(`Caption audioSource: ${audioSource}`)
logger.info(`Caption audioSource: ${audioSource} (owner: ${this._session.owner})`)
// 마이크 캡처 (mic 또는 both)
if (audioSource === 'mic' || audioSource === 'both') {
@ -190,6 +243,7 @@ class CaptionService extends EventEmitter {
await audioCaptureService.stop().catch(() => {})
}
hideCaptionOverlay()
this._session = { ...DEFAULT_START_OPTIONS }
this._setState('inactive')
const d3roErr =
err instanceof D3ROError
@ -205,10 +259,21 @@ class CaptionService extends EventEmitter {
// ── 중지 ──
async stop(): Promise<void> {
/**
* 자막 세션을 멈추고 요약을 돌려준다(말하던 마지막 문장 flush 포함).
*
* @param owner 생략하면 강제 정지(앱 종료·로그아웃·회의 강제 초기화).
* 지정하면 그 소유자의 세션일 때만 멈추고, 아니면 false 를 돌려준다.
* @returns 세션 요약(세그먼트가 없으면 null), 다른 소유자라 거부했으면 false
*/
async stop(owner?: CaptionOwner): Promise<CaptionSessionResult | null | false> {
if (this._state !== 'active' && this._state !== 'starting') {
logger.warn(`캡션 중지 불가: 현재 상태=${this._state}`)
return
return null
}
if (owner && owner !== this._session.owner) {
logger.warn(`캡션 중지 거부: 세션 소유자=${this._session.owner}, 요청=${owner}`)
return false
}
this._setState('stopping')
@ -238,22 +303,25 @@ class CaptionService extends EventEmitter {
// 오버레이 숨김
hideCaptionOverlay()
// 세션을 히스토리에 저장
const summary = this._saveSession()
// 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다)
const persist = this._session.persistHistory
const summary = this._saveSession(persist)
this._sessionId = null
this._sessionStartedAt = null
this._refineQueue = []
this._sessionLanguage = null
this._session = { ...DEFAULT_START_OPTIONS }
this._setState('inactive')
getSoundEffectService().play('recording-stop')
logger.info('Live Caption 중지')
if (summary) {
if (summary && persist) {
this.emit('session-saved', summary)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SESSION_SAVED, summary)
}
return summary
}
// ── dispose ──
@ -411,7 +479,7 @@ class CaptionService extends EventEmitter {
// ── 내부: 세션 저장 ──
private _saveSession(): CaptionSessionSummary | null {
private _saveSession(persist: boolean): CaptionSessionResult | null {
if (!this._sessionId || !this._sessionStartedAt || this._segments.length === 0) {
return null
}
@ -421,10 +489,27 @@ class CaptionService extends EventEmitter {
const fullText = this._segments.map((s) => s.text).join(' ')
const wordCount = fullText.split(/\s+/).filter((w) => w.length > 0).length
// 히스토리에 저장 (mode: 'caption')
// 히스토리에 저장 (mode: 'caption'). 만들어진 행 id 를 요약에 싣는다 —
// 자동 요약은 이 id 로 히스토리를 찾는다(예전엔 자막 세션 id 로 찾아 항상 실패했다).
const historyId = persist ? this._persistHistory(fullText, totalDurationMs, wordCount) : null
const summary: CaptionSessionResult = {
sessionId: this._sessionId,
historyId,
segments: [...this._segments],
startedAt: this._sessionStartedAt,
endedAt,
totalDurationMs,
}
this._segments = []
return summary
}
/** 'caption' 히스토리 행을 만들고 id 를 돌려준다. 실패하면 로그만 남기고 null. */
private _persistHistory(fullText: string, totalDurationMs: number, wordCount: number): string | null {
try {
const historyService = getHistoryService()
historyService.create({
const entry = getHistoryService().create({
originalText: fullText,
polishedText: null,
focusedApp: null,
@ -447,22 +532,13 @@ class CaptionService extends EventEmitter {
logger.info(
`캡션 세션 저장: ${this._segments.length}개 세그먼트, ${wordCount}단어, ${Math.round(totalDurationMs / 1000)}초`,
)
return entry.id
} catch (err) {
logger.error(
`캡션 세션 저장 실패: ${err instanceof Error ? err.message : String(err)}`,
)
return null
}
const summary: CaptionSessionSummary = {
sessionId: this._sessionId,
segments: [...this._segments],
startedAt: this._sessionStartedAt,
endedAt,
totalDurationMs,
}
this._segments = []
return summary
}
// ── 내부: 상태 전이 ──