d3ro-voice/apps/desktop/src/main/services/MeetingSummaryService.ts
Yun Chan ba9ef9741e fix: red-team round 3 hardening across desktop, mobile, core and server
Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
2026-09-28 20:45:52 +09:00

305 lines
11 KiB
TypeScript

// src/main/services/MeetingSummaryService.ts
// Phase 12.2: 회의록 자동 요약 서비스
// CaptionService 세션 종료 후 LLM으로 요약 생성
import { EventEmitter } from 'events'
import path from 'path'
import fs from 'fs'
import { app, dialog } from 'electron'
import { eq } from 'drizzle-orm'
import { getLogger } from './LoggerService'
import { getLlmGateway } from './llm/LlmGateway'
import { getCloudSyncService } from './CloudSyncService'
import { condenseTranscriptToBudget } from './meeting/transcript-condenser'
import { LLM_PROXY_CHAT_LIMITS } from '@d3ro/core/llm-chat'
import { getDatabase } from '../db'
import { history } from '../db/schema'
import { getMainWindow } from '../windows/WindowManager'
import { toSafeFilenameSegment } from '../utils/safe-filename'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import type { MeetingSummaryResult, MeetingSummaryProgress } from '@d3ro/core/types'
const logger = getLogger('MeetingSummaryService')
let isShowingSummarySaveDialog = false
const MEETING_SUMMARY_PROMPT = `다음은 회의 전사록입니다. 아래 형식으로 정리해주세요:
## 요약
(3줄 이내 핵심 요약)
## 핵심 결정사항
- (결정 1)
- (결정 2)
## 할 일 목록
- [ ] (할 일 1)
- [ ] (할 일 2)
전사록 외의 내용을 추가하지 마세요. 전사록이 비어 있거나 내용이 부족하면 "요약할 내용이 충분하지 않습니다"라고만 출력하세요.`
class MeetingSummaryService extends EventEmitter {
/**
* 히스토리 항목의 전사 텍스트를 LLM으로 요약
*/
async summarize(historyId: string): Promise<MeetingSummaryResult> {
// 라이센스 체크
try {
const { getLicenseService } = await import('./LicenseService')
const { Feature } = await import('@d3ro/core/types')
const license = getLicenseService()
const access = license.canUse(Feature.MEETING_SUMMARY)
if (!access.allowed) {
license.promptUpgrade(
Feature.MEETING_SUMMARY,
access.reason === 'quota_exceeded' ? 'quota_exceeded' : 'tier_required',
)
throw new D3ROError(ErrorCode.FeatureNotAvailable, 'Pro+ required for meeting summary')
}
} catch (err) {
if (err instanceof D3ROError) throw err
}
// 히스토리 항목 조회
const db = getDatabase()
const rows = db.select().from(history).where(eq(history.id, historyId)).all()
if (rows.length === 0) {
throw new D3ROError(ErrorCode.HistoryNotFound, `History not found: ${historyId}`)
}
const entry = rows[0]
const transcript = entry.originalText
if (!transcript || transcript.trim().length === 0) {
throw new D3ROError(ErrorCode.MeetingSummaryNoTranscript, 'No transcript text to summarize')
}
// 진행 상태 알림
this._sendProgress(historyId, 'generating')
try {
// LLM 요약 생성 — 백엔드 선택은 게이트웨이가 한다(llmBackend='local' 이면 로컬 Ollama).
// 예전엔 설정과 무관하게 Premium 에 고정돼, 로컬을 고른 로그인 사용자의 자막 전사가 클라우드로 가고
// 쿼터를 썼으며, 로그인하지 않은 사용자는 요약을 전혀 받지 못했다.
const gateway = getLlmGateway()
const llm = {
generate: (text: string, options?: { systemPrompt?: string; temperature?: number; maxTokens?: number }) =>
gateway.generate(text, options, {
onFallback: (reason) => logger.warn(`Meeting summary LLM fallback: ${reason}`),
}),
}
// 긴 전사는 한 메시지 한도(8,000자)를 넘어 거부된다 — 구간별로 정리한 뒤 요약한다.
const fitted = await condenseTranscriptToBudget(llm, transcript, LLM_PROXY_CHAT_LIMITS.maxMessageChars)
if (fitted.condensed) {
logger.info(`Summary input condensed in ${fitted.rounds} round(s): ${historyId}`)
}
const result = await llm.generate(fitted.text, {
systemPrompt: MEETING_SUMMARY_PROMPT,
temperature: 0.3,
})
const rawMarkdown = result.text.trim()
const parsed = this._parseMarkdown(rawMarkdown)
const summaryResult: MeetingSummaryResult = {
historyId,
summary: parsed.summary,
decisions: parsed.decisions,
actionItems: parsed.actionItems,
rawMarkdown,
generatedAt: Date.now(),
}
// DB에 요약 저장
const saved = db.update(history)
.set({ summaryText: rawMarkdown, updatedAt: Date.now() })
.where(eq(history.id, historyId))
.run()
// Phase 3.3: 요약 저장 후 자동 push (fire-and-forget).
// 요약하는 사이 기록이 지워졌으면 올리지 않는다 — 대기 중인 원격 삭제를 upsert 로 덮는다.
if (saved.changes > 0) void getCloudSyncService().pushOne('history', historyId)
this._sendProgress(historyId, 'done')
this._sendToRenderer(IPC_CHANNELS.MEETING_SUMMARY.SUMMARY_READY, summaryResult)
this.emit('summary-ready', summaryResult)
return summaryResult
} catch (err) {
this._sendProgress(historyId, 'error')
if (err instanceof D3ROError) throw err
const msg = err instanceof Error ? err.message : String(err)
throw new D3ROError(ErrorCode.MeetingSummaryGenerationFailed, msg)
}
}
/**
* 저장된 요약 조회
*/
getSummary(historyId: string): MeetingSummaryResult | null {
const db = getDatabase()
const rows = db.select().from(history).where(eq(history.id, historyId)).all()
if (rows.length === 0 || !rows[0].summaryText) {
return null
}
const entry = rows[0]
const parsed = this._parseMarkdown(entry.summaryText!)
return {
historyId,
summary: parsed.summary,
decisions: parsed.decisions,
actionItems: parsed.actionItems,
rawMarkdown: entry.summaryText!,
generatedAt: entry.updatedAt,
}
}
/**
* 마크다운 파일로 내보내기
*/
async exportMarkdown(historyId: string): Promise<string> {
const summary = this.getSummary(historyId)
if (!summary) {
throw new D3ROError(ErrorCode.MeetingSummaryExportFailed, 'No summary to export')
}
const db = getDatabase()
const rows = db.select().from(history).where(eq(history.id, historyId)).all()
const entry = rows[0]
const date = new Date(entry.createdAt)
const dateStr = date.toISOString().slice(0, 10)
const safeTitle = toSafeFilenameSegment(entry.title, 'meeting-summary')
const defaultName = `d3ro-summary-${safeTitle}-${dateStr}.md`
if (isShowingSummarySaveDialog) {
throw new D3ROError(ErrorCode.MeetingSummaryExportFailed, 'Export dialog already active')
}
isShowingSummarySaveDialog = true
let result: Electron.SaveDialogReturnValue
try {
const mainWindow = getMainWindow()
const dialogOptions = {
defaultPath: path.join(app.getPath('documents'), defaultName),
filters: [{ name: 'Markdown', extensions: ['md'] }],
}
result = mainWindow
? await dialog.showSaveDialog(mainWindow, dialogOptions)
: await dialog.showSaveDialog(dialogOptions)
} finally {
isShowingSummarySaveDialog = false
}
if (result.canceled || !result.filePath) {
throw new D3ROError(ErrorCode.MeetingSummaryExportFailed, 'Export cancelled')
}
const content = `# Meeting Summary — ${dateStr}\n\n${summary.rawMarkdown}\n\n---\n\n## Full Transcript\n\n${entry.originalText}\n`
fs.writeFileSync(result.filePath, content, 'utf-8')
return result.filePath
}
/**
* CaptionService 세션 종료 시 자동 요약 (옵션)
*/
async onCaptionSessionSaved(sessionSummary: { sessionId: string; historyId?: string | null }): Promise<void> {
// caption 모드 히스토리에서 해당 세션 찾기.
// 히스토리 행 id 는 HistoryService 가 따로 만든다 — 자막 세션 id 와 절대 같지 않으므로
// CaptionService 가 실어 준 historyId 로 찾는다(없으면 저장되지 않은 세션).
const historyId = sessionSummary.historyId
if (!historyId) {
logger.info(`Caption session was not saved to history, skipping summary: ${sessionSummary.sessionId}`)
return
}
const db = getDatabase()
const rows = db
.select()
.from(history)
.where(eq(history.id, historyId))
.all()
if (rows.length === 0) {
logger.warn(`Caption session not found in history: ${historyId}`)
return
}
const entry = rows[0]
if (!entry.originalText || entry.originalText.trim().length < 50) {
logger.info('Caption session too short for summary, skipping')
return
}
try {
await this.summarize(entry.id)
logger.info(`Auto-summary generated for caption session: ${entry.id}`)
} catch (err) {
logger.warn('Auto-summary failed:', err)
}
}
private _parseMarkdown(markdown: string): {
summary: string
decisions: string[]
actionItems: string[]
} {
const sections = markdown.split(/^## /m)
let summary = ''
const decisions: string[] = []
const actionItems: string[] = []
for (const section of sections) {
const lines = section.trim().split('\n')
const heading = lines[0]?.trim().toLowerCase() ?? ''
const body = lines.slice(1).join('\n').trim()
if (heading.includes('요약') || heading.includes('summary')) {
summary = body
} else if (heading.includes('결정') || heading.includes('decision')) {
const items = body.split('\n').filter((l) => l.trim().startsWith('-'))
decisions.push(...items.map((l) => l.replace(/^-\s*/, '').trim()))
} else if (heading.includes('할 일') || heading.includes('action')) {
const items = body.split('\n').filter((l) => l.trim().startsWith('-'))
actionItems.push(
...items.map((l) => l.replace(/^-\s*\[[ x]?\]\s*/, '').trim()),
)
}
}
return { summary, decisions, actionItems }
}
private _sendProgress(historyId: string, status: MeetingSummaryProgress['status']): void {
this._sendToRenderer(IPC_CHANNELS.MEETING_SUMMARY.SUMMARY_PROGRESS, { historyId, status })
}
private _sendToRenderer(channel: string, data: unknown): void {
try {
const mainWindow = getMainWindow()
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send(channel, data)
}
} catch {
// 윈도우 없으면 무시
}
}
dispose(): void {
this.removeAllListeners()
}
}
// ── 싱글톤 ──
let instance: MeetingSummaryService | null = null
export function resetMeetingSummaryServiceForTests(): void {
if (instance) instance.removeAllListeners()
instance = null
}
export function getMeetingSummaryService(): MeetingSummaryService {
if (!instance) {
instance = new MeetingSummaryService()
}
return instance
}