198 lines
6.8 KiB
TypeScript
198 lines
6.8 KiB
TypeScript
// 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()
|
|
})
|
|
})
|