feat: ship Wave 5-6 multi-surface hygiene, optimization, and bug fixes

This commit is contained in:
Yun Chan 2026-11-14 11:51:41 +09:00
parent 01ef3293cf
commit 66b6b45ba9
399 changed files with 17828 additions and 11330 deletions

View file

@ -0,0 +1,246 @@
// tests/main/db/sqlite-optimizations.test.ts
// SQLite 4대 수술 검증:
// 1) WAL 성능 PRAGMA (synchronous=NORMAL, temp_store=MEMORY, cache_size=-16000)
// 2) FTS5 trigram 가상 테이블 + INSERT/UPDATE/DELETE 트리거 + UnifiedSearchService 연동
// 3) RAG Float32 바이너리 BLOB + 메모리 캐시 (JSON.parse 0회)
// 4) PersonalGraphService 단일 트랜잭션 일괄 반영
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { eq } from 'drizzle-orm'
import { createTestDb } from '../../helpers/createTestDb'
import { bindTestDatabase, unbindTestDatabase } from '../../../src/main/db'
import {
history,
meetingMemos,
meetingSessions,
ragChunks,
} from '../../../src/main/db/schema'
import {
getUnifiedSearchService,
resetUnifiedSearchServiceForTests,
} from '../../../src/main/services/UnifiedSearchService'
import { SqliteChunkStore } from '../../../src/main/services/rag/chunk-store'
import { rankChunks } from '../../../src/main/services/rag/retrieval'
import {
getPersonalGraphService,
resetPersonalGraphServiceForTests,
} from '../../../src/main/services/PersonalGraphService'
const BASE_TS = 1_730_000_000_000
describe('SQLite 성능 및 검색/벡터 최적화', () => {
let testDb: ReturnType<typeof createTestDb>
beforeEach(() => {
testDb = createTestDb()
bindTestDatabase(testDb.db)
resetUnifiedSearchServiceForTests()
resetPersonalGraphServiceForTests()
})
afterEach(() => {
resetUnifiedSearchServiceForTests()
resetPersonalGraphServiceForTests()
unbindTestDatabase()
testDb.close()
vi.restoreAllMocks()
})
it('applySchema_실행시_WAL성능프라그마와FTS5트리그램테이블을설정한다', () => {
const synchronous = testDb.sqlite.pragma('synchronous', { simple: true })
const tempStore = testDb.sqlite.pragma('temp_store', { simple: true })
const cacheSize = testDb.sqlite.pragma('cache_size', { simple: true })
// synchronous: 1 = NORMAL, temp_store: 2 = MEMORY, cache_size: -16000 (~16MB)
expect(synchronous).toBe(1)
expect(tempStore).toBe(2)
expect(cacheSize).toBe(-16000)
const chunkColumns = testDb.sqlite.pragma('table_info(rag_chunks)') as Array<{ name: string }>
expect(chunkColumns.map((col) => col.name)).toContain('embedding_blob')
const ftsTables = testDb.sqlite
.prepare(
`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('history_fts', 'meeting_sessions_fts', 'meeting_memos_fts') ORDER BY name`
)
.all() as Array<{ name: string }>
expect(ftsTables.map((row) => row.name)).toEqual([
'history_fts',
'meeting_memos_fts',
'meeting_sessions_fts',
])
})
it('UnifiedSearchService_3자이상검색시_FTS5인덱스를타고수정삭제와동기화된다', () => {
testDb.db
.insert(history)
.values({
id: 'rec-1',
title: '주간 아키텍처 점검',
originalText: '초안 텍스트',
polishedText: '데이터베이스 인덱싱 최적화 방안을 논의했습니다.',
summaryText: '인덱싱 요약',
duration: 12.5,
createdAt: BASE_TS + 100,
updatedAt: BASE_TS + 100,
})
.run()
testDb.db
.insert(meetingSessions)
.values({
id: 'mtg-1',
title: '스프린트 회고',
status: 'completed',
startedAt: BASE_TS + 200,
rawTranscript: '[00:01] 백엔드 인덱싱 지연을 줄였습니다.',
createdAt: BASE_TS + 200,
updatedAt: BASE_TS + 200,
})
.run()
testDb.db
.insert(meetingSessions)
.values({
id: 'mtg-2',
title: '배포 체크리스트',
status: 'completed',
startedAt: BASE_TS + 300,
rawTranscript: '[00:05] 릴리스 일정 공유',
createdAt: BASE_TS + 300,
updatedAt: BASE_TS + 300,
})
.run()
testDb.db
.insert(meetingMemos)
.values({
id: 'memo-1',
sessionId: 'mtg-2',
content: '메모에만 적힌 인덱싱 확인 항목',
timestampMs: 5_000,
createdAt: BASE_TS + 310,
})
.run()
// EXPLAIN QUERY PLAN 검증: 전체 테이블 스캔 대신 history_fts 가상 테이블 인덱스를 타야 한다.
const planRows = testDb.sqlite
.prepare(
`EXPLAIN QUERY PLAN SELECT id FROM history WHERE id IN (SELECT row_id FROM history_fts WHERE history_fts MATCH '"인덱싱"')`
)
.all() as Array<{ detail: string }>
expect(planRows.some((row) => row.detail.includes('history_fts'))).toBe(true)
expect(planRows.some((row) => row.detail.includes('SCAN history '))).toBe(false)
const initial = getUnifiedSearchService().search({ query: '인덱싱' })
expect(initial.total).toBe(3)
expect(initial.results.map((item) => item.id)).toEqual(['mtg-2', 'mtg-1', 'rec-1'])
// UPDATE 트리거 동기화 검증
testDb.db
.update(history)
.set({
polishedText: '쿼리 플랜 개편안을 확정했습니다 (100% 달성).',
summaryText: '개편안 요약',
updatedAt: BASE_TS + 400,
})
.where(eq(history.id, 'rec-1'))
.run()
// DELETE 트리거 동기화 검증
testDb.db.delete(meetingMemos).where(eq(meetingMemos.id, 'memo-1')).run()
const afterMutation = getUnifiedSearchService().search({ query: '인덱싱' })
expect(afterMutation.results.map((item) => item.id)).toEqual(['mtg-1'])
// 리터럴 % 와일드카드 및 2자 이하 짧은 검색어도 정확히 일치해야 한다.
const literalPercent = getUnifiedSearchService().search({ query: '100% 달성' })
expect(literalPercent.results.map((item) => item.id)).toEqual(['rec-1'])
const shortQuery = getUnifiedSearchService().search({ query: '회고' })
expect(shortQuery.results.map((item) => item.id)).toEqual(['mtg-1'])
})
it('SqliteChunkStore_임베딩저장시_Float32바이너리와메모리캐시로JSON재파싱없이검색한다', () => {
const store = new SqliteChunkStore()
store.insertDocument({
id: 'doc-1',
fileName: 'architecture.md',
filePath: '/docs/architecture.md',
fileType: 'md',
chunkCount: 2,
indexed: true,
indexedAt: BASE_TS,
addedAt: BASE_TS,
})
store.replaceChunks('doc-1', ['SQLite WAL 모드 설명', '벡터 임베딩 바이너리 직렬화'])
const chunks = store.listChunks('doc-1')
expect(chunks).toHaveLength(2)
store.setEmbedding(chunks[0].id, [1, 0, 0])
store.setEmbedding(chunks[1].id, [0, 1, 0])
const rawRow = testDb.db
.select()
.from(ragChunks)
.where(eq(ragChunks.id, chunks[0].id))
.get()
expect(rawRow?.embeddingBlob?.byteLength).toBe(12)
const parseSpy = vi.spyOn(JSON, 'parse')
const embeddedFirst = store.listEmbeddedChunks()
expect(embeddedFirst).toHaveLength(2)
const ranked = rankChunks(
[0.05, 0.99, 0],
embeddedFirst,
new Map([['doc-1', 'architecture.md']]),
2,
)
expect(ranked[0].content).toBe('벡터 임베딩 바이너리 직렬화')
expect(parseSpy).not.toHaveBeenCalled()
// 두 번째 조회는 메모리 캐시를 그대로 반환하고, replaceChunks/removeDocument 시 즉시 무효화한다.
const selectSpy = vi.spyOn(testDb.db, 'select')
const embeddedCached = store.listEmbeddedChunks()
expect(embeddedCached).toHaveLength(2)
expect(selectSpy).not.toHaveBeenCalled()
expect(store.counts()).toEqual({ documentCount: 1, totalChunks: 2 })
store.removeDocument('doc-1')
expect(store.listEmbeddedChunks()).toEqual([])
expect(store.counts()).toEqual({ documentCount: 0, totalChunks: 0 })
})
it('PersonalGraphService_다중문장색인중중간실패시_단일트랜잭션으로전체롤백하고정상시일괄반영한다', () => {
const graph = getPersonalGraphService()
// phrase_edges 쓰기 단계에서 실패를 유도해 앞선 personal_phrases INSERT 까지 원자적으로 롤백되는지 검증한다.
testDb.sqlite.exec(`
CREATE TRIGGER fail_edge_insert BEFORE INSERT ON phrase_edges
BEGIN
SELECT RAISE(ABORT, 'simulated_edge_failure');
END;
`)
graph.indexText(
'배포 파이프라인 성능 점검 결과를 공유드립니다. 배포 파이프라인 성능 점검 지표를 확인했습니다.',
{ source: 'typed', appName: 'Slack.exe', at: BASE_TS },
)
expect(graph.getStats(3650).nodes).toBe(0)
testDb.sqlite.exec('DROP TRIGGER fail_edge_insert;')
graph.indexText(
'배포 파이프라인 성능 점검 결과를 공유드립니다. 배포 파이프라인 성능 점검 지표를 확인했습니다.',
{ source: 'typed', appName: 'Slack.exe', at: BASE_TS },
)
const stats = graph.getStats(3650)
expect(stats.nodes).toBe(2)
expect(stats.followsEdges).toBe(1)
expect(stats.sharesTermsEdges).toBe(1)
})
})

View file

@ -0,0 +1,86 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const state = vi.hoisted(() => ({
mainWindow: null as null | {
isDestroyed: () => boolean
webContents: { isDestroyed?: () => boolean; send: ReturnType<typeof vi.fn> }
},
allWindows: [] as Array<{
isDestroyed: () => boolean
webContents: { isDestroyed?: () => boolean; send: ReturnType<typeof vi.fn> }
}>,
}))
vi.mock('electron', () => ({
BrowserWindow: {
getAllWindows: () => state.allWindows,
},
}))
vi.mock('../../../src/main/windows/WindowManager', () => ({
getMainWindow: () => state.mainWindow,
}))
import { broadcastToAllWindows, safeSendToRenderer } from '../../../src/main/ipc/renderer-broadcast'
describe('renderer-broadcast IPC helper', () => {
afterEach(() => {
state.mainWindow = null
state.allWindows = []
vi.clearAllMocks()
})
it('safeSendToRenderer_mainWindowLive_sendsPayloadAndSkipsDestroyedStates', () => {
const liveSend = vi.fn()
state.mainWindow = {
isDestroyed: () => false,
webContents: { isDestroyed: () => false, send: liveSend },
}
safeSendToRenderer('voice:error', { code: 1 })
expect(liveSend).toHaveBeenCalledTimes(1)
expect(liveSend).toHaveBeenCalledWith('voice:error', { code: 1 })
const destroyedWindowSend = vi.fn()
state.mainWindow = {
isDestroyed: () => true,
webContents: { isDestroyed: () => false, send: destroyedWindowSend },
}
safeSendToRenderer('voice:error', { code: 2 })
expect(destroyedWindowSend).not.toHaveBeenCalled()
const destroyedContentsSend = vi.fn()
state.mainWindow = {
isDestroyed: () => false,
webContents: { isDestroyed: () => true, send: destroyedContentsSend },
}
safeSendToRenderer('voice:error', { code: 3 })
expect(destroyedContentsSend).not.toHaveBeenCalled()
state.mainWindow = null
safeSendToRenderer('voice:error', { code: 4 })
expect(liveSend).toHaveBeenCalledTimes(1)
})
it('broadcastToAllWindows_mixedWindows_sendsOnlyToNonDestroyedWindows', () => {
const sendLiveA = vi.fn()
const sendDestroyedWin = vi.fn()
const sendDestroyedContents = vi.fn()
const sendMinimalFake = vi.fn()
state.allWindows = [
{ isDestroyed: () => false, webContents: { isDestroyed: () => false, send: sendLiveA } },
{ isDestroyed: () => true, webContents: { isDestroyed: () => false, send: sendDestroyedWin } },
{ isDestroyed: () => false, webContents: { isDestroyed: () => true, send: sendDestroyedContents } },
{ isDestroyed: () => false, webContents: { send: sendMinimalFake } },
]
broadcastToAllWindows('config:changed', { key: 'theme', value: 'dark' })
expect(sendLiveA).toHaveBeenCalledTimes(1)
expect(sendLiveA).toHaveBeenCalledWith('config:changed', { key: 'theme', value: 'dark' })
expect(sendDestroyedWin).not.toHaveBeenCalled()
expect(sendDestroyedContents).not.toHaveBeenCalled()
expect(sendMinimalFake).toHaveBeenCalledTimes(1)
expect(sendMinimalFake).toHaveBeenCalledWith('config:changed', { key: 'theme', value: 'dark' })
})
})

View file

@ -1,129 +1,134 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ErrorCode } from '@d3ro/core/errors'
import type { History, MeetingMemoRow, MeetingSessionRow } from '../../../src/main/db/schema'
import {
bindTestDatabase,
unbindTestDatabase,
} from '../../../src/main/db'
import {
history,
meetingMemos,
meetingSessions,
type NewHistory,
type NewMeetingMemoRow,
type NewMeetingSessionRow,
} from '../../../src/main/db/schema'
import {
createUnifiedSearchExcerpt,
getUnifiedSearchService,
normalizeUnifiedSearchQuery,
resetUnifiedSearchServiceForTests,
} from '../../../src/main/services/UnifiedSearchService'
import { createTestDb } from '../../helpers/createTestDb'
interface MockBuilderOptions {
get?: unknown
all?: unknown[]
error?: Error
}
function createMockBuilder(options: MockBuilderOptions = {}) {
const builder = {
from: vi.fn(),
where: vi.fn(),
orderBy: vi.fn(),
limit: vi.fn(),
get: vi.fn(),
all: vi.fn(),
function makeHistoryRow(overrides: Partial<NewHistory> & { id: string }): NewHistory {
return {
title: '제품 메모',
originalText: '초기 원문',
polishedText: '다음 분기 출시 계획을 정리했습니다.',
focusedApp: null,
focusedAppName: null,
focusedAppWindowTitle: null,
mode: 'dictation',
status: 'completed',
errorCode: null,
audioLocalPath: null,
duration: 10,
detectedLanguage: 'ko',
micDevice: null,
wordCount: 6,
sttModel: null,
llmModel: null,
sttLatencyMs: null,
llmLatencyMs: null,
createdAt: 100,
updatedAt: 100,
appVersion: '1.9.0',
summaryText: null,
isFavorite: false,
...overrides,
}
builder.from.mockImplementation(() => {
if (options.error !== undefined) throw options.error
return builder
})
builder.where.mockReturnValue(builder)
builder.orderBy.mockReturnValue(builder)
builder.limit.mockReturnValue(builder)
builder.get.mockReturnValue(options.get ?? null)
builder.all.mockReturnValue(options.all ?? [])
return builder
}
const selectQueue: ReturnType<typeof createMockBuilder>[] = []
const mockDb = {
select: vi.fn(() => selectQueue.shift() ?? createMockBuilder()),
function makeMeetingRow(
overrides: Partial<NewMeetingSessionRow> & { id: string },
): NewMeetingSessionRow {
return {
title: '주간 회의',
status: 'completed',
startedAt: 200,
endedAt: 300,
durationMs: 100,
rawTranscript: '출시 계획을 다음 주에 검토합니다.',
editedTranscript: null,
minutesMarkdown: null,
minutesJson: null,
sttModel: null,
llmModel: null,
sttLatencyMs: null,
llmLatencyMs: null,
errorMessage: null,
createdAt: 200,
updatedAt: 300,
...overrides,
}
}
vi.mock('../../../src/main/db', () => ({
getDatabase: () => mockDb,
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
}),
}))
const record: History = {
id: 'record-1',
title: '제품 메모',
originalText: '초기 원문',
polishedText: '다음 분기 출시 계획을 정리했습니다.',
focusedApp: null,
focusedAppName: null,
focusedAppWindowTitle: null,
mode: 'dictation',
status: 'completed',
errorCode: null,
audioLocalPath: null,
duration: 10,
detectedLanguage: 'ko',
micDevice: null,
wordCount: 6,
sttModel: null,
llmModel: null,
sttLatencyMs: null,
llmLatencyMs: null,
createdAt: 100,
updatedAt: 100,
appVersion: '1.9.0',
summaryText: null,
isFavorite: false,
}
const meeting: MeetingSessionRow = {
id: 'meeting-1',
title: '주간 회의',
status: 'completed',
startedAt: 200,
endedAt: 300,
durationMs: 100,
rawTranscript: '출시 계획을 다음 주에 검토합니다.',
editedTranscript: null,
minutesMarkdown: null,
minutesJson: null,
sttModel: null,
llmModel: null,
sttLatencyMs: null,
llmLatencyMs: null,
errorMessage: null,
createdAt: 200,
updatedAt: 300,
function makeMemoRow(
overrides: Partial<NewMeetingMemoRow> & { id: string; sessionId: string },
): NewMeetingMemoRow {
return {
content: '기본 메모 내용',
timestampMs: 10_000,
revision: 1,
createdAt: 210,
updatedAt: 210,
...overrides,
}
}
describe('UnifiedSearchService', () => {
let closeDb: (() => void) | null = null
function useFreshTestDb() {
const testDb = createTestDb()
closeDb = testDb.close
bindTestDatabase(testDb.db)
return testDb
}
beforeEach(() => {
selectQueue.length = 0
vi.clearAllMocks()
resetUnifiedSearchServiceForTests()
unbindTestDatabase()
})
it('normalizes input and creates a bounded excerpt around the match', async () => {
const { createUnifiedSearchExcerpt, normalizeUnifiedSearchQuery } = await import(
'../../../src/main/services/UnifiedSearchService'
)
afterEach(() => {
resetUnifiedSearchServiceForTests()
unbindTestDatabase()
if (closeDb) {
closeDb()
closeDb = null
}
vi.restoreAllMocks()
})
it('normalizes input and creates a bounded excerpt around the match', () => {
expect(normalizeUnifiedSearchQuery(' 출시\n 계획 ')).toBe('출시 계획')
expect(normalizeUnifiedSearchQuery('a'.repeat(250))).toHaveLength(200)
expect(normalizeUnifiedSearchQuery(` ${'a'.repeat(199)} b`)).toBe('a'.repeat(199))
const excerpt = createUnifiedSearchExcerpt(`앞부분 ${'x'.repeat(80)} 출시 계획 ${'y'.repeat(80)}`, '출시 계획', 60)
const excerpt = createUnifiedSearchExcerpt(
`앞부분 ${'x'.repeat(80)} 출시 계획 ${'y'.repeat(80)}`,
'출시 계획',
60,
)
expect(excerpt).toContain('출시 계획')
expect(excerpt.startsWith('…')).toBe(true)
expect(excerpt.endsWith('…')).toBe(true)
})
it('merges records and meeting transcripts by occurrence time and preserves source ids', async () => {
selectQueue.push(
createMockBuilder({ get: { count: 1 } }),
createMockBuilder({ all: [record] }),
createMockBuilder({ get: { count: 1 } }),
createMockBuilder({ all: [meeting] }),
)
const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
'../../../src/main/services/UnifiedSearchService'
)
resetUnifiedSearchServiceForTests()
it('merges records and meeting transcripts by occurrence time and preserves source ids', () => {
const { db } = useFreshTestDb()
db.insert(history).values(makeHistoryRow({ id: 'record-1', createdAt: 100, updatedAt: 100 })).run()
db.insert(meetingSessions).values(makeMeetingRow({ id: 'meeting-1', startedAt: 200, createdAt: 200 })).run()
const response = getUnifiedSearchService().search({ query: '계획', limit: 10 })
@ -139,17 +144,12 @@ describe('UnifiedSearchService', () => {
expect(response.results[1]).toMatchObject({ matchedField: 'content' })
})
it('returns immediately for an empty query', async () => {
const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
'../../../src/main/services/UnifiedSearchService'
)
resetUnifiedSearchServiceForTests()
it('returns immediately for an empty query without opening DB', () => {
expect(getUnifiedSearchService().search({ query: ' ' })).toEqual({
query: '',
results: [],
total: 0,
})
expect(mockDb.select).not.toHaveBeenCalled()
})
it.each([
@ -160,58 +160,43 @@ describe('UnifiedSearchService', () => {
{ query: '계획', limit: Number.NaN },
{ query: '계획', limit: Number.POSITIVE_INFINITY },
{ query: '계획', limit: '10' },
])('rejects malformed runtime parameters with ConfigInvalidValue: %o', async (params) => {
const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
'../../../src/main/services/UnifiedSearchService'
)
resetUnifiedSearchServiceForTests()
])('rejects malformed runtime parameters with ConfigInvalidValue: %o', (params) => {
expect(() => getUnifiedSearchService().search(params)).toThrowError(
expect.objectContaining({ code: ErrorCode.ConfigInvalidValue }),
)
expect(mockDb.select).not.toHaveBeenCalled()
})
it('maps database failures to the IPC error contract', async () => {
selectQueue.push(createMockBuilder({ error: new Error('database unavailable') }))
const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
'../../../src/main/services/UnifiedSearchService'
)
resetUnifiedSearchServiceForTests()
it('maps database failures to the IPC error contract', () => {
expect(() => getUnifiedSearchService().search({ query: '계획' })).toThrowError(
expect.objectContaining({ code: ErrorCode.DBQueryFailed }),
)
})
it('includes meeting_memos and timed transcript segments in meeting search results', async () => {
const memoOnlyMeeting: MeetingSessionRow = {
...meeting,
id: 'meeting-memo-1',
title: '설계 검토 회의',
startedAt: 400,
createdAt: 400,
rawTranscript: '[00:10] 아키텍처 개요 설명',
}
const memoRow: MeetingMemoRow = {
id: 'memo-1',
sessionId: 'meeting-memo-1',
content: '마이그레이션 체크리스트 확인 필요',
timestampMs: 75_000,
createdAt: 410,
updatedAt: 410,
}
selectQueue.push(
createMockBuilder({ get: { count: 0 } }),
createMockBuilder({ all: [] }),
createMockBuilder({ get: { count: 0 } }),
createMockBuilder({ all: [] }),
createMockBuilder({ all: [memoRow] }),
createMockBuilder({ all: [memoOnlyMeeting] }),
)
const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
'../../../src/main/services/UnifiedSearchService'
)
resetUnifiedSearchServiceForTests()
it('includes meeting_memos and timed transcript segments in meeting search results', () => {
const { db } = useFreshTestDb()
db.insert(meetingSessions)
.values(
makeMeetingRow({
id: 'meeting-memo-1',
title: '설계 검토 회의',
startedAt: 400,
createdAt: 400,
rawTranscript: '[00:10] 아키텍처 개요 설명',
}),
)
.run()
db.insert(meetingMemos)
.values(
makeMemoRow({
id: 'memo-1',
sessionId: 'meeting-memo-1',
content: '마이그레이션 체크리스트 확인 필요',
timestampMs: 75_000,
createdAt: 410,
updatedAt: 410,
}),
)
.run()
const response = getUnifiedSearchService().search({ query: '체크리스트', limit: 10 })
@ -226,4 +211,246 @@ describe('UnifiedSearchService', () => {
}),
])
})
it('search_oldLongMeetingMemoVsRecentShortMeeting_prioritizesRecentMeetingAndCreatedAtMemo', () => {
const { db } = useFreshTestDb()
// Old long meeting: high timestampMs (2 hours in), early createdAt/startedAt
db.insert(meetingSessions)
.values([
makeMeetingRow({
id: 'old-long-meeting',
title: '과거 장기 회의',
startedAt: 100,
createdAt: 100,
rawTranscript: '잡담 내용',
}),
makeMeetingRow({
id: 'recent-short-meeting',
title: '최신 짧은 회의',
startedAt: 900,
createdAt: 900,
rawTranscript: '일반 진행 상황',
}),
])
.run()
db.insert(meetingMemos)
.values([
makeMemoRow({
id: 'old-late-offset-memo',
sessionId: 'old-long-meeting',
content: '로드맵 1차 초안 메모',
timestampMs: 7_200_000,
createdAt: 110,
updatedAt: 110,
}),
makeMemoRow({
id: 'recent-early-offset-memo',
sessionId: 'recent-short-meeting',
content: '로드맵 최신 결정사항',
timestampMs: 5_000,
createdAt: 910,
updatedAt: 910,
}),
makeMemoRow({
id: 'recent-earlier-created-memo',
sessionId: 'recent-short-meeting',
content: '로드맵 중간 메모',
timestampMs: 60_000,
createdAt: 905,
updatedAt: 905,
}),
])
.run()
const limited = getUnifiedSearchService().search({ query: '로드맵', limit: 1 })
expect(limited.total).toBe(2)
expect(limited.results.map((r) => r.id)).toEqual(['recent-short-meeting'])
expect(limited.results[0].excerpt).toBe('[00:05] 로드맵 최신 결정사항')
})
it('search_meetingStartedAtDiffersFromCreatedAt_ordersByStartedAt', () => {
const { db } = useFreshTestDb()
db.insert(meetingSessions)
.values([
makeMeetingRow({
id: 'older-started-imported-later',
title: '과거 회의 사후 동기화',
startedAt: 500,
createdAt: 950,
rawTranscript: '분기 목표 리뷰',
}),
makeMeetingRow({
id: 'newer-started-created-earlier',
title: '최근 회의',
startedAt: 800,
createdAt: 200,
rawTranscript: '분기 목표 확정',
}),
])
.run()
const limited = getUnifiedSearchService().search({ query: '분기 목표', limit: 1 })
expect(limited.total).toBe(2)
expect(limited.results[0].id).toBe('newer-started-created-earlier')
expect(limited.results[0].occurredAt).toBe(800)
})
it('search_meetingMatchesDirectlyOutsideLimitAndViaMemos_countsDistinctTotalWithoutDoubleCounting', () => {
const { db } = useFreshTestDb()
db.insert(history)
.values(
makeHistoryRow({
id: 'hist-overlap',
title: '아키텍처 기록',
polishedText: '아키텍처 변경 공지',
createdAt: 1_000,
updatedAt: 1_000,
}),
)
.run()
db.insert(meetingSessions)
.values([
makeMeetingRow({
id: 'meet-both-recent',
title: '아키텍처 위원회',
startedAt: 900,
createdAt: 900,
rawTranscript: '아키텍처 리뷰',
}),
makeMeetingRow({
id: 'meet-both-old-outside-limit',
title: '초기 아키텍처 회의',
startedAt: 100,
createdAt: 100,
rawTranscript: '아키텍처 설계 초안',
}),
makeMeetingRow({
id: 'meet-memo-only-1',
title: '일반 스탠드업 1',
startedAt: 700,
createdAt: 700,
rawTranscript: '진행 보고',
}),
makeMeetingRow({
id: 'meet-memo-only-2',
title: '일반 스탠드업 2',
startedAt: 600,
createdAt: 600,
rawTranscript: '진행 보고',
}),
])
.run()
db.insert(meetingMemos)
.values([
makeMemoRow({
id: 'memo-m1',
sessionId: 'meet-both-recent',
content: '아키텍처 메모 1',
createdAt: 905,
}),
makeMemoRow({
id: 'memo-m2',
sessionId: 'meet-both-old-outside-limit',
content: '아키텍처 메모 2',
createdAt: 950,
}),
makeMemoRow({
id: 'memo-m3a',
sessionId: 'meet-memo-only-1',
content: '아키텍처 후속 과제 A',
createdAt: 710,
}),
makeMemoRow({
id: 'memo-m3b',
sessionId: 'meet-memo-only-1',
content: '아키텍처 후속 과제 B',
createdAt: 720,
}),
makeMemoRow({
id: 'memo-m4',
sessionId: 'meet-memo-only-2',
content: '아키텍처 후속 과제 C',
createdAt: 610,
}),
])
.run()
const response = getUnifiedSearchService().search({ query: '아키텍처', limit: 1 })
// 1 history + 4 distinct meetingSessions = 5 total, even though limit is 1 and meet-both-old matches both directly and via memo
expect(response.results).toHaveLength(1)
expect(response.total).toBe(5)
})
it('search_ftsTablesAbsent_fallsBackToLikeFilteringSafely', () => {
const { db, sqlite } = useFreshTestDb()
db.insert(history)
.values(
makeHistoryRow({
id: 'hist-legacy',
title: '레거시 노트',
polishedText: '트라이그램 없는 데이터베이스 검색 테스트',
createdAt: 300,
updatedAt: 300,
}),
)
.run()
db.insert(meetingSessions)
.values(
makeMeetingRow({
id: 'meet-legacy',
title: '레거시 회의',
startedAt: 400,
createdAt: 400,
rawTranscript: '일반 회의록',
}),
)
.run()
db.insert(meetingMemos)
.values(
makeMemoRow({
id: 'memo-legacy',
sessionId: 'meet-legacy',
content: '데이터베이스 백업 메모',
createdAt: 410,
}),
)
.run()
sqlite.exec('DROP TABLE IF EXISTS history_fts')
sqlite.exec('DROP TABLE IF EXISTS meeting_sessions_fts')
sqlite.exec('DROP TABLE IF EXISTS meeting_memos_fts')
const response = getUnifiedSearchService().search({ query: '데이터베이스', limit: 10 })
expect(response.total).toBe(2)
expect(response.results.map((r) => r.id)).toEqual(['meet-legacy', 'hist-legacy'])
})
it('search_ftsMatchThrowsAtRuntime_fallsBackToLikeFilteringSafely', () => {
const { db, sqlite } = useFreshTestDb()
db.insert(history)
.values(
makeHistoryRow({
id: 'hist-fts-broken',
title: '복구 테스트',
polishedText: '인덱스 손상 복구 검증',
createdAt: 500,
updatedAt: 500,
}),
)
.run()
// Replace history_fts with a plain non-FTS table so sqlite_master reports it exists, causing MATCH to fail at runtime
sqlite.exec('DROP TRIGGER IF EXISTS history_fts_ai')
sqlite.exec('DROP TRIGGER IF EXISTS history_fts_au')
sqlite.exec('DROP TRIGGER IF EXISTS history_fts_ad')
sqlite.exec('DROP TABLE history_fts')
sqlite.exec('CREATE TABLE history_fts (row_id TEXT)')
const response = getUnifiedSearchService().search({ query: '손상 복구', limit: 10 })
expect(response.total).toBe(1)
expect(response.results.map((r) => r.id)).toEqual(['hist-fts-broken'])
})
})

View file

@ -0,0 +1,114 @@
import { EventEmitter } from 'events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { initInMemoryConfig, resetInMemoryConfig } from '../../../src/main/services/ConfigService'
import { AdMediationEngine } from '../../../src/main/services/ads/AdMediationEngine'
import {
getAudioCaptureService,
resetAudioCaptureServiceForTests,
} from '../../../src/main/services/AudioCaptureService'
import {
getLocalLLMService,
resetLocalLLMServiceForTests,
} from '../../../src/main/services/LocalLLMService'
const spawnState = vi.hoisted(() => ({
nextProc: null as null | (EventEmitter & {
stdout: EventEmitter
stderr: EventEmitter
kill: ReturnType<typeof vi.fn>
}),
}))
vi.mock('child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('child_process')>()
return {
...actual,
spawn: vi.fn((...args: Parameters<typeof actual.spawn>) => {
if (spawnState.nextProc) {
const proc = spawnState.nextProc
spawnState.nextProc = null
return proc
}
return actual.spawn(...args)
}),
}
})
describe('Main service timer cleanup regressions', () => {
beforeEach(() => {
vi.useFakeTimers()
initInMemoryConfig()
resetLocalLLMServiceForTests()
resetAudioCaptureServiceForTests()
;(AdMediationEngine as unknown as { instance: null }).instance = null
})
afterEach(() => {
resetLocalLLMServiceForTests()
resetAudioCaptureServiceForTests()
;(AdMediationEngine as unknown as { instance: null }).instance = null
spawnState.nextProc = null
resetInMemoryConfig()
vi.unstubAllGlobals()
vi.useRealTimers()
vi.restoreAllMocks()
})
it('LocalLLMService_disposeAfterStartServer_cancelsPendingAvailabilityCheckTimers', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ version: '0.5.0' }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const llm = getLocalLLMService()
const status = await llm.startServer()
expect(status).toBe('running')
expect(vi.getTimerCount()).toBe(2)
const callsBeforeDispose = fetchMock.mock.calls.length
llm.dispose()
expect(vi.getTimerCount()).toBe(0)
await vi.advanceTimersByTimeAsync(5_000)
expect(fetchMock).toHaveBeenCalledTimes(callsBeforeDispose)
})
it('AdMediationEngine_runAuctionSettlesBeforeTimeout_clearsBidTimeoutTimer', async () => {
const engine = AdMediationEngine.getInstance()
const config = engine.getConfig()
engine.setConfig({
headerBiddingTimeoutMs: 15_000,
networks: config.networks.map((n) =>
n.id === 'direct_sponsor' ? { ...n, enabled: true } : n,
),
})
const result = await engine.runAuction({
placementId: 'dock-1',
format: 'banner_dock',
})
expect(result.winner === null).toBe(true)
expect(result.winningBidEcpm).toBe(0)
expect(result.participatingBids).toHaveLength(1)
expect(vi.getTimerCount()).toBe(0)
})
it('AudioCaptureService_testCaptureExitsEarly_clearsDurationKillTimer', async () => {
const proc = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
kill: vi.fn(),
})
spawnState.nextProc = proc
const service = getAudioCaptureService()
const capturePromise = service.testCapture(10_000)
expect(vi.getTimerCount()).toBe(1)
proc.emit('close', 0)
const stats = await capturePromise
expect(stats).toEqual({ averageLevel: 0, peakLevel: 0, hasAudio: false })
expect(proc.kill).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
})

View file

@ -0,0 +1,200 @@
// tests/main/services/disk-wav-audio-sink.test.ts
// GAP-PERF-01 잔여: 장시간 회의 녹음 PCM 디스크 스트리밍 계약 테스트
import fs from 'fs'
import os from 'os'
import path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CaptionSegment } from '@d3ro/core/types'
import { MeetingRecordingSession } from '../../../src/main/services/meeting/MeetingRecordingSession'
import {
DiskWavAudioSink,
MAX_WAV_DATA_BYTES,
writeWavHeader16kMonoPcm16,
} from '../../../src/main/services/meeting/disk-wav-audio-sink'
describe('DiskWavAudioSink & MeetingRecordingSession 스트리밍', () => {
let tempDir = ''
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'd3ro-wav-sink-'))
})
afterEach(() => {
vi.restoreAllMocks()
if (tempDir) {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
it('녹음종료_다중PCM청크스트리밍_메모리누적없이유효한WAV헤더와페이로드를기록한다', async () => {
const wavPath = path.join(tempDir, 'meeting-audio', 'session-1.wav')
const sink = new DiskWavAudioSink(wavPath)
let chunkListener: ((buffer: Buffer) => void) | null = null
const session = new MeetingRecordingSession('session-1', 1_000, {
caption: {
onSegment: () => () => undefined,
stop: async () => ({
segments: [{ id: 'seg-1', text: '회의 발언', timestamp: 2_000, isFinal: true } satisfies CaptionSegment],
}),
},
audio: {
onChunk: (listener) => {
chunkListener = listener
return () => {
chunkListener = null
}
},
},
audioSink: sink,
now: () => 5_000,
})
session.attachCaption()
session.attachAudio()
const chunk1 = Buffer.from([0x01, 0x02, 0x03, 0x04])
const chunk2 = Buffer.from([0x05, 0x06, 0x07, 0x08, 0x09, 0x0a])
chunkListener?.(chunk1)
chunkListener?.(chunk2)
// 중간 체크포인트는 임시 .part 를 유지하고 최종 WAV 를 아직 닫지 않는다
const mid = session.checkpoint({ includeAudio: false })
expect(mid.pcm.length).toBe(0)
expect(mid.audioSavedToDisk).toBe(false)
expect(fs.existsSync(`${wavPath}.part`)).toBe(true)
expect(fs.existsSync(wavPath)).toBe(false)
const snapshot = await session.stop()
expect(snapshot.pcm.length).toBe(0)
expect(snapshot.audioSavedToDisk).toBe(true)
expect(snapshot.pcmByteLength).toBe(10)
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
expect(fs.existsSync(wavPath)).toBe(true)
const written = fs.readFileSync(wavPath)
expect(written.length).toBe(44 + 10)
expect(written.subarray(0, 4).toString('ascii')).toBe('RIFF')
expect(written.readUInt32LE(4)).toBe(36 + 10)
expect(written.subarray(8, 12).toString('ascii')).toBe('WAVE')
expect(written.subarray(12, 16).toString('ascii')).toBe('fmt ')
expect(written.readUInt16LE(20)).toBe(1)
expect(written.readUInt16LE(22)).toBe(1)
expect(written.readUInt32LE(24)).toBe(16000)
expect(written.readUInt16LE(34)).toBe(16)
expect(written.subarray(36, 40).toString('ascii')).toBe('data')
expect(written.readUInt32LE(40)).toBe(10)
expect([...written.subarray(44)]).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
})
it('세션분리_시작실패나중단시detach호출_임시part파일을제거한다', () => {
const wavPath = path.join(tempDir, 'session-abort.wav')
const sink = new DiskWavAudioSink(wavPath)
let chunkListener: ((buffer: Buffer) => void) | null = null
const session = new MeetingRecordingSession('session-abort', 1_000, {
caption: {
onSegment: () => () => undefined,
stop: async () => null,
},
audio: {
onChunk: (listener) => {
chunkListener = listener
return () => {
chunkListener = null
}
},
},
audioSink: sink,
now: () => 2_000,
})
session.attachAudio()
chunkListener?.(Buffer.from([0x11, 0x22]))
expect(fs.existsSync(`${wavPath}.part`)).toBe(true)
session.detach()
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
expect(fs.existsSync(wavPath)).toBe(false)
})
it('무음종료_청크가하나도없을때_빈WAV파일을남기지않는다', async () => {
const wavPath = path.join(tempDir, 'session-empty.wav')
const sink = new DiskWavAudioSink(wavPath)
const session = new MeetingRecordingSession('session-empty', 1_000, {
caption: {
onSegment: () => () => undefined,
stop: async () => null,
},
audio: {
onChunk: () => () => undefined,
},
audioSink: sink,
now: () => 2_000,
})
session.attachAudio()
const snapshot = await session.stop()
expect(snapshot.audioSavedToDisk).toBe(false)
expect(snapshot.pcmByteLength).toBe(0)
expect(fs.existsSync(wavPath)).toBe(false)
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
})
it('append_initialPlaceholderWriteSyncThrows_closesOpenedFdRemovesPartAndRethrows', () => {
const wavPath = path.join(tempDir, 'placeholder-fail.wav')
const sink = new DiskWavAudioSink(wavPath)
const openedFds: number[] = []
const realOpenSync = fs.openSync
vi.spyOn(fs, 'openSync').mockImplementation((...args) => {
const fd = realOpenSync(...args)
openedFds.push(fd)
return fd
})
const closeSpy = vi.spyOn(fs, 'closeSync')
vi.spyOn(fs, 'writeSync').mockImplementationOnce(() => {
throw new Error('ENOSPC: no space left on device')
})
expect(() => sink.append(Buffer.from([0x01, 0x02]))).toThrow('ENOSPC: no space left on device')
expect(openedFds).toHaveLength(1)
expect(closeSpy).toHaveBeenCalledWith(openedFds[0])
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
expect(sink.pcmByteLength).toBe(0)
expect(sink.finalize()).toEqual({ saved: false, pcmByteLength: 0 })
})
it('writeWavHeader16kMonoPcm16_withinAndBeyondUint32Limit_validatesRange', () => {
const maxHeader = writeWavHeader16kMonoPcm16(Buffer.alloc(44), MAX_WAV_DATA_BYTES)
expect(maxHeader.readUInt32LE(4)).toBe(0xffffffff)
expect(maxHeader.readUInt32LE(40)).toBe(MAX_WAV_DATA_BYTES)
expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), MAX_WAV_DATA_BYTES + 1)).toThrow(
RangeError,
)
expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), -1)).toThrow(RangeError)
expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), 1.5)).toThrow(RangeError)
})
it('append_chunkExceedingUint32Limit_throwsRangeErrorWithoutCorruptingExistingAudio', () => {
const wavPath = path.join(tempDir, 'limit-check.wav')
const sink = new DiskWavAudioSink(wavPath)
const initialChunk = Buffer.from([0xaa, 0xbb])
sink.append(initialChunk)
expect(sink.pcmByteLength).toBe(2)
const oversizedSlice = { length: MAX_WAV_DATA_BYTES } as unknown as Buffer
expect(() => sink.append(oversizedSlice)).toThrow(RangeError)
expect(sink.pcmByteLength).toBe(2)
const finalized = sink.finalize()
expect(finalized).toEqual({ saved: true, pcmByteLength: 2 })
expect(fs.readFileSync(wavPath).subarray(44)).toEqual(initialChunk)
})
})

View file

@ -0,0 +1,133 @@
// tests/main/services/meeting-diarization.test.ts
// GAP-MTG-02: MeetingModeService.diarizeSession pyannote HTTP 경로 및 LLM 폴백 검증
import fs from 'fs'
import path from 'path'
import { eq } from 'drizzle-orm'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { app } from 'electron'
import { useRedHarness } from '../../red/harness'
const llmCapture = vi.hoisted(() => ({
calls: [] as Array<{ text: string; systemPrompt?: string }>,
}))
vi.mock('../../../src/main/services/LocalLLMService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/main/services/LocalLLMService')>()
return {
...actual,
getLocalLLMService: () => ({
isAvailable: () => true,
generate: async (text: string, options?: { systemPrompt?: string }) => {
llmCapture.calls.push({ text, systemPrompt: options?.systemPrompt })
return {
text: '[00:02] [화자 1] 안녕하세요\n[00:08] [화자 2] 반갑습니다',
model: 'gemma-test',
}
},
cancelGeneration: vi.fn(),
}),
}
})
useRedHarness()
import { configSet } from '../../../src/main/services/ConfigService'
import { getMeetingModeService } from '../../../src/main/services/MeetingModeService'
import { getDatabase } from '../../../src/main/db'
import { meetingSessions } from '../../../src/main/db/schema'
function insertCompletedSession(sessionId: string, rawTranscript: string): string {
const startedAt = 1_700_000_000_000
getDatabase()
.insert(meetingSessions)
.values({
id: sessionId,
title: '화자 구분 테스트 회의',
status: 'completed',
startedAt,
endedAt: startedAt + 15_000,
durationMs: 15_000,
rawTranscript,
createdAt: startedAt,
updatedAt: startedAt,
})
.run()
const audioDir = path.join(app.getPath('userData'), 'meeting-audio')
fs.mkdirSync(audioDir, { recursive: true })
const wavPath = path.join(audioDir, `${sessionId}.wav`)
fs.writeFileSync(wavPath, Buffer.from('RIFF0000WAVEfmt '))
return wavPath
}
describe('MeetingModeService.diarizeSession (GAP-MTG-02)', () => {
beforeEach(() => {
llmCapture.calls = []
configSet('llmBackend', 'local')
})
afterEach(() => {
vi.restoreAllMocks()
})
it('화자분리_사이드카diarize성공시_pyannote구간을1기반화자라벨로저장한다', async () => {
const sessionId = '11111111-1111-4111-8111-111111111111'
insertCompletedSession(sessionId, '[00:02] 안녕하세요\n[00:08] 반갑습니다')
configSet('hfToken', 'hf_valid_token')
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({
status: 'ok',
num_speakers: 2,
segments: [
{ speaker: 'SPEAKER_00', start: 0.0, end: 5.0 },
{ speaker: 'SPEAKER_01', start: 5.5, end: 12.0 },
],
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
),
)
await getMeetingModeService().diarizeSession(sessionId, 2)
expect(fetchSpy).toHaveBeenCalledTimes(1)
expect(String(fetchSpy.mock.calls[0]?.[0])).toContain('/diarize')
expect(llmCapture.calls).toHaveLength(0)
const updated = getDatabase()
.select()
.from(meetingSessions)
.where(eq(meetingSessions.id, sessionId))
.get()
expect(updated?.editedTranscript).toBe('[00:02] [화자 1] 안녕하세요\n[00:08] [화자 2] 반갑습니다')
})
it('화자분리_사이드카pyannote미설치503응답시_LLM화자추정으로폴백한다', async () => {
const sessionId = '22222222-2222-4222-8222-222222222222'
insertCompletedSession(sessionId, '[00:02] 안녕하세요\n[00:08] 반갑습니다')
configSet('hfToken', 'hf_valid_token')
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({
status: 'unavailable',
code: 'pyannote_not_installed',
message: 'pyannote.audio 패키지가 설치되어 있지 않습니다',
}),
{ status: 503, headers: { 'Content-Type': 'application/json' } },
),
)
await getMeetingModeService().diarizeSession(sessionId, 2)
expect(llmCapture.calls).toHaveLength(1)
const updated = getDatabase()
.select()
.from(meetingSessions)
.where(eq(meetingSessions.id, sessionId))
.get()
expect(updated?.editedTranscript).toBe('[00:02] [화자 1] 안녕하세요\n[00:08] [화자 2] 반갑습니다')
})
})

View file

@ -0,0 +1,239 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import {
configGet,
configSet,
initInMemoryConfig,
resetInMemoryConfig,
} from '../../../src/main/services/ConfigService'
import {
getOnlineLLMService,
resetOnlineLLMServiceForTests,
} from '../../../src/main/services/OnlineLLMService'
async function collectChatStream(
gen: AsyncGenerator<string, string>,
): Promise<{ tokens: string[]; result: string }> {
const tokens: string[] = []
let next = await gen.next()
while (!next.done) {
tokens.push(next.value)
next = await gen.next()
}
return { tokens, result: next.value }
}
function captureAbortedFetch(onStarted: () => void): typeof fetch {
return vi.fn((_input: string | URL | Request, init?: RequestInit) => {
const signal = init?.signal
return new Promise<Response>((_resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException('The operation was aborted', 'AbortError'))
return
}
signal?.addEventListener(
'abort',
() => reject(new DOMException('The operation was aborted', 'AbortError')),
{ once: true },
)
onStarted()
})
}) as unknown as typeof fetch
}
describe('OnlineLLMService chatStream', () => {
beforeEach(() => {
initInMemoryConfig()
configSet('authToken', 'valid-jwt-token')
configSet('onlineApiUrl', 'http://127.0.0.1:5000')
resetOnlineLLMServiceForTests()
})
afterEach(() => {
resetOnlineLLMServiceForTests()
resetInMemoryConfig()
vi.unstubAllGlobals()
})
it('chatStream_cancelGenerationCalledDuringRequest_abortsFetchAndThrowsCancelled', async () => {
const service = getOnlineLLMService()
let startedResolve!: () => void
const started = new Promise<void>((resolve) => {
startedResolve = resolve
})
vi.stubGlobal('fetch', captureAbortedFetch(startedResolve))
const run = collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }]))
await started
service.cancelGeneration()
await expect(run).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingCancelled,
})
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response(JSON.stringify({ text: 'recovered' }), { status: 200 })),
)
const retry = await collectChatStream(service.chatStream([{ role: 'user', content: 'next' }]))
expect(retry.tokens).toEqual(['recovered'])
expect(retry.result).toBe('recovered')
})
it('chatStream_disposeCalledDuringRequest_abortsFetchAndBlocksFutureCalls', async () => {
const service = getOnlineLLMService()
let startedResolve!: () => void
const started = new Promise<void>((resolve) => {
startedResolve = resolve
})
vi.stubGlobal('fetch', captureAbortedFetch(startedResolve))
const run = collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }]))
await started
service.dispose()
await expect(run).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingCancelled,
})
await expect(
collectChatStream(service.chatStream([{ role: 'user', content: 'after-dispose' }])),
).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingFailed,
})
})
it('chatStream_externalSignalAborted_abortsFetchAndThrowsCancelled', async () => {
const service = getOnlineLLMService()
let startedResolve!: () => void
const started = new Promise<void>((resolve) => {
startedResolve = resolve
})
vi.stubGlobal('fetch', captureAbortedFetch(startedResolve))
const external = new AbortController()
const run = collectChatStream(
service.chatStream([{ role: 'user', content: 'hello' }], { signal: external.signal }),
)
await started
external.abort()
await expect(run).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingCancelled,
})
})
it('chatStream_serverReturns401_clearsAuthTokenAndThrowsUnreachable', async () => {
const service = getOnlineLLMService()
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('Unauthorized', { status: 401 })),
)
await expect(
collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])),
).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMServerUnreachable,
})
expect(configGet('authToken')).toBe(null)
})
it('chatStream_serverReturns500_throwsLLMProcessingFailed', async () => {
const service = getOnlineLLMService()
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('Internal Error', { status: 500 })),
)
await expect(
collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])),
).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingFailed,
})
expect(configGet('authToken')).toBe('valid-jwt-token')
})
it.each([
{ label: 'missing text field', body: { model: 'd3ro-gpt4o-mini' } },
{ label: 'whitespace-only text', body: { text: ' \n\t ' } },
{ label: 'null response json', body: null },
])('chatStream_emptyOrInvalidPayload_$label_throwsLLMProcessingFailed', async ({ body }) => {
const service = getOnlineLLMService()
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response(JSON.stringify(body), { status: 200 })),
)
let caught: unknown
try {
await collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }]))
} catch (err) {
caught = err
}
expect(caught instanceof D3ROError).toBe(true)
expect((caught as D3ROError).code).toBe(ErrorCode.LLMProcessingFailed)
})
it('chatStream_fetchRejectsOrInvalidJson_wrapsInLLMProcessingFailed', async () => {
const service = getOnlineLLMService()
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new Error('socket hang up')
}),
)
await expect(
collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])),
).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingFailed,
})
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('{not-json', { status: 200 })),
)
await expect(
collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])),
).rejects.toMatchObject({
name: 'D3ROError',
code: ErrorCode.LLMProcessingFailed,
})
})
it('chatStream_messageContainsPII_redactsBeforeFetchAndRehydratesOutput', async () => {
const service = getOnlineLLMService()
let sentBody = ''
vi.stubGlobal(
'fetch',
vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
sentBody = String(init?.body ?? '')
const parsed = JSON.parse(sentBody) as { messages: Array<{ content: string }> }
const redactedUserMsg = parsed.messages[0].content
return new Response(
JSON.stringify({ text: `확인 완료: ${redactedUserMsg}` }),
{ status: 200 },
)
}),
)
const { tokens, result } = await collectChatStream(
service.chatStream([{ role: 'user', content: '연락처는 alice@example.com 입니다.' }]),
)
expect(sentBody.includes('alice@example.com')).toBe(false)
expect(tokens).toEqual(['확인 완료: 연락처는 alice@example.com 입니다.'])
expect(result).toBe('확인 완료: 연락처는 alice@example.com 입니다.')
})
})

View file

@ -0,0 +1,111 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mockConfigStore = new Map<string, unknown>()
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: string) => mockConfigStore.get(key)),
configSet: vi.fn((key: string, value: unknown) => {
mockConfigStore.set(key, value)
}),
}))
import {
getOnlineLLMService,
resetOnlineLLMServiceForTests,
} from '../../../src/main/services/OnlineLLMService'
import { secureWipeAudioChunks } from '@d3ro/core/utils/secure-memory'
describe('클라우드 LLM PII 가명화·복원 배선 (W5-01)', () => {
const originalFetch = globalThis.fetch
beforeEach(() => {
mockConfigStore.clear()
mockConfigStore.set('authToken', 'jwt-test-token')
mockConfigStore.set('onlineApiUrl', 'http://127.0.0.1:5000')
mockConfigStore.set('llmModelId', 'd3ro-gpt4o-mini')
resetOnlineLLMServiceForTests()
})
afterEach(() => {
globalThis.fetch = originalFetch
resetOnlineLLMServiceForTests()
})
it('processText_민감정보포함프롬프트_클라우드전송시토큰화하고응답에서원문을복원한다', async () => {
let capturedBody: { prompt?: string } = {}
globalThis.fetch = vi.fn(async (_input, init) => {
capturedBody = JSON.parse(String(init?.body ?? '{}')) as { prompt?: string }
const sentPrompt = capturedBody.prompt ?? ''
return new Response(
JSON.stringify({
text: `정리됨: ${sentPrompt}`,
model: 'd3ro-gpt4o-mini',
promptTokens: 10,
completionTokens: 10,
totalDurationMs: 25,
cost: 0,
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}) as typeof fetch
const result = await getOnlineLLMService().processText(
'연락처 010-1234-5678 및 주민번호 950101-1234567 확인 부탁드립니다',
'refine',
)
expect(capturedBody.prompt).not.toContain('010-1234-5678')
expect(capturedBody.prompt).not.toContain('950101-1234567')
expect(capturedBody.prompt).toContain('[REDACTED_PHONE_NUMBER_')
expect(capturedBody.prompt).toContain('[REDACTED_KR_RRN_')
expect(result).toBe(
'정리됨: 연락처 010-1234-5678 및 주민번호 950101-1234567 확인 부탁드립니다',
)
})
it('chatStream_다중메시지민감정보_요청메시지에서PII를숨기고스트림응답에서복원한다', async () => {
let capturedMessages: Array<{ role: string; content: string }> = []
globalThis.fetch = vi.fn(async (_input, init) => {
const parsed = JSON.parse(String(init?.body ?? '{}')) as {
messages: Array<{ role: string; content: string }>
}
capturedMessages = parsed.messages
return new Response(
JSON.stringify({
text: `확인된 이메일은 ${parsed.messages[0]?.content ?? ''} 입니다.`,
model: 'd3ro-gpt4o-mini',
promptTokens: 8,
completionTokens: 8,
totalDurationMs: 20,
cost: 0,
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}) as typeof fetch
const chunks: string[] = []
for await (const chunk of getOnlineLLMService().chatStream([
{ role: 'user', content: 'founder@d3ro.ai' },
])) {
chunks.push(chunk)
}
expect(capturedMessages[0]?.content).not.toContain('founder@d3ro.ai')
expect(capturedMessages[0]?.content).toContain('[REDACTED_EMAIL_')
expect(chunks.join('')).toBe('확인된 이메일은 founder@d3ro.ai 입니다.')
})
it('secureWipeAudioChunks_오디오버퍼폐기시_내부바이트를전부0으로덮어쓰고배열을비운다', () => {
const chunkA = Buffer.from([12, 34, 56, 78])
const chunkB = Buffer.from([90, 11, 22, 33])
const chunks = [chunkA, chunkB]
secureWipeAudioChunks(chunks)
expect(chunks).toHaveLength(0)
expect(Array.from(chunkA.values())).toEqual([0, 0, 0, 0])
expect(Array.from(chunkB.values())).toEqual([0, 0, 0, 0])
})
})

View file

@ -0,0 +1,227 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { eq } from 'drizzle-orm'
import { bindTestDatabase, unbindTestDatabase } from '../../../src/main/db'
import { ragChunks } from '../../../src/main/db/schema'
import {
decodeFloat32Buffer,
invalidateEmbeddedChunksCache,
SqliteChunkStore,
} from '../../../src/main/services/rag/chunk-store'
import { rankChunks } from '../../../src/main/services/rag/retrieval'
import { resetRAGServiceForTests } from '../../../src/main/services/RAGService'
import { adapterFor } from '../../../src/main/services/sync/sync-adapters'
import { createTestDb } from '../../helpers/createTestDb'
describe('SqliteChunkStore cache optimization, invalidation & hardening', () => {
let closeDb: (() => void) | null = null
function setupDb() {
const testDb = createTestDb()
closeDb = testDb.close
bindTestDatabase(testDb.db)
return testDb
}
beforeEach(() => {
unbindTestDatabase()
resetRAGServiceForTests()
})
afterEach(() => {
resetRAGServiceForTests()
unbindTestDatabase()
if (closeDb) {
closeDb()
closeDb = null
}
vi.restoreAllMocks()
})
it('listEmbeddedChunks_decodesFloat32Vector_stripsRedundantJsonStringFromCache', () => {
setupDb()
const store = new SqliteChunkStore()
store.insertDocument({
id: 'doc-1',
fileName: 'guide.md',
filePath: 'C:/docs/guide.md',
fileType: 'md',
chunkCount: 2,
indexed: true,
indexedAt: 1_000,
addedAt: 1_000,
})
store.replaceChunks('doc-1', ['alpha content', 'beta content'])
const chunks = store.listChunks('doc-1')
store.setEmbedding(chunks[0].id, [1, 0, 0])
store.setEmbedding(chunks[1].id, [0, 1, 0])
const parseSpy = vi.spyOn(JSON, 'parse')
const cached = store.listEmbeddedChunks()
expect(cached).toHaveLength(2)
expect(cached.map((c) => c.embedding)).toEqual(['', ''])
expect(Array.from(cached[0].vector ?? [])).toEqual([1, 0, 0])
expect(Array.from(cached[1].vector ?? [])).toEqual([0, 1, 0])
const ranked = rankChunks([0, 0.9, 0.1], cached, new Map([['doc-1', 'guide.md']]), 1)
expect(ranked).toHaveLength(1)
expect(ranked[0].content).toBe('beta content')
expect(parseSpy).not.toHaveBeenCalled()
})
it('invalidateEmbeddedChunksCache_afterDirectDbDelete_clearsStaleCachedChunks', () => {
const { db } = setupDb()
const store = new SqliteChunkStore()
store.insertDocument({
id: 'doc-stale',
fileName: 'stale.txt',
filePath: 'C:/docs/stale.txt',
fileType: 'txt',
chunkCount: 1,
indexed: true,
indexedAt: 2_000,
addedAt: 2_000,
})
store.replaceChunks('doc-stale', ['to be deleted'])
const chunks = store.listChunks('doc-stale')
store.setEmbedding(chunks[0].id, [0.5, 0.5])
expect(store.listEmbeddedChunks()).toHaveLength(1)
// Simulate out-of-band delete bypassing SqliteChunkStore methods
db.delete(ragChunks).where(eq(ragChunks.documentId, 'doc-stale')).run()
// Before invalidation cache still serves stale entry
expect(store.listEmbeddedChunks()).toHaveLength(1)
invalidateEmbeddedChunksCache(db)
expect(store.listEmbeddedChunks()).toEqual([])
// Also verify zero-arg invalidation clears currently open DB
store.replaceChunks('doc-stale', ['re-added'])
const nextChunks = store.listChunks('doc-stale')
store.setEmbedding(nextChunks[0].id, [1, 0])
expect(store.listEmbeddedChunks()).toHaveLength(1)
db.delete(ragChunks).where(eq(ragChunks.documentId, 'doc-stale')).run()
invalidateEmbeddedChunksCache()
expect(store.listEmbeddedChunks()).toEqual([])
})
it('knowledgeAdapter_deleteLocalAndApplyRemote_invalidatesEmbeddedChunksCache', async () => {
const { db } = setupDb()
const store = new SqliteChunkStore()
const docId = '11111111-1111-4111-8111-111111111111'
store.insertDocument({
id: docId,
fileName: 'sync.md',
filePath: 'remote://sync.md',
fileType: 'md',
chunkCount: 1,
indexed: true,
indexedAt: 3_000,
addedAt: 3_000,
})
store.replaceChunks(docId, ['synced chunk'])
const [chunk] = store.listChunks(docId)
store.setEmbedding(chunk.id, [1, 0])
expect(store.listEmbeddedChunks()).toHaveLength(1)
// Even if RAGService uses an external custom store that mutates SQL directly,
// knowledgeAdapter.deleteLocal / applyRemote must invalidate SqliteChunkStore cache.
const spyStore: SqliteChunkStore = Object.assign(Object.create(SqliteChunkStore.prototype), {
removeDocument(id: string) {
db.delete(ragChunks).where(eq(ragChunks.documentId, id)).run()
return true
},
getDocument: () => null,
insertDocument: () => {},
replaceChunks: () => {},
listChunks: () => [],
updateDocument: () => {},
})
resetRAGServiceForTests({ store: spyStore })
const adapter = adapterFor('knowledge_documents')
expect(adapter === null).toBe(false)
expect(adapter!.deleteLocal(docId)).toBe(true)
expect(store.listEmbeddedChunks()).toEqual([])
// Populate again and verify applyRemote also invalidates cache
store.replaceChunks(docId, ['before remote apply'])
const [reChunk] = store.listChunks(docId)
store.setEmbedding(reChunk.id, [0, 1])
expect(store.listEmbeddedChunks()).toHaveLength(1)
await adapter!.applyRemote(
{
id: docId,
file_name: 'sync.md',
file_type: 'md',
chunk_count: 1,
created_at: '2026-01-01T00:00:00.000Z',
updated_at: '2026-01-02T00:00:00.000Z',
},
{
userId: 'user-1',
isCurrent: () => true,
remote: {
selectChildren: vi.fn(async () => [{ chunk_index: 0, content: 'updated chunk' }]),
} as never,
},
)
// Cache was cleared so listEmbeddedChunks re-queries DB (still 1 here until re-indexed, selectSpy verifies DB query)
const selectSpy = vi.spyOn(db, 'select')
expect(store.listEmbeddedChunks()).toHaveLength(1)
expect(selectSpy).toHaveBeenCalledTimes(1)
})
it.each([
{ label: 'malformed json', json: '{bad-json' },
{ label: 'non-array primitive', json: '42' },
{ label: 'empty array', json: '[]' },
{ label: 'non-finite element', json: '[1, null, 3]' },
])('decodeFloat32Buffer_$label_returnsUndefinedWithoutThrowing', ({ json }) => {
expect(decodeFloat32Buffer(null, json)).toBe(undefined)
expect(decodeFloat32Buffer(Buffer.alloc(3), json)).toBe(undefined)
})
it('listEmbeddedChunksAndRankChunks_oneCorruptedRow_skipsBrokenRowAndRetrievesHealthyRows', () => {
const { db } = setupDb()
const store = new SqliteChunkStore()
store.insertDocument({
id: 'doc-mixed',
fileName: 'mixed.txt',
filePath: 'C:/docs/mixed.txt',
fileType: 'txt',
chunkCount: 2,
indexed: true,
indexedAt: 4_000,
addedAt: 4_000,
})
store.replaceChunks('doc-mixed', ['corrupt chunk', 'healthy chunk'])
const chunks = store.listChunks('doc-mixed')
// Inject corrupted JSON fallback without binary blob into chunk 0
db.update(ragChunks)
.set({ embedding: '{corrupt', embeddingBlob: null })
.where(eq(ragChunks.id, chunks[0].id))
.run()
store.setEmbedding(chunks[1].id, [0, 1, 0])
const loaded = store.listEmbeddedChunks()
expect(loaded).toHaveLength(1)
expect(loaded[0].content).toBe('healthy chunk')
const ranked = rankChunks(
[0, 1, 0],
[
...loaded,
{ documentId: 'doc-mixed', content: 'broken memory chunk', embedding: '{bad' },
],
new Map([['doc-mixed', 'mixed.txt']]),
5,
)
expect(ranked).toHaveLength(1)
expect(ranked[0].content).toBe('healthy chunk')
})
})

View file

@ -0,0 +1,198 @@
// tests/main/services/runtime-hygiene-optimizations.test.ts
// 런타임/프로세스 디커플링 검증:
// 1) InputTelemetryService: 텔레메트리 비활성(기본 모드) 시 1,000Hz mousemove 훅을 붙이지 않고, 설정 토글 시 동적 연결/해제
// 2) LocalSTTService & STTManager: 클라우드 공급자 전환 또는 유휴 언로드 시 사이드카(UIA 브리지)는 살려둔 채 기본 Whisper 모델만 내려 RAM/VRAM 회수
import { EventEmitter } from 'events'
import type { ChildProcess } from 'child_process'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const hookCalls = vi.hoisted(() => ({
on: vi.fn(),
removeListener: vi.fn(),
}))
vi.mock('electron', () => ({
app: { getPath: () => '/tmp/d3ro-test' },
screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) },
}))
vi.mock('uiohook-napi', () => ({
uIOhook: {
on: hookCalls.on,
removeListener: hookCalls.removeListener,
},
}))
vi.mock('../../../src/main/services/global-input-hook', () => ({
acquireGlobalInputHook: () => () => undefined,
}))
vi.mock('../../../src/main/services/KeyBindingService', () => ({
uiohookCodeToVk: () => null,
}))
vi.mock('../../../src/main/services/UiaContextService', () => ({
getUiaContextService: () => ({
isAvailable: () => false,
lastReason: 'test',
lastSuccessAt: 0,
}),
}))
vi.mock('../../../src/main/utils/win32-foreground', () => ({
getForegroundWindowInfo: () => null,
isForegroundKoreanIme: () => false,
}))
import {
configSet,
initInMemoryConfig,
resetInMemoryConfig,
} from '../../../src/main/services/ConfigService'
import {
getInputTelemetryService,
resetInputTelemetryServiceForTests,
} from '../../../src/main/services/InputTelemetryService'
import {
LocalSTTService,
getLocalSTTService,
resetLocalSTTServiceForTests,
} from '../../../src/main/services/LocalSTTService'
import { SidecarSupervisor, type SidecarFetchFn } from '../../../src/main/services/stt/SidecarSupervisor'
import { getSTTManager, resetSTTManagerForTests } from '../../../src/main/services/stt/STTManager'
class FakeSidecarProcess extends EventEmitter {
exitCode: number | null = null
signalCode: NodeJS.Signals | null = null
stdout = null
stderr = null
kill = vi.fn((): boolean => {
this.exitCode = 0
this.emit('exit', 0, null)
return true
})
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
describe('런타임 백그라운드 오버헤드 및 모델 상주 최적화', () => {
beforeEach(() => {
initInMemoryConfig()
hookCalls.on.mockClear()
hookCalls.removeListener.mockClear()
resetInputTelemetryServiceForTests()
resetLocalSTTServiceForTests()
resetSTTManagerForTests()
})
afterEach(() => {
resetInputTelemetryServiceForTests()
resetLocalSTTServiceForTests()
resetSTTManagerForTests()
resetInMemoryConfig()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('InputTelemetryService_텔레메트리비활성기본모드시_mousemove훅을붙이지않고켜질때만연결한다', () => {
configSet('inputTelemetryEnabled', false)
configSet('inputTelemetryPaused', false)
configSet('typoAutoCorrectEnabled', true)
const telemetry = getInputTelemetryService()
telemetry.start()
const attachedEvents = hookCalls.on.mock.calls.map((call) => call[0] as string)
expect(attachedEvents).toContain('keydown')
expect(attachedEvents).toContain('mousedown')
expect(attachedEvents).not.toContain('mousemove')
expect(attachedEvents).not.toContain('wheel')
// 사용자가 입력 텔레메트리를 켜면 실행 중에도 mousemove·wheel 리스너를 즉시 연결한다.
hookCalls.on.mockClear()
configSet('inputTelemetryEnabled', true)
telemetry.applyConfig()
const dynamicallyAttached = hookCalls.on.mock.calls.map((call) => call[0] as string)
expect(dynamicallyAttached).toContain('mousemove')
expect(dynamicallyAttached).toContain('wheel')
// 다시 끄면 키보드·클릭 관찰은 유지하면서 mousemove·wheel 만 분리한다.
hookCalls.removeListener.mockClear()
configSet('inputTelemetryEnabled', false)
telemetry.applyConfig()
const dynamicallyDetached = hookCalls.removeListener.mock.calls.map((call) => call[0] as string)
expect(dynamicallyDetached).toContain('mousemove')
expect(dynamicallyDetached).toContain('wheel')
expect(telemetry.isRunning).toBe(true)
telemetry.stop()
})
it('LocalSTTService_기본모델언로드및클라우드공급자전환시_사이드카는유지한채모델메모리만회수한다', async () => {
const unloadBodies: Array<Record<string, unknown>> = []
let clock = 0
const fetchFn: SidecarFetchFn = async (input, init) => {
if (input.endsWith('/health')) {
return jsonResponse({ status: 'ready', model: 'tiny', gpu: false })
}
if (input.endsWith('/load')) {
return jsonResponse({ status: 'loaded', model_id: 'tiny', load_time_ms: 5 })
}
if (input.endsWith('/unload')) {
const parsed = JSON.parse(String(init?.body ?? '{}')) as Record<string, unknown>
unloadBodies.push(parsed)
return jsonResponse({ status: 'unloaded', models: ['tiny'] })
}
if (input.endsWith('/shutdown')) {
return jsonResponse({ ok: true })
}
throw new TypeError(`unexpected ${input}`)
}
const supervisor = new SidecarSupervisor({
resolveLaunch: async () => ({ command: 'fake-sidecar', args: [], source: 'venv' }),
modelsDir: () => 'models',
baseUrlFor: (port) => `http://127.0.0.1:${port}`,
spawn: vi.fn(() => {
const proc = new FakeSidecarProcess()
setImmediate(() => proc.emit('spawn'))
return proc as unknown as ChildProcess
}),
fetch: fetchFn,
findFreePort: async (start) => start,
now: () => clock,
sleep: async (ms) => {
clock += ms
},
})
vi.stubGlobal('fetch', fetchFn)
const local = new LocalSTTService({ supervisor })
await local.initialize('tiny')
expect(local.currentModelId).toBe('tiny')
expect(local.getStatus().engineState).toBe('ready')
await local.releasePrimaryModel()
expect(unloadBodies).toEqual([{ slot: 'primary' }])
expect(local.currentModelId).toBe(null)
expect(local.getStatus().engineState).toBe('not-installed')
expect(supervisor.isHealthy).toBe(true)
// STTManager 가 클라우드 공급자로 전환할 때도 싱글톤 LocalSTTService 의 releasePrimaryModel 을 호출해야 한다.
const releaseSpy = vi.spyOn(getLocalSTTService(), 'releasePrimaryModel').mockResolvedValue()
getSTTManager().setProvider('d3ro-cloud')
expect(releaseSpy).toHaveBeenCalledTimes(1)
await local.dispose()
})
})

View file

@ -0,0 +1,142 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
type Listener = (...args: unknown[]) => void
const state = vi.hoisted(() => ({
windows: [] as Array<{
visible: boolean
destroyed: boolean
windowListeners: Map<string, Listener>
}>,
}))
vi.unmock('../../../src/main/windows/WindowManager')
vi.mock('electron', () => {
class FakeBrowserWindow {
visible = false
destroyed = false
windowListeners = new Map<string, Listener>()
webContents = {
on: vi.fn(),
send: vi.fn(),
isDestroyed: () => false,
insertCSS: async () => '',
executeJavaScript: async () => undefined,
invalidate: vi.fn(),
setWindowOpenHandler: vi.fn(),
}
showInactive = vi.fn(() => {
this.visible = true
})
show = vi.fn(() => {
this.visible = true
})
hide = vi.fn(() => {
this.visible = false
})
setIgnoreMouseEvents = vi.fn()
setBounds = vi.fn()
setAlwaysOnTop = vi.fn()
moveTop = vi.fn()
loadURL = vi.fn(async () => undefined)
loadFile = vi.fn(async () => undefined)
constructor() {
state.windows.push(this)
}
on(event: string, listener: Listener): this {
this.windowListeners.set(event, listener)
return this
}
isVisible(): boolean {
return this.visible
}
isDestroyed(): boolean {
return this.destroyed
}
}
return {
nativeTheme: { shouldUseDarkColors: true, on: () => undefined, removeListener: () => undefined },
app: { quit: vi.fn(), getPath: vi.fn(() => '.'), on: vi.fn(), getVersion: vi.fn(() => '1.0.0'), isPackaged: false },
BrowserWindow: Object.assign(FakeBrowserWindow, { getAllWindows: vi.fn(() => []) }),
screen: {
getPrimaryDisplay: vi.fn(() => ({ workAreaSize: { width: 1280, height: 720 }, workArea: { x: 0, y: 0, width: 1280, height: 720 } })),
getAllDisplays: vi.fn(() => [{ workArea: { x: 0, y: 0, width: 1280, height: 720 } }]),
getCursorScreenPoint: vi.fn(() => ({ x: 400, y: 400 })),
getDisplayNearestPoint: vi.fn(() => ({ workArea: { x: 0, y: 0, width: 1280, height: 720 } })),
screenToDipRect: vi.fn((_win: unknown, rect: { x: number; y: number; width: number; height: number }) => rect),
},
ipcMain: { on: vi.fn(), once: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() },
Menu: { setApplicationMenu: vi.fn(), buildFromTemplate: vi.fn() },
clipboard: { writeText: vi.fn() },
shell: { openExternal: vi.fn(async () => undefined) },
safeStorage: { isEncryptionAvailable: vi.fn(() => false) },
nativeImage: { createFromPath: vi.fn(), createEmpty: vi.fn() },
Tray: vi.fn(),
dialog: { showErrorBox: vi.fn() },
}
})
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: (key: string) => (key === 'language' ? 'ko' : key === 'theme' ? 'dark' : {}),
configSet: vi.fn(),
}))
describe('WindowManager popup hide/show timer race regressions', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.resetModules()
state.windows.length = 0
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
it('showHistoryPopup_calledWithin150msAfterHide_cancelsPendingHideTimerAndStaysVisible', async () => {
const wm = await import('../../../src/main/windows/WindowManager')
wm.showHistoryPopup([{ id: 'h-1', text: 'first' }])
expect(wm.isHistoryPopupVisible()).toBe(true)
wm.hideHistoryPopup()
await vi.advanceTimersByTimeAsync(50)
// Re-open before the 150ms hide timer fires
wm.showHistoryPopup([{ id: 'h-1', text: 'second' }])
expect(wm.isHistoryPopupVisible()).toBe(true)
await vi.advanceTimersByTimeAsync(200)
expect(wm.isHistoryPopupVisible()).toBe(true)
// Subsequent hide still hides cleanly after 150ms
wm.hideHistoryPopup()
await vi.advanceTimersByTimeAsync(160)
expect(wm.isHistoryPopupVisible()).toBe(false)
})
it('showCommandPopup_calledWithin150msAfterHide_cancelsPendingHideTimerAndStaysVisible', async () => {
const wm = await import('../../../src/main/windows/WindowManager')
wm.showCommandPopup([{ id: 'cmd-1', name: 'Summarize' }], null)
expect(wm.isCommandPopupVisible()).toBe(true)
wm.hideCommandPopup()
await vi.advanceTimersByTimeAsync(50)
wm.showCommandPopup([{ id: 'cmd-1', name: 'Summarize' }], 'cmd-1')
expect(wm.isCommandPopupVisible()).toBe(true)
await vi.advanceTimersByTimeAsync(200)
expect(wm.isCommandPopupVisible()).toBe(true)
wm.hideCommandPopup()
await vi.advanceTimersByTimeAsync(160)
expect(wm.isCommandPopupVisible()).toBe(false)
})
})