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.
This commit is contained in:
Yun Chan 2026-09-28 20:45:52 +09:00
parent 2428ede03d
commit ba9ef9741e
161 changed files with 17056 additions and 2379 deletions

View file

@ -0,0 +1,145 @@
import { describe, expect, it } from 'vitest'
import { ErrorCode } from '@d3ro/core/errors'
import {
normalizeErrorCode,
offersForceRestart,
presentError,
settingsTabOf,
} from '../../src/renderer/navigation/error-recovery'
import { buildMeetingErrorInfo, forceRestartLabel } from '../../src/renderer/pages/meeting/meeting-error'
import { canDismissOnboarding } from '../../src/renderer/components/onboarding-dismiss'
// 회귀:
// 1) voice:error 101(STT 모델 없음)이 닫을 수 없는 온보딩 모달을 열어 메인 창을 가뒀다.
// 2) 회의 후처리 실패(882)가 '회의를 시작할 수 없습니다'로 보이고, 주 버튼이 새 녹음을 강제로 시작했다.
// 3) 회의 오류 분류가 ErrorCode 와 맞지 않았다(1400=충돌, 200-220=마이크).
describe('presentError — voice', () => {
it('101 은 온보딩이 아니라 설정 → STT 탭 딥링크로 복구한다', () => {
const p = presentError({ context: 'voice', code: ErrorCode.STTModelNotFound })
expect(p.category).toBe('sttModelMissing')
expect(p.messageKey).toBe('voice.error.modelMissing')
expect(p.recoveries).toEqual([{ kind: 'openSettings', tab: 'stt' }])
expect(settingsTabOf(p)).toBe('stt')
})
it.each([103, 130, 131, 132])('%i 은 엔진 오류 문구를 유지하고 복구 동작은 없다', (code) => {
const p = presentError({ context: 'voice', code })
expect(p.category).toBe('sttEngine')
expect(p.messageKey).toBe('voice.error.engine')
expect(p.recoveries).toEqual([])
})
it('300 경고는 llmSkipped 문구, 300 오류는 원문 그대로', () => {
expect(presentError({ context: 'voice', code: 300, severity: 'warning' }).messageKey).toBe('voice.warning.llmSkipped')
const asError = presentError({ context: 'voice', code: 300, severity: 'error' })
expect(asError.category).toBe('general')
expect(asError.messageKey).toBeNull()
})
it('모르는 코드는 원문을 쓰고 설정 딥링크가 없다', () => {
const p = presentError({ context: 'voice', code: 999 })
expect(p.messageKey).toBeNull()
expect(settingsTabOf(p)).toBeNull()
})
})
describe('presentError — meetingProcessing', () => {
it('882 는 후처리 실패이고 강제 재시작(새 녹음)을 절대 제시하지 않는다', () => {
const p = presentError({ context: 'meetingProcessing', code: ErrorCode.MeetingProcessingFailed, message: '후처리 실패: SQLITE_FULL' })
expect(p.category).toBe('processing')
expect(offersForceRestart(p)).toBe(false)
})
it('후처리 문구에 model/already 같은 키워드가 있어도 processing 이다', () => {
for (const message of ['후처리 실패: model busy', '후처리 실패: already locked', '후처리 실패: audio']) {
const p = presentError({ context: 'meetingProcessing', code: 882, message })
expect(p.category).toBe('processing')
expect(offersForceRestart(p)).toBe(false)
}
})
})
describe('presentError — meetingStart', () => {
it.each([ErrorCode.MeetingAlreadyRecording, ErrorCode.CaptionAlreadyActive])('%i 는 충돌 → 강제 재시작', (code) => {
const p = presentError({ context: 'meetingStart', code, message: 'x' })
expect(p.category).toBe('collision')
expect(p.recoveries).toEqual([{ kind: 'forceRestart' }])
})
it('1400 은 ErrorCode 가 아니므로 충돌로 보지 않는다', () => {
expect(presentError({ context: 'meetingStart', code: 1400, message: 'x' }).category).toBe('general')
})
it.each([101, 103, 110, 130, 132, 140])('STT 코드 %i 는 STT 설정 + 재시도', (code) => {
const p = presentError({ context: 'meetingStart', code, message: 'x' })
expect(p.category).toBe('stt')
expect(p.recoveries).toEqual([{ kind: 'openSettings', tab: 'stt' }, { kind: 'forceRestart' }])
})
it.each([400, 401, 410, 420, 431])('오디오 코드 %i 는 오디오 설정 + 재시도', (code) => {
const p = presentError({ context: 'meetingStart', code, message: 'x' })
expect(p.category).toBe('audio')
expect(settingsTabOf(p)).toBe('audio')
})
it.each([200, 210, 220])('TTS 코드 %i 는 마이크 오류가 아니다', (code) => {
const p = presentError({ context: 'meetingStart', code, message: 'x' })
expect(p.category).toBe('general')
expect(settingsTabOf(p)).toBeNull()
})
it('시작 경로에 882 가 와도 강제 재시작을 주지 않는다', () => {
expect(offersForceRestart(presentError({ context: 'meetingStart', code: 882 }))).toBe(false)
})
it('코드가 없는 catch 경로는 문구 키워드로 폴백한다', () => {
expect(presentError({ context: 'meetingStart', message: 'Caption already active' }).category).toBe('collision')
expect(presentError({ context: 'meetingStart', message: 'whisper sidecar died' }).category).toBe('stt')
expect(presentError({ context: 'meetingStart', message: 'mic not found' }).category).toBe('audio')
expect(presentError({ context: 'meetingStart', message: 'ipc timeout' }).category).toBe('general')
})
it('숫자 문자열 코드도 정규화한다', () => {
expect(normalizeErrorCode('880')).toBe(880)
expect(normalizeErrorCode('STT_UNAVAILABLE')).toBeNull()
expect(normalizeErrorCode(undefined)).toBeNull()
expect(presentError({ context: 'meetingStart', code: '880' }).category).toBe('collision')
})
})
describe('buildMeetingErrorInfo', () => {
it('후처리 실패는 시작 실패 제목이 아니고 복구 버튼이 없다', () => {
const info = buildMeetingErrorInfo('meetingProcessing', '후처리 실패: disk full', 882)
expect(info.title).not.toBe('회의를 시작할 수 없습니다')
expect(info.category).toBe('processing')
expect(info.recoveries).toEqual([])
expect(info.code).toBe(882)
expect(info.message).toBe('후처리 실패: disk full')
})
it('충돌 라벨과 일반 라벨이 다르다', () => {
expect(forceRestartLabel('collision')).not.toBe(forceRestartLabel('general'))
})
it('코드·문구가 없으면 카테고리 기본값을 쓴다', () => {
const info = buildMeetingErrorInfo('meetingStart')
expect(info.category).toBe('general')
expect(info.code).toBe('MEETING_START_ERROR')
expect(info.message.length).toBeGreaterThan(0)
})
})
describe('canDismissOnboarding', () => {
it('첫 실행(미완료)은 success 전까지 닫을 수 없다', () => {
expect(canDismissOnboarding('select_mode', false)).toBe(false)
expect(canDismissOnboarding('local_ollama_setup', false)).toBe(false)
expect(canDismissOnboarding('success', false)).toBe(true)
})
it('이미 온보딩을 마친 사용자는 어느 단계에서든 닫을 수 있다', () => {
for (const phase of ['select_mode', 'local_ollama_setup', 'online_auth', 'failed'] as const) {
expect(canDismissOnboarding(phase, true)).toBe(true)
}
})
})

View file

@ -0,0 +1,147 @@
import fs from 'fs'
import path from 'path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { MouseButton, VK } from '@d3ro/core/keybinding'
type EffectFn = () => void | (() => void)
const effects: EffectFn[] = []
vi.mock('react', () => ({
useEffect: (fn: EffectFn) => {
effects.push(fn)
},
}))
const {
KeyBindingCaptureSession,
resolveCapturePort,
useKeyBindingCaptureSuspension,
} = await import('../../src/renderer/components/keybinding/keybinding-capture')
const { BROWSER_BUTTON_TO_MOUSE, NO_MODIFIERS, buildBinding, resolveKeyCode } = await import(
'../../src/renderer/components/keybinding/keybinding-recording'
)
const PICKER = path.resolve(
__dirname,
'../../src/renderer/components/keybinding/KeyBindingPicker.tsx'
)
function fakePort() {
const calls: string[] = []
return {
calls,
port: {
beginCapture: vi.fn(async () => {
calls.push('begin')
}),
endCapture: vi.fn(async () => {
calls.push('end')
}),
},
}
}
describe('KeyBindingPicker — 녹화 중 전역 트리거 중단 (r3-23)', () => {
beforeEach(() => {
effects.length = 0
})
it('피커가 열려 있는 동안 캡처 억제 훅을 open 으로 건다', () => {
const source = fs.readFileSync(PICKER, 'utf8')
expect(source).toContain('useKeyBindingCaptureSuspension(open)')
// 전역 on/off 는 hotkeyEnabled 를 저장하므로 캡처에 쓰면 안 된다.
expect(source).not.toMatch(/keybinding\s*\.\s*setEnabled/)
})
it('열리면 beginCapture, 닫히거나 언마운트되면 endCapture 를 한 번씩 보낸다', () => {
const { port, calls } = fakePort()
useKeyBindingCaptureSuspension(true, () => port)
expect(effects).toHaveLength(1)
const cleanup = effects[0]()
expect(calls).toEqual(['begin'])
expect(typeof cleanup).toBe('function')
if (typeof cleanup === 'function') cleanup()
expect(calls).toEqual(['begin', 'end'])
})
it('닫혀 있으면 아무것도 보내지 않는다', () => {
const { port, calls } = fakePort()
useKeyBindingCaptureSuspension(false, () => port)
const cleanup = effects[0]()
expect(cleanup).toBeUndefined()
expect(calls).toEqual([])
})
it('세션은 begin/end 를 중복 전송하지 않고 begin 없이 end 를 보내지 않는다', () => {
const { port, calls } = fakePort()
const session = new KeyBindingCaptureSession(port)
session.end()
session.begin()
session.begin()
expect(session.isActive).toBe(true)
session.end()
session.end()
expect(session.isActive).toBe(false)
expect(calls).toEqual(['begin', 'end'])
})
it('IPC 실패는 녹화를 막지 않는다', async () => {
const session = new KeyBindingCaptureSession({
beginCapture: () => Promise.reject(new Error('no handler')),
endCapture: () => Promise.reject(new Error('no handler')),
})
expect(() => {
session.begin()
session.end()
}).not.toThrow()
await Promise.resolve()
})
it('포트가 없으면(null) 조용히 아무것도 하지 않는다', () => {
const session = new KeyBindingCaptureSession(null)
session.begin()
expect(session.isActive).toBe(false)
})
it('preload API 구조로 포트를 판별한다', () => {
expect(resolveCapturePort(undefined)).toBeNull()
expect(resolveCapturePort({ setEnabled: () => undefined })).toBeNull()
expect(resolveCapturePort({ beginCapture: () => undefined })).toBeNull()
const begin = vi.fn(() => Promise.resolve({ success: true }))
const end = vi.fn(() => Promise.resolve({ success: true }))
const port = resolveCapturePort({ beginCapture: begin, endCapture: end })
expect(port).not.toBeNull()
void port?.beginCapture()
void port?.endCapture()
expect(begin).toHaveBeenCalledTimes(1)
expect(end).toHaveBeenCalledTimes(1)
})
})
describe('keybinding-recording — 추출된 녹화 규칙 (동작 보존)', () => {
it('좌/우 수정자를 location 으로 구분한다', () => {
expect(resolveKeyCode({ keyCode: 17, which: 17, location: 1 })).toBe(VK.CtrlLeft)
expect(resolveKeyCode({ keyCode: 17, which: 17, location: 2 })).toBe(VK.CtrlRight)
expect(resolveKeyCode({ keyCode: 16, which: 16, location: 2 })).toBe(VK.ShiftRight)
expect(resolveKeyCode({ keyCode: 18, which: 18, location: 1 })).toBe(VK.AltLeft)
expect(resolveKeyCode({ keyCode: 93, which: 93, location: 2 })).toBe(VK.MetaRight)
expect(resolveKeyCode({ keyCode: 93, which: 93, location: 0 })).toBe(93)
expect(resolveKeyCode({ keyCode: 0, which: 65, location: 0 })).toBe(65)
})
it('주 키는 비수정자 키, 없으면 마지막 수정자', () => {
expect(buildBinding([], NO_MODIFIERS)).toBeNull()
const combo = buildBinding([VK.CtrlLeft, 65], { ...NO_MODIFIERS, ctrl: true })
expect(combo).toMatchObject({ device: 'keyboard', code: 65, ctrl: true })
const mods = buildBinding([VK.CtrlLeft, VK.AltRight], { ...NO_MODIFIERS, ctrl: true })
expect(mods?.code).toBe(VK.AltRight)
})
it('브라우저 마우스 버튼을 uiohook 코드로 옮긴다', () => {
expect(BROWSER_BUTTON_TO_MOUSE[1]).toBe(MouseButton.Middle)
expect(BROWSER_BUTTON_TO_MOUSE[2]).toBe(MouseButton.Right)
expect(BROWSER_BUTTON_TO_MOUSE[3]).toBe(MouseButton.Back)
expect(BROWSER_BUTTON_TO_MOUSE[4]).toBe(MouseButton.Forward)
})
})

View file

@ -0,0 +1,129 @@
// tests/unit/stt-model-download-redteam-r3-24.test.ts
// STT 탭 모델 다운로드가 실패/취소로 끝나도 '다운로드 중 (x%)' 에 멈추지 않는지 회귀 검증.
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { ErrorCode, ipcError, ipcSuccess, type IPCResult } from '@d3ro/core/errors'
import {
classifyModelDownloadResult,
releaseIfCurrent,
runModelDownload,
type ModelDownloadView,
} from '../../src/renderer/components/stt/modelDownload'
/** STTTab 의 downloadingModelId / downloadError 상태를 흉내 내는 가짜 view */
function fakeView(): ModelDownloadView & {
downloadingModelId: string | null
error: { modelId: string; message: string } | null
events: string[]
} {
const state = {
downloadingModelId: null as string | null,
error: null as { modelId: string; message: string } | null,
events: [] as string[],
}
return Object.assign(state, {
started: (id: string) => {
state.events.push(`started:${id}`)
state.error = null
state.downloadingModelId = id
},
succeeded: (id: string) => {
state.events.push(`succeeded:${id}`)
state.downloadingModelId = releaseIfCurrent(state.downloadingModelId, id)
},
cancelled: (id: string) => {
state.events.push(`cancelled:${id}`)
state.downloadingModelId = releaseIfCurrent(state.downloadingModelId, id)
},
failed: (id: string, message: string) => {
state.events.push(`failed:${id}`)
state.downloadingModelId = releaseIfCurrent(state.downloadingModelId, id)
state.error = { modelId: id, message }
},
})
}
describe('runModelDownload', () => {
it('ipcError(사이드카 기동 실패 등)면 진행 표시를 풀고 오류 메시지를 노출한다', async () => {
const view = fakeView()
const outcome = await runModelDownload(
'large-v3-turbo',
{ download: async () => ipcError<void>(ErrorCode.STTModelDownloadFailed, '다운로드 시작 실패 (HTTP 500): boom') },
view,
)
expect(outcome).toEqual({ kind: 'failed', message: '다운로드 시작 실패 (HTTP 500): boom' })
expect(view.downloadingModelId).toBeNull()
expect(view.error).toEqual({ modelId: 'large-v3-turbo', message: '다운로드 시작 실패 (HTTP 500): boom' })
})
it('취소 결과는 오류 없이 진행 표시만 푼다', async () => {
const view = fakeView()
const outcome = await runModelDownload(
'small',
{ download: async () => ipcError<void>(ErrorCode.STTModelDownloadCancelled, '모델 다운로드 취소: small') },
view,
)
expect(outcome.kind).toBe('cancelled')
expect(view.downloadingModelId).toBeNull()
expect(view.error).toBeNull()
})
it('invoke 자체가 reject 되어도 진행 표시를 푼다', async () => {
const view = fakeView()
const outcome = await runModelDownload(
'small',
{ download: async () => { throw new Error('ipc channel closed') } },
view,
)
expect(outcome).toEqual({ kind: 'failed', message: 'ipc channel closed' })
expect(view.downloadingModelId).toBeNull()
})
it('성공하면 succeeded 로 끝나고 오류가 없다', async () => {
const view = fakeView()
const outcome = await runModelDownload('small', { download: async () => ipcSuccess(undefined) }, view)
expect(outcome.kind).toBe('succeeded')
expect(view.events).toEqual(['started:small', 'succeeded:small'])
expect(view.downloadingModelId).toBeNull()
expect(view.error).toBeNull()
})
it('늦게 도착한 A 실패가 그 사이 시작한 B 의 진행 표시를 지우지 않는다', async () => {
const view = fakeView()
let failA: (r: IPCResult<void>) => void = () => undefined
const pendingA = runModelDownload(
'A',
{ download: () => new Promise<IPCResult<void>>((resolve) => { failA = resolve }) },
view,
)
view.started('B')
failA(ipcError<void>(ErrorCode.STTModelDownloadFailed, 'A failed'))
await pendingA
expect(view.downloadingModelId).toBe('B')
})
})
describe('classifyModelDownloadResult', () => {
it('실패 코드별 결말', () => {
expect(classifyModelDownloadResult(ipcSuccess(undefined))).toEqual({ kind: 'succeeded' })
expect(classifyModelDownloadResult(ipcError(ErrorCode.STTModelDownloadCancelled, 'x'))).toEqual({ kind: 'cancelled' })
expect(classifyModelDownloadResult(ipcError(ErrorCode.STTModelDownloadFailed, 'y'))).toEqual({
kind: 'failed',
message: 'y',
})
expect(classifyModelDownloadResult({ thrown: 'raw' })).toEqual({ kind: 'failed', message: 'raw' })
})
})
describe('STTTab wiring', () => {
it('handleDownloadModel 이 IPC 결과를 버리지 않고 runModelDownload 로 처리한다', () => {
const src = readFileSync(
join(__dirname, '../../src/renderer/components/STTTab.tsx'),
'utf8',
)
expect(src).toContain('await runModelDownload(')
expect(src).not.toMatch(/await window\.electronAPI\.stt\.downloadModel\(\{ modelId \}\)\s*\n\s*\}, \[\]\)/)
})
})

View file

@ -0,0 +1,319 @@
// tests/unit/system-audio-capture-redteam-r3-22.test.ts
// SystemAudioCaptureController: stop-during-start 취소, off/on 중복 획득 방지,
// getDisplayMedia 실패 시 loopback 해제를 fake port로 검증한다.
import { describe, it, expect, vi } from 'vitest'
import {
SystemAudioCaptureController,
type PcmPipeline,
type SystemAudioPort,
type SystemAudioStream,
} from '../../src/renderer/utils/systemAudioCaptureController'
import { float32ToPcm16 } from '../../src/renderer/utils/systemAudioCapture'
interface Deferred<T> {
promise: Promise<T>
resolve: (v: T) => void
reject: (e: unknown) => void
}
function deferred<T>(): Deferred<T> {
let resolve!: (v: T) => void
let reject!: (e: unknown) => void
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
class FakeStream implements SystemAudioStream {
stopped = false
videoDropped = false
constructor(readonly id: number, private readonly audio = true) {}
dropVideoTracks(): void {
this.videoDropped = true
}
hasAudioTrack(): boolean {
return this.audio
}
stop(): void {
this.stopped = true
}
}
class FakePipeline implements PcmPipeline {
closed = false
constructor(readonly stream: FakeStream, readonly onPcm: (b: ArrayBuffer) => void) {}
close(): void {
this.closed = true
}
}
class FakePort implements SystemAudioPort<FakeStream> {
loopbackEnabled = false
enableCalls = 0
disableCalls = 0
displayRequests: Deferred<FakeStream>[] = []
pipelines: FakePipeline[] = []
/** 루프백 핸들러가 꺼진 상태에서 getDisplayMedia 요청 → 실제 Electron처럼 실패 */
requestsWithoutLoopback = 0
async enableLoopback(): Promise<void> {
this.enableCalls++
this.loopbackEnabled = true
}
async disableLoopback(): Promise<void> {
this.disableCalls++
this.loopbackEnabled = false
}
getDisplayMedia(): Promise<FakeStream> {
if (!this.loopbackEnabled) this.requestsWithoutLoopback++
const d = deferred<FakeStream>()
this.displayRequests.push(d)
return d.promise
}
createPcmPipeline(stream: FakeStream, onPcm: (b: ArrayBuffer) => void): PcmPipeline {
const p = new FakePipeline(stream, onPcm)
this.pipelines.push(p)
return p
}
openPipelines(): FakePipeline[] {
return this.pipelines.filter((p) => !p.closed)
}
}
/** 마이크로태스크 큐 비우기 */
async function flush(): Promise<void> {
for (let i = 0; i < 10; i++) await Promise.resolve()
}
function setup(): { port: FakePort; ctrl: SystemAudioCaptureController<FakeStream>; onPcm: ReturnType<typeof vi.fn> } {
const port = new FakePort()
const onPcm = vi.fn()
const ctrl = new SystemAudioCaptureController(port, { onPcm })
return { port, ctrl, onPcm }
}
describe('SystemAudioCaptureController', () => {
it('starts: enable loopback → getDisplayMedia → disable loopback → pipeline', async () => {
const { port, ctrl, onPcm } = setup()
const started = ctrl.start()
expect(ctrl.getState()).toBe('starting')
await flush()
const stream = new FakeStream(1)
port.displayRequests[0].resolve(stream)
await started
expect(ctrl.getState()).toBe('active')
expect(ctrl.isActive()).toBe(true)
expect(port.enableCalls).toBe(1)
expect(port.disableCalls).toBe(1)
expect(port.loopbackEnabled).toBe(false)
expect(stream.videoDropped).toBe(true)
expect(port.openPipelines()).toHaveLength(1)
expect(port.pipelines[0].onPcm).toBe(onPcm)
ctrl.stop()
expect(ctrl.getState()).toBe('idle')
expect(port.pipelines[0].closed).toBe(true)
expect(stream.stopped).toBe(true)
})
it('stop while getDisplayMedia is pending cancels the start and releases the stream', async () => {
const { port, ctrl } = setup()
const started = ctrl.start()
await flush()
expect(port.displayRequests).toHaveLength(1)
ctrl.stop() // 대기 중 STOP 도착
expect(ctrl.getState()).toBe('idle')
const stream = new FakeStream(1)
port.displayRequests[0].resolve(stream)
await expect(started).resolves.toBeUndefined()
expect(ctrl.getState()).toBe('idle')
expect(stream.stopped).toBe(true)
expect(port.pipelines).toHaveLength(0) // 캡처 파이프라인이 만들어지지 않음
expect(port.loopbackEnabled).toBe(false)
})
it('stop issued synchronously after start acquires nothing', async () => {
const { port, ctrl } = setup()
const started = ctrl.start()
ctrl.stop()
await started
expect(port.displayRequests).toHaveLength(0)
expect(port.loopbackEnabled).toBe(false)
expect(ctrl.getState()).toBe('idle')
})
it('stop while enableLoopback is pending disables loopback without requesting media', async () => {
const { port, ctrl } = setup()
const enable = deferred<void>()
port.enableLoopback = async () => {
port.enableCalls++
await enable.promise
port.loopbackEnabled = true
}
const started = ctrl.start()
await flush()
expect(port.enableCalls).toBe(1)
ctrl.stop()
enable.resolve()
await started
expect(port.displayRequests).toHaveLength(0)
expect(port.loopbackEnabled).toBe(false)
expect(port.disableCalls).toBe(1)
})
it('start while starting returns the same pending promise (no second acquisition)', async () => {
const { port, ctrl } = setup()
const a = ctrl.start()
const b = ctrl.start()
expect(b).toBe(a)
await flush()
expect(port.enableCalls).toBe(1)
expect(port.displayRequests).toHaveLength(1)
port.displayRequests[0].resolve(new FakeStream(1))
await a
expect(port.openPipelines()).toHaveLength(1)
})
it('start while active is a no-op', async () => {
const { port, ctrl } = setup()
const a = ctrl.start()
await flush()
port.displayRequests[0].resolve(new FakeStream(1))
await a
await ctrl.start()
expect(port.enableCalls).toBe(1)
expect(port.openPipelines()).toHaveLength(1)
})
it('on → off → on inside the pending window leaves exactly one stoppable capture', async () => {
const { port, ctrl } = setup()
const first = ctrl.start()
await flush()
ctrl.stop()
const second = ctrl.start()
await flush()
// 두 번째 start는 첫 starter 정리 전까지 loopback/getDisplayMedia를 건드리지 않는다
expect(port.displayRequests).toHaveLength(1)
const s1 = new FakeStream(1)
port.displayRequests[0].resolve(s1)
await first
await flush()
expect(s1.stopped).toBe(true)
// 이제 두 번째 starter가 자기 loopback 핸들러로 요청
expect(port.displayRequests).toHaveLength(2)
expect(port.requestsWithoutLoopback).toBe(0)
const s2 = new FakeStream(2)
port.displayRequests[1].resolve(s2)
await second
expect(ctrl.getState()).toBe('active')
expect(port.openPipelines()).toHaveLength(1)
expect(port.openPipelines()[0].stream).toBe(s2)
ctrl.stop()
expect(port.openPipelines()).toHaveLength(0)
expect(s2.stopped).toBe(true)
})
it('on → off → on → off leaves nothing running', async () => {
const { port, ctrl } = setup()
const first = ctrl.start()
await flush()
ctrl.stop()
const second = ctrl.start()
ctrl.stop()
port.displayRequests[0].resolve(new FakeStream(1))
await first
await second
await flush()
expect(ctrl.getState()).toBe('idle')
expect(port.displayRequests).toHaveLength(1) // 두 번째 starter는 시작 전에 취소됨
expect(port.pipelines).toHaveLength(0)
expect(port.loopbackEnabled).toBe(false)
})
it('failed getDisplayMedia always disables loopback and rejects to the caller', async () => {
const { port, ctrl } = setup()
const started = ctrl.start()
await flush()
port.displayRequests[0].reject(new Error('denied'))
await expect(started).rejects.toThrow('denied')
expect(port.loopbackEnabled).toBe(false)
expect(port.disableCalls).toBe(1)
expect(ctrl.getState()).toBe('idle')
// 실패 후 재시작 가능
const again = ctrl.start()
await flush()
port.displayRequests[1].resolve(new FakeStream(2))
await again
expect(ctrl.getState()).toBe('active')
})
it('failed getDisplayMedia after stop still disables loopback but does not reject', async () => {
const { port, ctrl } = setup()
const started = ctrl.start()
await flush()
ctrl.stop()
port.displayRequests[0].reject(new Error('denied'))
await expect(started).resolves.toBeUndefined()
expect(port.loopbackEnabled).toBe(false)
})
it('stream without an audio track is stopped and the start rejects', async () => {
const { port, ctrl } = setup()
const started = ctrl.start()
await flush()
const stream = new FakeStream(1, false)
port.displayRequests[0].resolve(stream)
await expect(started).rejects.toThrow('No audio track')
expect(stream.stopped).toBe(true)
expect(port.pipelines).toHaveLength(0)
expect(ctrl.getState()).toBe('idle')
})
it('stop is idempotent when nothing was started', () => {
const { port, ctrl } = setup()
expect(() => {
ctrl.stop()
ctrl.stop()
}).not.toThrow()
expect(ctrl.getState()).toBe('idle')
expect(port.enableCalls).toBe(0)
})
it('cleanup errors are reported, not thrown', async () => {
const port = new FakePort()
const onCleanupError = vi.fn()
const ctrl = new SystemAudioCaptureController(port, { onPcm: vi.fn(), onCleanupError })
const started = ctrl.start()
await flush()
const stream = new FakeStream(1)
stream.stop = () => {
throw new Error('stop failed')
}
port.displayRequests[0].resolve(stream)
await started
expect(() => ctrl.stop()).not.toThrow()
expect(onCleanupError).toHaveBeenCalledTimes(1)
})
})
describe('float32ToPcm16', () => {
it('clamps and scales samples to PCM16', () => {
const out = new Int16Array(float32ToPcm16(new Float32Array([0, 1, -1, 2, -2, 0.5])))
expect(Array.from(out)).toEqual([0, 32767, -32768, 32767, -32768, 16383])
})
})