feat: 회의 파일 가져오기와 입력 엔진 배포 보완

This commit is contained in:
Yun Chan 2026-11-01 19:39:06 +09:00
parent 5a8c5cd792
commit b3519e5da7
54 changed files with 1129 additions and 116 deletions

View file

@ -7,6 +7,7 @@ import { ErrorCode, ipcSuccess, ipcError } from '@d3ro/core/errors'
import { getFileTranscriptionService } from '../services/FileTranscriptionService'
import { getLogger } from '../services/LoggerService'
import type { FileTranscriptionStartParams } from '@d3ro/core/types'
import { SUPPORTED_MEDIA_EXTENSIONS } from '../services/file-transcription/media-formats'
const logger = getLogger('file-transcription-handlers')
@ -33,10 +34,7 @@ export function registerFileTranscriptionHandlers(): void {
filters: [
{
name: 'Audio/Video',
extensions: [
'mp3', 'wav', 'm4a', 'ogg', 'flac', 'wma', 'aac',
'mp4', 'mkv', 'webm', 'avi', 'mov',
],
extensions: [...SUPPORTED_MEDIA_EXTENSIONS],
},
],
}

View file

@ -1,11 +1,12 @@
// src/main/ipc/meeting-mode-handlers.ts
// Phase 14 / 14.5: Meeting Mode IPC 핸들러
import { ipcMain } from 'electron'
import { dialog, ipcMain } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ErrorCode, ipcSuccess, ipcError, D3ROError } from '@d3ro/core/errors'
import { getMeetingModeService } from '../services/MeetingModeService'
import { getLogger } from '../services/LoggerService'
import { SUPPORTED_MEDIA_EXTENSIONS } from '../services/file-transcription/media-formats'
import { LiveSegmentEditor, normalizeSegmentText } from '../services/meeting/live-segment-edits'
import {
MEETING_CHAT_GET_HISTORY_CHANNEL,
@ -15,6 +16,7 @@ import type { LiveSegmentEditResult } from '../services/meeting/live-segment-edi
import type {
CaptionSegment,
MeetingSessionDetail,
MeetingImportParams,
MeetingAddMemoParams,
MeetingGetSessionsParams,
MeetingGetSessionParams,
@ -102,6 +104,34 @@ export function registerMeetingModeHandlers(): void {
}
})
ipcMain.handle(ch.IMPORT_RECORDING, async (_event, params: MeetingImportParams) => {
try {
let filePath = params.filePath
if (!filePath) {
const { getMainWindow } = await import('../windows/WindowManager')
const mainWindow = getMainWindow()
const options = {
properties: ['openFile'] as ('openFile')[],
filters: [{ name: 'Audio/Video', extensions: [...SUPPORTED_MEDIA_EXTENSIONS] }],
}
const selected = mainWindow
? await dialog.showOpenDialog(mainWindow, options)
: await dialog.showOpenDialog(options)
if (selected.canceled || selected.filePaths.length === 0) {
return ipcError(ErrorCode.FileTranscriptionCancelled, 'File selection cancelled')
}
filePath = selected.filePaths[0]
}
return ipcSuccess(await getMeetingModeService().importRecording(filePath, params.language))
} catch (err) {
logger.error(`importRecording 실패: ${err instanceof Error ? err.message : String(err)}`)
return ipcError(
err instanceof D3ROError ? err.code : ErrorCode.MeetingProcessingFailed,
err instanceof Error ? err.message : String(err),
)
}
})
ipcMain.handle('meetingMode:forceReset', async () => {
try {
await getMeetingModeService().forceReset()

View file

@ -35,6 +35,7 @@ import type {
} from '@d3ro/core/types'
import { collapseRepeatedSegments, collapseRepeats, isDegenerateTranscript } from './file-transcription/repetition'
import { SUPPORTED_MEDIA_EXTENSION_SET } from './file-transcription/media-formats'
const logger = getLogger('FileTranscriptionService')
@ -44,11 +45,6 @@ const CHUNK_DURATION_SEC = 30
const MAX_FILE_SIZE_BYTES = 2 * 1024 * 1024 * 1024
/** initialPrompt 컨텍스트 윈도우 (자) */
const CONTEXT_WINDOW_SIZE = 300
/** 지원 확장자 */
const SUPPORTED_EXTENSIONS = new Set([
'.mp3', '.wav', '.m4a', '.ogg', '.flac', '.wma', '.aac',
'.mp4', '.mkv', '.webm', '.avi', '.mov',
])
/** 기본 ffmpeg 위치 포트: 로컬 사본 조회 + 런타임 feed 다운로드 */
const defaultFfmpegLocator: FfmpegLocator = {
@ -94,14 +90,18 @@ class FileTranscriptionService extends EventEmitter {
}
}
async startTranscription(filePath: string, language?: string): Promise<FileTranscriptionResult> {
async startTranscription(
filePath: string,
language?: string,
options: { saveToHistory?: boolean; onConverted?: (wavPath: string) => Promise<void> } = {},
): Promise<FileTranscriptionResult> {
if (this._state !== 'idle') {
throw new D3ROError(ErrorCode.FileTranscriptionChunkFailed, 'Transcription already in progress')
}
// 파일 검증
const ext = path.extname(filePath).toLowerCase()
if (!SUPPORTED_EXTENSIONS.has(ext)) {
if (!SUPPORTED_MEDIA_EXTENSION_SET.has(ext)) {
throw new D3ROError(ErrorCode.FileTranscriptionInvalidFormat, `Unsupported format: ${ext}`)
}
@ -152,6 +152,8 @@ class FileTranscriptionService extends EventEmitter {
const wavPath = path.join(job.tempDir, 'audio.wav')
await this._convertToWav(job, ffmpegPath, filePath, wavPath)
throwIfCancelled()
await options.onConverted?.(wavPath)
throwIfCancelled()
// 오디오 길이 확인
const totalDurationSec = await this._probeDuration(job, ffmpegPath, wavPath)
@ -234,31 +236,32 @@ class FileTranscriptionService extends EventEmitter {
processingTimeMs,
}
// 히스토리에 저장
try {
const wordCount = fullText.split(/\s+/).filter((w) => w.length > 0).length
getHistoryService().create({
originalText: fullText,
polishedText: null,
focusedApp: null,
focusedAppName: null,
focusedAppWindowTitle: null,
mode: 'file-transcription',
status: 'completed',
errorCode: null,
audioLocalPath: filePath,
duration: totalDurationSec,
detectedLanguage: null,
micDevice: null,
wordCount,
sttModel: configGet('sttModelId') as string | null,
llmModel: null,
sttLatencyMs: processingTimeMs,
llmLatencyMs: null,
appVersion: app.getVersion(),
})
} catch (err) {
logger.warn('Failed to save file transcription to history:', err)
if (options.saveToHistory !== false) {
try {
const wordCount = fullText.split(/\s+/).filter((w) => w.length > 0).length
getHistoryService().create({
originalText: fullText,
polishedText: null,
focusedApp: null,
focusedAppName: null,
focusedAppWindowTitle: null,
mode: 'file-transcription',
status: 'completed',
errorCode: null,
audioLocalPath: filePath,
duration: totalDurationSec,
detectedLanguage: null,
micDevice: null,
wordCount,
sttModel: configGet('sttModelId') as string | null,
llmModel: null,
sttLatencyMs: processingTimeMs,
llmLatencyMs: null,
appVersion: app.getVersion(),
})
} catch (err) {
logger.warn('Failed to save file transcription to history:', err)
}
}
this._setJobState(job, 'completed')

View file

@ -56,6 +56,8 @@ import {
parseTranscriptLines,
} from '@d3ro/core/meeting-transcript'
import { markdownToDocx } from '@d3ro/core/utils/markdown-to-docx'
import { getFileTranscriptionService } from './FileTranscriptionService'
import { buildImportedMeetingTranscript } from './meeting/imported-recording'
import type {
MeetingModeState,
MeetingMemo,
@ -122,6 +124,8 @@ let isShowingMeetingSaveDialog = false
class MeetingModeService extends EventEmitter {
private _state: MeetingModeState = 'idle'
private _importInFlight = false
private _accountRevision = 0
/**
* 진행 중인 녹음. 녹음 한 건의 세그먼트·메모·오디오·구독은 이 객체가 단독으로 소유한다.
* 후처리가 끝날 때까지 남아 있어 getStateInfo 가 세션 id 를 계속 보고한다(실시간 편집 반영용).
@ -158,6 +162,7 @@ class MeetingModeService extends EventEmitter {
this.on('error', () => { /* default sink */ })
// 계정 DB 가 바뀔 때마다(로그인·로그아웃) 그 DB 에 남은 중단된 녹음을 정리한다.
this._unsubscribeScope = onAccountScopeChanged(() => {
this._accountRevision += 1
try {
this.recoverInterruptedSessions()
} catch (err) {
@ -245,6 +250,69 @@ class MeetingModeService extends EventEmitter {
this._sendStateToRenderer()
}
async importRecording(filePath: string, language?: string): Promise<MeetingSessionDetail> {
if (this._state !== 'idle' || this._importInFlight) {
throw new D3ROError(ErrorCode.MeetingAlreadyRecording, '다른 회의 녹음 또는 파일 가져오기가 진행 중입니다')
}
this._importInFlight = true
const accountRevision = this._accountRevision
const assertImportAccount = (): void => {
if (accountRevision !== this._accountRevision) {
throw new D3ROError(ErrorCode.FileTranscriptionCancelled, 'Account changed during meeting import')
}
}
const sessionId = crypto.randomUUID()
const audioPath = meetingAudioFilePathSync(sessionId)
let completed = false
try {
const transcription = await getFileTranscriptionService().startTranscription(
filePath,
language,
{
saveToHistory: false,
onConverted: async (wavPath) => {
assertImportAccount()
fs.mkdirSync(pathDirname(audioPath), { recursive: true })
await fs.promises.copyFile(wavPath, audioPath)
assertImportAccount()
},
},
)
assertImportAccount()
const imported = buildImportedMeetingTranscript(transcription)
if (!imported.rawTranscript) {
throw new D3ROError(ErrorCode.MeetingProcessingFailed, '파일에서 인식된 발화가 없습니다')
}
const endedAt = Date.now()
const startedAt = Math.max(0, endedAt - imported.durationMs)
getDatabase().insert(meetingSessions).values({
id: sessionId,
title: imported.title,
status: 'completed',
startedAt,
endedAt,
durationMs: imported.durationMs,
rawTranscript: imported.rawTranscript,
sttModel: configGet('sttModelId') as string | undefined,
sttLatencyMs: transcription.processingTimeMs,
createdAt: endedAt,
updatedAt: endedAt,
}).run()
getCloudSyncService().pushOne('meetings', sessionId)
getCloudSyncService().pushOne('meeting_audio', sessionId)
completed = true
const detail = this._loadSessionDetail(sessionId)
if (!detail) throw new D3ROError(ErrorCode.MeetingSessionNotFound, '가져온 회의를 다시 읽지 못했습니다')
this.emit('session-completed', detail)
return detail
} finally {
this._importInFlight = false
if (!completed) await fs.promises.rm(audioPath, { force: true }).catch(() => undefined)
}
}
// ── 녹음 시작 ──
async startRecording(options?: { force?: boolean }): Promise<MeetingStartResult> {
@ -252,7 +320,7 @@ class MeetingModeService extends EventEmitter {
await this.forceReset()
}
if (this._state !== 'idle') {
if (this._state !== 'idle' || this._importInFlight) {
throw new D3ROError(
ErrorCode.MeetingAlreadyRecording,
`회의 모드가 이미 실행 중입니다 (${this._state}). 이전 회의를 종료하거나 강제 초기화 후 다시 시도해주세요.`,

View file

@ -0,0 +1,8 @@
export const SUPPORTED_MEDIA_EXTENSIONS = [
'mp3', 'wav', 'm4a', 'ogg', 'flac', 'wma', 'aac',
'mp4', 'mkv', 'webm', 'avi', 'mov',
] as const
export const SUPPORTED_MEDIA_EXTENSION_SET: ReadonlySet<string> = new Set(
SUPPORTED_MEDIA_EXTENSIONS.map((extension) => `.${extension}`),
)

View file

@ -0,0 +1,28 @@
import type { FileTranscriptionResult } from '@d3ro/core/types'
import { formatTranscriptLines } from '@d3ro/core/meeting-transcript'
export interface ImportedMeetingTranscript {
title: string
rawTranscript: string
durationMs: number
}
export function buildImportedMeetingTranscript(
result: Pick<FileTranscriptionResult, 'fileName' | 'fullText' | 'segments' | 'totalDurationSec'>,
): ImportedMeetingTranscript {
const title = result.fileName.replace(/\.[^.]+$/, '').trim().slice(0, 160) || result.fileName.slice(0, 160)
const lines = result.segments.length > 0
? result.segments.map((segment) => ({
timestampMs: Math.max(0, Math.round(segment.start * 1000)),
timed: true,
speaker: null,
text: segment.text.trim(),
})).filter((segment) => segment.text.length > 0)
: [{ timestampMs: 0, timed: false, speaker: null, text: result.fullText.trim() }]
return {
title,
rawTranscript: formatTranscriptLines(lines),
durationMs: Math.max(0, Math.round(result.totalDurationSec * 1000)),
}
}

View file

@ -20,12 +20,13 @@ export function isRuntimeComponent(value: unknown): value is RuntimeComponent {
}
/**
* 이 앱이 요구하는 런타임 최소 버전. 사이드카 API 가 바뀔 때만 올린다.
* 이 앱이 요구하는 런타임 최소 버전. 필수 API 또는 입력 안전성 수정이 있을 때 올린다.
* 1.5.0 — UIA 브리지(`/uia/focus`). 1.7.0 — 보조 모델 자리(`/load` slot, `/transcribe` model_id).
* 1.16.0 — CPU 스레드 예산과 터미널/xterm UIA 고속 경로.
* ffmpeg 는 CLI 가 안정적이라 확인하지 않는다.
*/
export const RUNTIME_MIN_VERSION: Readonly<Record<RuntimeComponent, string | null>> = {
sidecar: '1.7.0',
sidecar: '1.16.0',
ffmpeg: null,
}