d3ro-voice/packages/core/src/meeting-transcript.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

183 lines
7.3 KiB
TypeScript

// packages/core/src/meeting-transcript.ts
// 회의 전사 텍스트 ↔ 구간(segment) 변환의 정본.
// 데스크톱은 전사를 `[MM:SS] [화자] 내용` 줄로 저장하고, Supabase `transcripts` 는 구간 행으로 저장한다
// (모바일은 구간이 있으면 구간을 우선 표시한다). 두 표현을 이 한 곳에서만 바꾼다.
import { splitTextToFit } from './text-chunking'
export interface TranscriptLine {
/** 회의 시작 기준 ms. 시각 표기가 없는 줄은 앞 줄의 시각을 이어받는다(처음이면 0). */
timestampMs: number
/** 시각 표기가 있었는지 — 없으면 화면이 순번으로 대신 표시할 수 있다 */
timed: boolean
speaker: string | null
text: string
}
const LINE_PATTERN = /^\[(\d{1,3}):(\d{2})\]\s*(?:\[([^\]]+)\]\s*)?(.*)$/
/** 빈 줄을 버리고 각 줄을 구간으로 나눈다. 내용이 빈 줄(`[00:01]` 만 있는 줄)도 버린다. */
export function parseTranscriptLines(text: string | null | undefined): TranscriptLine[] {
if (!text) return []
const lines: TranscriptLine[] = []
let lastTimestamp = 0
for (const raw of text.split('\n')) {
const line = raw.trim()
if (!line) continue
const match = LINE_PATTERN.exec(line)
if (match) {
const content = match[4].trim()
lastTimestamp = (Number(match[1]) * 60 + Number(match[2])) * 1000
if (!content) continue
lines.push({ timestampMs: lastTimestamp, timed: true, speaker: match[3]?.trim() || null, text: content })
} else {
lines.push({ timestampMs: lastTimestamp, timed: false, speaker: null, text: line })
}
}
return lines
}
export function formatTranscriptTimestamp(ms: number): string {
const totalSeconds = Math.max(0, Math.floor(ms / 1000))
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
}
/** parseTranscriptLines 의 역변환(시각 표기가 없던 줄은 그대로). */
export function formatTranscriptLines(lines: readonly TranscriptLine[]): string {
return lines
.map((l) => {
if (!l.timed) return l.text
const speaker = l.speaker ? `[${l.speaker}] ` : ''
return `[${formatTranscriptTimestamp(l.timestampMs)}] ${speaker}${l.text}`
})
.join('\n')
}
/** 캡처 세그먼트(절대 epoch 타임스탬프)를 회의 시작 기준 전사 줄로 조립한다. */
export interface TimedSegmentInput {
text: string
/** 절대 시각(epoch ms). CaptionService 가 Date.now() 로 찍는다. */
timestamp: number
}
/**
* 회의 세그먼트로 전사 텍스트를 만든다.
*
* 세그먼트 시각은 epoch 이므로 반드시 회의 시작 시각을 빼서 상대 시각으로 바꾼다
* (예전엔 epoch 을 그대로 써 `[29841999:45]` 가 저장되어 파싱·화자 구분·동기화가 모두 깨졌다).
* 시작 전 시각은 0 으로 자르고, 빈 텍스트 세그먼트는 버린다.
*/
export function buildTranscriptFromSegments(
segments: readonly TimedSegmentInput[],
sessionStartedAt: number,
): string {
const lines: TranscriptLine[] = []
for (const segment of segments) {
const text = segment.text.trim()
if (!text) continue
lines.push({
timestampMs: Math.max(0, segment.timestamp - sessionStartedAt),
timed: true,
speaker: null,
text,
})
}
return formatTranscriptLines(lines)
}
/** 화자 구분 결과 구간. start/end 는 초 단위(pyannote 응답 형식). */
export interface SpeakerSegment {
speaker: string
start: number
end: number
}
/**
* 전사 줄에 화자 구분 결과를 적용한다. 시각이 있는 줄의 시각이 속한 구간의 화자로
* speaker 필드를 **교체**한다(앞에 덧붙이지 않으므로 다시 돌려도 라벨이 쌓이지 않는다).
* 구간에 속하지 않거나 시각이 없는 줄은 그대로 둔다.
*
* @param labelFor 원시 화자 id(예: SPEAKER_01)를 표시 라벨로 바꾸는 함수 — 표시 문구는 호출자 소관
*/
export function applySpeakerLabels(
lines: readonly TranscriptLine[],
segments: readonly SpeakerSegment[],
labelFor: (rawSpeaker: string) => string = (raw) => raw,
): TranscriptLine[] {
return lines.map((line) => {
if (!line.timed) return line
const seconds = line.timestampMs / 1000
const match = segments.find((s) => seconds >= s.start && seconds <= s.end)
if (!match) return line
return { ...line, speaker: labelFor(match.speaker) }
})
}
/** 줄 앞의 `[MM:SS] [화자] ` 머리 — 긴 줄을 자를 때 이어지는 조각에도 붙여 시각·화자를 잃지 않는다 */
const LINE_PREFIX = /^\[\d{1,3}:\d{2}\]\s*(?:\[[^\]]+\]\s*)?/
/**
* maxChars 보다 긴 한 줄을 maxChars 이하 줄들로 자른다(문장 경계 → 공백 → 글자 수).
* `[MM:SS] [화자]` 머리가 있으면 조각마다 붙인다 — 단, 머리가 한도의 절반을 넘으면 붙이지 않는다.
*/
function splitLongLine(line: string, maxChars: number): string[] {
if (line.length <= maxChars) return [line]
const prefix = LINE_PREFIX.exec(line)?.[0] ?? ''
if (!prefix || prefix.length * 2 > maxChars) return splitTextToFit(line, maxChars)
const body = line.slice(prefix.length)
return splitTextToFit(body, maxChars - prefix.length).map((piece) => `${prefix}${piece}`)
}
/**
* 전사를 줄 경계에서 끊어 LLM 한 번에 보낼 크기(maxChars 이하)의 조각들로 나눈다.
* 한 줄이 maxChars 보다 길면(줄바꿈 없는 자막·파일·폰 전사) 그 줄을 문장 경계 → 공백 → 글자 수
* 순으로 잘라 여러 줄로 만든다 — 예전엔 줄 하나가 통째로 한 조각이 되어 LLM 입력·출력 한도를 넘었다.
* 빈 줄은 버린다.
*/
export function chunkTranscriptByLines(text: string | null | undefined, maxChars: number): string[] {
if (!text) return []
const limit = Math.max(1, Math.floor(maxChars))
const chunks: string[] = []
let current: string[] = []
let size = 0
const lines = text
.split('\n')
.map((raw) => raw.trimEnd())
.filter((line) => line.trim().length > 0)
.flatMap((line) => splitLongLine(line, limit))
for (const line of lines) {
if (current.length > 0 && size + line.length + 1 > limit) {
chunks.push(current.join('\n'))
current = []
size = 0
}
current.push(line)
size += line.length + 1
}
if (current.length > 0) chunks.push(current.join('\n'))
return chunks
}
const TIMED_LINE = /^\s*\[\d{1,3}:\d{2}\]/
function countTimedLines(text: string): number {
return text.split('\n').filter((l) => TIMED_LINE.test(l)).length
}
/**
* LLM 이 전사 조각을 다시 쓴 결과가 잘렸는지(출력 토큰 한도 등) 추정한다.
* - 입력에 시각 줄이 있으면: 출력의 시각 줄이 입력의 80% 미만이면 잘린 것으로 본다.
* - 없으면: 출력 길이가 입력의 50% 미만이면 잘린 것으로 본다.
* 잘린 결과로 전사를 덮어쓰면 회의 뒷부분이 문서·채팅·동기화에서 조용히 사라진다.
*/
export function looksTruncatedRewrite(input: string, output: string): boolean {
const trimmed = output.trim()
if (!trimmed) return true
const inputTimed = countTimedLines(input)
if (inputTimed > 0) {
return countTimedLines(trimmed) < Math.ceil(inputTimed * 0.8)
}
return trimmed.length < input.trim().length * 0.5
}