diff --git a/apps/desktop/sidecar/main.py b/apps/desktop/sidecar/main.py index c211606..8c0489d 100644 --- a/apps/desktop/sidecar/main.py +++ b/apps/desktop/sidecar/main.py @@ -24,6 +24,7 @@ from __future__ import annotations import argparse import asyncio import fnmatch +import gc import logging import os import signal @@ -595,6 +596,33 @@ async def load_model(body: dict) -> JSONResponse: # noqa: ANN001 ) +@app.post("/unload") +async def unload_model(request: Request) -> JSONResponse: + """보조 자리 모델을 내려 VRAM/RAM 을 돌려준다. + + 자막·회의가 끝난 뒤에도 보조 모델(예: large-v3-turbo)이 받아쓰기 모델과 함께 상주하면 + GPU 여유가 줄어 Ollama 모델 로드가 느려지거나 OOM 이 난다. 기본(primary) 모델은 받아쓰기 + 지연을 막기 위해 내리지 않는다. + + Request body: { "slot": "aux" } + """ + body = await request.json() + slot: str = body.get("slot", "aux") + if slot != "aux": + return JSONResponse( + status_code=400, + content={"status": "error", "message": "only the aux slot can be unloaded"}, + ) + + async with _inference_lock: + released = list(_aux_models) + _aux_models.clear() + if released: + gc.collect() + logger.info("보조 모델 언로드: %s", ", ".join(released)) + return JSONResponse(content={"status": "unloaded", "models": released}) + + async def _watch_disconnect(request: Request, cancel: threading.Event) -> None: """클라이언트가 연결을 끊으면(타임아웃 abort 등) cancel 을 세운다.""" while not cancel.is_set(): diff --git a/apps/desktop/src/main/bootstrap.ts b/apps/desktop/src/main/bootstrap.ts index 14893ce..1500a82 100644 --- a/apps/desktop/src/main/bootstrap.ts +++ b/apps/desktop/src/main/bootstrap.ts @@ -21,7 +21,7 @@ import { getTextInsertService } from './services/TextInsertService' import { getCustomInstructionService } from './services/CustomInstructionService' import { getVoiceCommandService } from './services/VoiceCommandService' import { getInputTelemetryService } from './services/InputTelemetryService' -import { getSuggestionService, hasInputContextConsent } from './services/SuggestionService' +import { getSuggestionService } from './services/SuggestionService' import { initTypoCorrectionService } from './services/TypoCorrectionService' import { getPersonalGraphService } from './services/PersonalGraphService' import { getForegroundWindowInfo } from './utils/win32-foreground' @@ -228,8 +228,7 @@ async function initInputIntelligence(): Promise { systemPrompt: options.systemPrompt, temperature: 0, maxTokens: options.maxTokens, - signal: options.signal, - keepAlive: '10m' + signal: options.signal }) }) typo.on('settled', ({ context }) => suggestion.handleTypingContext(context)) @@ -307,15 +306,9 @@ async function initInputIntelligence(): Promise { logger.info('[bootstrap] accessibility tree enabled for UIA context capture') } - // 제안이 켜져 있으면 켜진 시점부터 모델을 미리 올려 둔다 — 토글 시에만 워밍업하면 - // 앱을 새로 켤 때마다 첫 제안이 콜드 로딩으로 타임아웃된다. - // 입력 수집 동의가 없으면 입력 맥락이 오지 않아 제안이 뜰 수 없다 — 모델을 데우지 않는다. - if (configGet('suggestionEnabled') && hasInputContextConsent()) void suggestion.warmUp() - - // Ollama 서버가 나중에 뜨는 경우(느린 부팅 등) 가용해지는 시점에도 워밍업한다. - getLocalLLMService().on('availability-changed', ({ available }) => { - if (available && configGet('suggestionEnabled') && hasInputContextConsent()) void suggestion.warmUp() - }) + // 부팅 시에는 제안 모델을 미리 올리지 않는다. gemma4:e4b 는 올라가는 순간 RAM 을 11GB 넘게 + // 붙잡아(2026-10-11 실측: 앱 기동 20초 만에 여유 RAM 7.9GB→32MB) 타이핑하지 않는 사용자까지 + // PC 전체가 느려졌다. 첫 키 입력 때 SuggestionService._keepWarm 이 조용히 워밍업한다. telemetry.start() diff --git a/apps/desktop/src/main/ipc/audio-handlers.ts b/apps/desktop/src/main/ipc/audio-handlers.ts index 6aac281..2d1c080 100644 --- a/apps/desktop/src/main/ipc/audio-handlers.ts +++ b/apps/desktop/src/main/ipc/audio-handlers.ts @@ -17,8 +17,14 @@ let testLastRms = 0 * 잡고 있는 참조를 빼앗아 그쪽 마이크가 조용히 끊긴다 — 테스트는 자기 임대만 놓는다. */ let testLease: CaptureLease | null = null +/** + * 테스트 세대. acquire() 를 기다리는 사이 테스트가 다시 시작·중지되면 앞선 호출은 낡은 것이다 — + * 예전엔 모듈 변수를 덮어써 첫 호출의 interval·리스너·임대가 고아로 남아 마이크가 앱 종료까지 켜졌다. + */ +let testGeneration = 0 function stopAudioTest(): void { + testGeneration += 1 const service = getAudioCaptureService() if (testAudioHandler) { service.off('audio-data', testAudioHandler) @@ -67,9 +73,16 @@ export function registerAudioHandlers(): void { try { // 이전 테스트가 진행 중이면 정리 stopAudioTest() + const generation = testGeneration const service = getAudioCaptureService() - testLease = await service.acquire() + const lease = await service.acquire() + if (generation !== testGeneration) { + // 기다리는 사이 새 테스트가 시작됐거나 중지됐다 — 이 임대는 바로 놓는다 + await lease.release().catch(() => { /* ignore */ }) + return ipcSuccess({ averageLevel: 0, peakLevel: 0, hasAudio: false }) + } + testLease = lease // 오디오 데이터에서 RMS 추적 testAudioHandler = (payload: { buffer: Buffer; timestamp: number }) => { diff --git a/apps/desktop/src/main/services/CaptionService.ts b/apps/desktop/src/main/services/CaptionService.ts index 88575c8..cf7547e 100644 --- a/apps/desktop/src/main/services/CaptionService.ts +++ b/apps/desktop/src/main/services/CaptionService.ts @@ -51,7 +51,6 @@ const SILENCE_RMS_THRESHOLD = 0.003 /** 문맥 다듬기 대기열 상한 — 밀리면 오래된 줄은 다듬지 않고 넘긴다 */ const REFINE_QUEUE_LIMIT = 3 const REFINE_TIMEOUT_MS = 6000 -const REFINE_KEEP_ALIVE = '10m' /** 기본 자막 설정 */ const DEFAULT_CONFIG: CaptionConfig = { @@ -326,6 +325,9 @@ class CaptionService extends EventEmitter { await this._audio.release() // 오버레이 숨김 this._hideOverlaySafely() + // 자막 전용 보조 모델은 세션이 끝나면 내린다 — 남겨 두면 받아쓰기 모델과 함께 VRAM 을 잡아 + // Ollama 로드를 느리게 하거나 OOM 을 부른다. 다음 세션 시작 때 다시 올린다. + if (this._captionModelId) void getLocalSTTService().releaseAuxModel() } // 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다) @@ -535,7 +537,6 @@ class CaptionService extends EventEmitter { temperature: 0, maxTokens: Math.min(256, segment.text.length * 2 + 32), timeoutMs: REFINE_TIMEOUT_MS, - keepAlive: REFINE_KEEP_ALIVE, }) const refined = acceptCaptionRefinement(segment.text, result.text) if (!refined) return diff --git a/apps/desktop/src/main/services/CloudSyncService.ts b/apps/desktop/src/main/services/CloudSyncService.ts index 58bea39..1c988cc 100644 --- a/apps/desktop/src/main/services/CloudSyncService.ts +++ b/apps/desktop/src/main/services/CloudSyncService.ts @@ -113,6 +113,8 @@ class CloudSyncService extends EventEmitter { private _realtimeRetryTimer: NodeJS.Timeout | null = null private _initialized = false private _realtimeChannel: RealtimeChannel | null = null + /** 진행 중인 startRealtime — 동시 호출을 하나로 합친다 */ + private _realtimeStarting: Promise | null = null private _engine: SyncEngine | null = null /** 로그인 시작(startSignIn) 후 콜백을 받아들이는 기한. null이면 진행 중인 로그인이 없다 */ private _pendingSignInUntil: number | null = null @@ -803,14 +805,27 @@ class CloudSyncService extends EventEmitter { * devices 변경이 오면 이 기기의 연결 해제 여부를 확인한다. * 중복 호출 방지를 위해 기존 채널이 있으면 먼저 해제. */ - async startRealtime(): Promise { + startRealtime(): Promise { + // heartbeat·재시도 타이머·인증 처리가 동시에 부를 수 있다. 겹치면 realtime-js 가 같은 topic 의 + // 기존 채널 객체를 돌려줘 postgres_changes 바인딩이 호출마다 중복으로 쌓였다 — 한 번에 하나만 돈다. + if (!this._realtimeStarting) { + this._realtimeStarting = this._startRealtime().finally(() => { + this._realtimeStarting = null + }) + } + return this._realtimeStarting + } + + private async _startRealtime(): Promise { if (!this._client || !this._session) { logger.warn('Realtime 시작 불가 — 로그인 필요') return } if (this._realtimeChannel) { - await this._realtimeChannel.unsubscribe() + const previous = this._realtimeChannel this._realtimeChannel = null + // unsubscribe 만 하면 클라이언트 레지스트리에 채널이 남아 같은 topic 으로 재사용된다 + await this._client.removeChannel(previous) } const userId = this._session.user.id @@ -843,8 +858,9 @@ class CloudSyncService extends EventEmitter { { event: '*', schema: 'public', table: 'devices', filter: `user_id=eq.${userId}` }, () => void this._checkInDevice('heartbeat') ) - this._realtimeChannel = channel - .subscribe((status) => { + const subscribed = channel.subscribe((status) => { + // 교체된 이전 채널의 CLOSED 는 무시한다 — 재구독을 다시 예약해 채널이 겹치게 된다 + if (this._realtimeChannel !== subscribed) return logger.info(`Realtime 채널 상태: ${status}`) // U1: TIMED_OUT / CHANNEL_ERROR / CLOSED 시 지수 백오프 자동 재구독. // Supabase realtime은 네트워크 jitter로 간헐적 TIMED_OUT이 발생할 수 있고, @@ -862,6 +878,7 @@ class CloudSyncService extends EventEmitter { this._scheduleRealtimeRetry() } }) + this._realtimeChannel = subscribed } /** @@ -907,8 +924,10 @@ class CloudSyncService extends EventEmitter { } this._realtimeRetryCount = 0 if (this._realtimeChannel) { - await this._realtimeChannel.unsubscribe() + const channel = this._realtimeChannel this._realtimeChannel = null + if (this._client) await this._client.removeChannel(channel) + else await channel.unsubscribe() logger.info('Realtime 채널 종료') } } diff --git a/apps/desktop/src/main/services/LocalLLMService.ts b/apps/desktop/src/main/services/LocalLLMService.ts index b8666d0..f2735e3 100644 --- a/apps/desktop/src/main/services/LocalLLMService.ts +++ b/apps/desktop/src/main/services/LocalLLMService.ts @@ -14,7 +14,11 @@ import { resolveSystemPrompt } from './llm-prompts' import { getBundledOllamaPath } from '../utils/paths' import { normalizeLoopbackUrl } from '../utils/loopback' import { readNdjsonLines } from '../utils/ndjson-reader' -import { ModelResidencyLedger, type ModelResidencyPort } from './llm/model-residency' +import { + LOCAL_LLM_KEEP_ALIVE, + ModelResidencyLedger, + type ModelResidencyPort +} from './llm/model-residency' import { toChatRequest, toRoleMessages, @@ -437,7 +441,7 @@ class LocalLLMService extends EventEmitter { prompt, system: options?.systemPrompt, stream: false, - keep_alive: options?.keepAlive, + keep_alive: options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE, // Ollama v0.20+ think 파라미터: reasoning 모델에서 thinking 토큰 생성 중단. // gemma4/llama3.2 등 non-reasoning 모델에서는 무시됨. think: false, @@ -457,7 +461,7 @@ class LocalLLMService extends EventEmitter { } const data = (await response.json()) as OllamaGenerateResponse - this._residency.noteRequest(model, options?.keepAlive, Date.now()) + this._residency.noteRequest(model, options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE, Date.now()) const result: GenerateResult = { text: data.response, @@ -504,7 +508,7 @@ class LocalLLMService extends EventEmitter { prompt, ...(options?.raw ? { raw: true } : { system: options?.systemPrompt }), stream: true, - keep_alive: options?.keepAlive, + keep_alive: options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE, think: false, options: { temperature: options?.temperature ?? 0.3, @@ -571,7 +575,7 @@ class LocalLLMService extends EventEmitter { request.controller.abort() } // 서버가 응답을 시작했다면 모델이 올라왔고 이 요청의 keep_alive 가 만료 시각을 정했다. - if (reader) this._residency.noteRequest(model, options?.keepAlive, Date.now()) + if (reader) this._residency.noteRequest(model, options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE, Date.now()) request.close() } } @@ -868,7 +872,7 @@ class LocalLLMService extends EventEmitter { // @d3ro/core/llm-chat 계약: system 은 선두 system 메시지 하나로 정규화해 보낸다. messages: toRoleMessages(toChatRequest(messages)), stream: true, - keep_alive: options?.keepAlive, + keep_alive: options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE, think: false, options: { temperature: options?.temperature ?? 0.7, @@ -914,7 +918,7 @@ class LocalLLMService extends EventEmitter { request.abortCause ??= 'cancelled' request.controller.abort() } - if (reader) this._residency.noteRequest(model, options?.keepAlive, Date.now()) + if (reader) this._residency.noteRequest(model, options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE, Date.now()) request.close() } } @@ -924,6 +928,35 @@ class LocalLLMService extends EventEmitter { return this._residency } + /** + * 이 앱이 올려 둔(아직 상주 중으로 추정되는) 모델을 Ollama 에서 즉시 내린다 (keep_alive: 0). + * + * 종료 후에도 keep_alive 동안 모델이 RAM/VRAM 을 붙잡지 않게 한다. 다른 앱이 쓰던 모델은 + * 건드리지 않도록 이 앱이 요청한 모델만 대상으로 한다. 실패해도 종료를 막지 않는다. + */ + async unloadResidentModels(timeoutMs = 2000): Promise { + const models = this._residency.residentModels(Date.now()) + if (models.length === 0) return + const serverUrl = getOllamaServerUrl() + await Promise.all( + models.map(async (model) => { + try { + const response = await fetch(`${serverUrl}/api/generate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model, keep_alive: 0 }), + signal: AbortSignal.timeout(timeoutMs) + }) + await response.body?.cancel() + this._residency.forget(model) + logger.info(`Ollama 모델 언로드 (model=${model}, status=${response.status})`) + } catch (error) { + logger.warn(`Ollama 모델 언로드 실패 (model=${model}): ${error instanceof Error ? error.message : String(error)}`) + } + }) + ) + } + dispose(): void { this._disposed = true this.stopPolling() @@ -1029,6 +1062,10 @@ export function resetLocalLLMServiceForTests(): void { instance = null } -export function disposeLocalLLMService(): void { - instance?.dispose() +export async function disposeLocalLLMService(): Promise { + if (!instance) return + // 진행 중 요청을 먼저 끊어야 언로드 직후 그 요청이 모델을 다시 올리지 않는다 + instance.cancelGeneration() + await instance.unloadResidentModels() + instance.dispose() } diff --git a/apps/desktop/src/main/services/LocalSTTService.ts b/apps/desktop/src/main/services/LocalSTTService.ts index b257ade..fe96146 100644 --- a/apps/desktop/src/main/services/LocalSTTService.ts +++ b/apps/desktop/src/main/services/LocalSTTService.ts @@ -663,6 +663,32 @@ class LocalSTTService extends EventEmitter { this._auxModelId = modelId } + /** + * 보조 자리 모델을 내린다 — 자막·회의가 끝나면 받아쓰기 모델만 남겨 VRAM/RAM 을 돌려준다. + * 예전 사이드카(엔드포인트 없음)나 통신 실패여도 세션 종료를 막지 않는다. + */ + async releaseAuxModel(): Promise { + if (!this._auxModelId || !this._supervisor.isHealthy) return + const modelId = this._auxModelId + try { + const response = await fetch(`${this._baseUrl}/unload`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ slot: 'aux' }), + signal: AbortSignal.timeout(SIDECAR_REQUEST_TIMEOUT_MS), + }) + await response.body?.cancel() + if (response.ok) { + this._auxModelId = null + logger.info(`보조 STT 모델 언로드: ${modelId}`) + } else { + logger.warn(`보조 STT 모델 언로드 실패 (HTTP ${response.status})`) + } + } catch (error) { + logger.warn(`보조 STT 모델 언로드 실패: ${error instanceof Error ? error.message : String(error)}`) + } + } + private async _loadModel(modelId: string, slot: 'primary' | 'aux' = 'primary'): Promise { logger.info(`모델 로딩 시작: ${modelId} (${slot})`) const startTime = Date.now() diff --git a/apps/desktop/src/main/services/MeetingModeService.ts b/apps/desktop/src/main/services/MeetingModeService.ts index 627a80d..cfb2b0c 100644 --- a/apps/desktop/src/main/services/MeetingModeService.ts +++ b/apps/desktop/src/main/services/MeetingModeService.ts @@ -882,7 +882,14 @@ class MeetingModeService extends EventEmitter { header.write('data', 36) header.writeUInt32LE(dataSize, 40) - fs.writeFileSync(filePath, Buffer.concat([header, pcmBuffer])) + // 헤더와 PCM 을 이어 붙이지 않고 따로 쓴다 — 3시간 회의면 concat 사본만 350MB 가 더 생긴다 + const fd = fs.openSync(filePath, 'w') + try { + fs.writeSync(fd, header) + fs.writeSync(fd, pcmBuffer) + } finally { + fs.closeSync(fd) + } } private _sendToRenderer(channel: string, data: unknown): void { diff --git a/apps/desktop/src/main/services/SuggestionService.ts b/apps/desktop/src/main/services/SuggestionService.ts index 8c06116..33d7eae 100644 --- a/apps/desktop/src/main/services/SuggestionService.ts +++ b/apps/desktop/src/main/services/SuggestionService.ts @@ -58,6 +58,7 @@ import { } from './SuggestionRepository' import { SuggestionBudget } from './suggestion/SuggestionBudget' import { ModelWarmTracker } from './suggestion/ModelWarmTracker' +import { LOCAL_LLM_KEEP_ALIVE, LOCAL_LLM_KEEP_ALIVE_MS } from './llm/model-residency' import { getForegroundWindowInfo } from '../utils/win32-foreground' const logger = getLogger('SuggestionService') @@ -207,21 +208,23 @@ interface ModelRequest { } /** - * 모델을 메모리에 유지하는 시간. + * 모델을 메모리에 유지하는 시간 — 앱 공통 값(LOCAL_LLM_KEEP_ALIVE)을 그대로 쓴다. * - * 콜드 리로드 실측(11.4s)이 요청 타임아웃(8s)보다 길어, 짧은 유휴 유지 시간은 - * 유휴 후 첫 요청을 항상 타임아웃시켰다 — 충분히 길게 유지한다. + * 예전엔 콜드 리로드(11.4s) 회피용으로 30m 을 따로 썼지만, 다른 기능의 짧은 keep_alive 와 + * 서로 덮어써 리로드를 오히려 부추겼고 유휴 중 RAM 11GB 를 붙잡았다. 쓰는 동안은 아래 연장으로 + * 식지 않게 하고, 콜드 첫 요청은 _keepWarm 의 첫 키 입력 워밍업이 흡수한다. */ -const SUGGESTION_KEEP_ALIVE = '30m' -const SUGGESTION_KEEP_ALIVE_MS = 30 * 60_000 +const SUGGESTION_KEEP_ALIVE = LOCAL_LLM_KEEP_ALIVE +const SUGGESTION_KEEP_ALIVE_MS = LOCAL_LLM_KEEP_ALIVE_MS /** * 타이핑 중인데 남은 유지 시간이 이보다 짧으면 1토큰 요청으로 유지 시간을 연장한다. * * 실측(2026-10-03): 50분 자리를 비운 뒤 돌아오자 콜드 로드에 29초가 걸려 그동안 "준비 중" 만 * 보였다(GPU 메모리 10.6/12GB — 음성 인식 모델과 함께 올라가 있어 로드가 느리다). 쓰는 동안에는 - * 절대 식지 않게, 자리를 비우면 keep-alive 뒤에 내려가게 한다. + * 절대 식지 않게, 자리를 비우면 keep-alive 뒤에 내려가게 한다. keep-alive(10m)보다 충분히 작아야 + * 타이핑 중 매분 연장 요청을 쏘지 않는다. */ -const KEEP_WARM_REFRESH_MS = 10 * 60_000 +const KEEP_WARM_REFRESH_MS = 4 * 60_000 /** 유지 연장 요청 최소 간격 */ const KEEP_WARM_MIN_INTERVAL_MS = 60_000 /** keep-alive 만료 직전 여유 — 경계에서 콜드 모델로 요청하지 않는다. */ diff --git a/apps/desktop/src/main/services/VoiceConversationService.ts b/apps/desktop/src/main/services/VoiceConversationService.ts index 882a045..df20f6a 100644 --- a/apps/desktop/src/main/services/VoiceConversationService.ts +++ b/apps/desktop/src/main/services/VoiceConversationService.ts @@ -26,6 +26,12 @@ const logger = getLogger('VoiceConversationService') /** 대화 히스토리 최대 턴 수 (user+assistant 쌍) */ const MAX_HISTORY_TURNS = 10 +/** + * 한 번의 듣기에서 보관하는 최대 오디오(최근 5분, 16kHz 16bit mono ≈ 9.6MB). + * 응답 뒤 자동으로 다시 듣기 때문에 창을 켜 둔 채 자리를 비우면 시간당 115MB 씩 끝없이 쌓였다 — + * 넘치면 오래된 앞부분부터 버린다(한 턴의 발화가 5분을 넘는 일은 없다). + */ +const MAX_LISTEN_AUDIO_BYTES = 5 * 60 * 16000 * 2 /** 시스템 프롬프트 */ const SYSTEM_PROMPT = `You are D3RO, a helpful local AI voice assistant. Respond concisely and naturally, as if having a spoken conversation. Keep answers brief (2-3 sentences) unless the user asks for detail. Respond in the same language the user speaks.` @@ -34,6 +40,7 @@ class VoiceConversationService extends EventEmitter { private _messages: ConversationMessage[] = [] private _isActive = false private _audioBuffers: Buffer[] = [] + private _audioBufferBytes = 0 private _audioListenerBound = false private _audioLevelListenerBound = false /** @@ -161,6 +168,7 @@ class VoiceConversationService extends EventEmitter { private _startListening(): void { this._audioBuffers = [] + this._audioBufferBytes = 0 const audioService = getAudioCaptureService() if (!this._audioListenerBound) { @@ -200,6 +208,7 @@ class VoiceConversationService extends EventEmitter { audioService.stop().catch(() => { /* ignore */ }) } this._audioBuffers = [] + this._audioBufferBytes = 0 } /** 세션이 살아 있으면 listening 으로 돌아가 다시 듣는다. */ @@ -212,6 +221,11 @@ class VoiceConversationService extends EventEmitter { private _onAudioData = (payload: { buffer: Buffer }): void => { if (this._state !== 'listening') return this._audioBuffers.push(payload.buffer) + this._audioBufferBytes += payload.buffer.length + while (this._audioBufferBytes > MAX_LISTEN_AUDIO_BYTES && this._audioBuffers.length > 1) { + const dropped = this._audioBuffers.shift() + this._audioBufferBytes -= dropped?.length ?? 0 + } } /** @@ -414,7 +428,6 @@ class VoiceConversationService extends EventEmitter { local: { maxTokens: 512, timeoutMs: 60_000, - keepAlive: '2m', }, }) } diff --git a/apps/desktop/src/main/services/VoiceModeService.ts b/apps/desktop/src/main/services/VoiceModeService.ts index 316238b..bfadc7f 100644 --- a/apps/desktop/src/main/services/VoiceModeService.ts +++ b/apps/desktop/src/main/services/VoiceModeService.ts @@ -177,6 +177,24 @@ function describe(err: unknown): string { return err instanceof Error ? err.message : String(err) } +/** + * 청크 목록의 끝에서 maxBytes 만큼만 새 버퍼로 모은다. + * 예전엔 1.5초마다 녹음 전체를 concat 한 뒤 잘라 30분 녹음이면 초당 ~38MB 의 가비지를 만들었고, + * subarray 라 진행 중 부분 전사가 원본 전체를 붙잡았다. 끝부분 청크만 복사한다. + */ +function tailAudio(chunks: readonly Buffer[], maxBytes: number): Buffer { + const picked: Buffer[] = [] + let total = 0 + for (let i = chunks.length - 1; i >= 0 && total < maxBytes; i -= 1) { + picked.push(chunks[i]) + total += chunks[i].length + } + picked.reverse() + const merged = Buffer.concat(picked, total) + // 청크 경계에서 넘친 앞부분은 버린다 (merged 는 창 크기 + 청크 하나 정도라 subarray 로 충분) + return total > maxBytes ? merged.subarray(total - maxBytes) : merged +} + /** LLM 을 실제로 부르는 경로 */ type LlmProcessingRoute = Exclude @@ -786,9 +804,7 @@ class VoiceModeService extends EventEmitter { if (!run.sttReady) return if (run.audioBufferBytes < PARTIAL_MIN_AUDIO_MS * BYTES_PER_MS) return - const merged = Buffer.concat(run.audioBuffer) - const maxBytes = PARTIAL_MAX_WINDOW_MS * BYTES_PER_MS - const window = merged.length > maxBytes ? merged.subarray(merged.length - maxBytes) : merged + const window = tailAudio(run.audioBuffer, PARTIAL_MAX_WINDOW_MS * BYTES_PER_MS) const language = configGet('sttLanguage') const task = (async (): Promise => { diff --git a/apps/desktop/src/main/services/llm/model-residency.ts b/apps/desktop/src/main/services/llm/model-residency.ts index 3e6879b..28d24e9 100644 --- a/apps/desktop/src/main/services/llm/model-residency.ts +++ b/apps/desktop/src/main/services/llm/model-residency.ts @@ -9,6 +9,17 @@ /** keep_alive 를 생략하면 Ollama 서버 기본값(5분)이 적용된다. */ export const OLLAMA_DEFAULT_KEEP_ALIVE_MS = 5 * 60_000 +/** + * 앱의 모든 로컬 LLM 요청이 쓰는 단일 keep_alive. + * + * 기능마다 30m/10m/5m/2m 로 달랐을 때는 서로 만료 시각을 덮어써 언로드→콜드 리로드(9.6GB 재읽기)가 + * 반복됐고, 30m 상주는 유휴 중에도 RAM 을 11GB 넘게 붙잡았다(gemma4:e4b 는 Windows CUDA 에서 + * mmap 없이 5.9GB 를 pinned host 메모리에 올린다, 2026-10-11 실측). 쓰는 동안은 제안 서비스가 + * 유지 연장하고, 손을 떼면 이 시간 뒤에 내려가 메모리를 돌려준다. + */ +export const LOCAL_LLM_KEEP_ALIVE = '10m' +export const LOCAL_LLM_KEEP_ALIVE_MS = 10 * 60_000 + /** * Ollama keep_alive 값을 ms 로 푼다. 음수는 "무기한"(Infinity), 0 은 즉시 내림, 해석할 수 없으면 기본값. * 문자열은 Go duration 형식('10m', '30s', '1h30m')과 초 단위 숫자 문자열을 받는다. @@ -50,6 +61,15 @@ export class ModelResidencyLedger implements ModelResidencyPort { return this._expiresAt.get(model) ?? null } + /** 지금 시각에 아직 상주 중이라고 추정되는 모델 — 종료 시 언로드 대상 */ + residentModels(now: number): string[] { + return [...this._expiresAt].filter(([, until]) => until > now).map(([model]) => model) + } + + forget(model: string): void { + this._expiresAt.delete(model) + } + reset(): void { this._expiresAt.clear() } diff --git a/apps/desktop/tests/main/services/SuggestionService.test.ts b/apps/desktop/tests/main/services/SuggestionService.test.ts index c4ffef8..67ae65b 100644 --- a/apps/desktop/tests/main/services/SuggestionService.test.ts +++ b/apps/desktop/tests/main/services/SuggestionService.test.ts @@ -115,7 +115,7 @@ afterEach(async () => { }) describe('SuggestionService warm-up', () => { - it('동시 warm-up 호출을 하나의 1토큰 요청으로 합치고 30분간 유지한다', async () => { + it('동시 warm-up 호출을 하나의 1토큰 요청으로 합치고 공통 keep-alive(10분)로 유지한다', async () => { localLlm.streamGenerate.mockImplementation(async function* () { yield 'ok' }) @@ -129,7 +129,7 @@ describe('SuggestionService warm-up', () => { expect(localLlm.streamGenerate).toHaveBeenCalledTimes(1) expect(localLlm.streamGenerate).toHaveBeenCalledWith( 'hi', - expect.objectContaining({ maxTokens: 1, keepAlive: '30m' }) + expect.objectContaining({ maxTokens: 1, keepAlive: '10m' }) ) expect(warmingStates).toEqual([true, false]) }) diff --git a/apps/desktop/tests/main/services/VoiceConversationService.test.ts b/apps/desktop/tests/main/services/VoiceConversationService.test.ts index c247bd6..2d587c4 100644 --- a/apps/desktop/tests/main/services/VoiceConversationService.test.ts +++ b/apps/desktop/tests/main/services/VoiceConversationService.test.ts @@ -152,7 +152,6 @@ describe('VoiceConversationService local response ownership', () => { signal: expect.any(AbortSignal), maxTokens: 512, timeoutMs: 60_000, - keepAlive: '2m', }), ) diff --git a/apps/desktop/tests/main/services/local-llm-service.test.ts b/apps/desktop/tests/main/services/local-llm-service.test.ts index c1ad163..4504eb9 100644 --- a/apps/desktop/tests/main/services/local-llm-service.test.ts +++ b/apps/desktop/tests/main/services/local-llm-service.test.ts @@ -179,3 +179,48 @@ describe('LocalLLMService request lifecycle', () => { service.stopPolling() }) }) + +describe('LocalLLMService model residency (2026-10-11 memory policy)', () => { + beforeEach(() => { + initInMemoryConfig() + resetLocalLLMServiceForTests() + markAvailable() + }) + + afterEach(() => { + resetLocalLLMServiceForTests() + resetInMemoryConfig() + vi.unstubAllGlobals() + }) + + it('applies the shared 10m keep_alive when a caller does not set one', async () => { + const bodies: Array<{ keep_alive?: string | number }> = [] + vi.stubGlobal('fetch', vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + bodies.push(JSON.parse(String(init?.body)) as { keep_alive?: string }) + return completedGenerateResponse() + })) + + await getLocalLLMService().generate('hi', { model: 'gemma4:e4b' }) + + expect(bodies[0].keep_alive).toBe('10m') + }) + + it('unloads only the models this app loaded, once, with keep_alive 0', async () => { + const bodies: Array<{ model: string; keep_alive?: string | number; prompt?: string }> = [] + vi.stubGlobal('fetch', vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + bodies.push(JSON.parse(String(init?.body)) as { model: string; keep_alive?: string }) + return completedGenerateResponse() + })) + const service = getLocalLLMService() + + await service.unloadResidentModels() + expect(bodies).toHaveLength(0) + + await service.generate('hi', { model: 'gemma4:e4b' }) + await service.unloadResidentModels() + await service.unloadResidentModels() + + const unloads = bodies.filter((body) => body.keep_alive === 0) + expect(unloads).toEqual([{ model: 'gemma4:e4b', keep_alive: 0 }]) + }) +}) diff --git a/apps/desktop/tests/main/sync/cloud-credentials-redteam-r3-1.test.ts b/apps/desktop/tests/main/sync/cloud-credentials-redteam-r3-1.test.ts index 7493cca..3122d01 100644 --- a/apps/desktop/tests/main/sync/cloud-credentials-redteam-r3-1.test.ts +++ b/apps/desktop/tests/main/sync/cloud-credentials-redteam-r3-1.test.ts @@ -172,6 +172,7 @@ vi.mock('@supabase/supabase-js', () => { }, from: () => query(), channel: () => channel, + removeChannel: async () => "ok", realtime: { setAuth: async () => undefined }, functions: { invoke: vi.fn(async () => ({ data: { ok: true }, error: null })), diff --git a/apps/desktop/tests/main/sync/cloud-sync-restore-redteam-r2-1.test.ts b/apps/desktop/tests/main/sync/cloud-sync-restore-redteam-r2-1.test.ts index 3d74b04..e9b20b3 100644 --- a/apps/desktop/tests/main/sync/cloud-sync-restore-redteam-r2-1.test.ts +++ b/apps/desktop/tests/main/sync/cloud-sync-restore-redteam-r2-1.test.ts @@ -181,6 +181,7 @@ vi.mock('@supabase/supabase-js', () => { }, from: () => query(), channel: () => channel, + removeChannel: async () => "ok", realtime: { setAuth: async () => undefined }, }), } diff --git a/docs/map/10-feature-catalog.md b/docs/map/10-feature-catalog.md index 7abab86..0700a3f 100644 --- a/docs/map/10-feature-catalog.md +++ b/docs/map/10-feature-catalog.md @@ -37,7 +37,7 @@ Status quick-reference: `[x]` done+verified · `[~]` partial/unverified · `[ ]` | ID | Feature | D | W | M | B | Anchors / notes | |---|---|---|---|---|---|---| -| AI-01 | Local LLM (Ollama) | [~] | [-] | [ ] | [-] | Desktop bundled Ollama. 2026-09-22 guard contract: no boot warmup; suggestion `keep_alive: 2m`; request-owned cancellation; generate/stream 2048 tokens / 120 s and chat 512 / 60 s; `done` frame required with incomplete-stream cleanup; deduplicated Ollama spawn/poll plus lifecycle disposal. GAP-LLM-03 has targeted evidence (6 test files / 69 passed / 0 failed; changed code/tests ESLint and diff check exit 0). Raw Ollama confirms cold timeout cleanup, a 553 ms `num_predict=1`/`keep_alive='2m'` response, and after the about-119.9 s expiry a 19:48:59 +09:00 `/api/ps` HTTP 200 / 45.8 ms `{models:[]}` observation with no intervening generate/unload/kill/retry; `/api/version` was HTTP 200 / 7.3 ms / `0.32.13`. This is raw API expiry/unload evidence, not app-restart or GUI/runtime proof (GAP-LLM-04). | +| AI-01 | Local LLM (Ollama) | [~] | [-] | [ ] | [-] | Desktop bundled Ollama. 2026-09-22 guard contract: no boot warmup; suggestion `keep_alive: 2m`; request-owned cancellation; generate/stream 2048 tokens / 120 s and chat 512 / 60 s; `done` frame required with incomplete-stream cleanup; deduplicated Ollama spawn/poll plus lifecycle disposal. GAP-LLM-03 has targeted evidence (6 test files / 69 passed / 0 failed; changed code/tests ESLint and diff check exit 0). Raw Ollama confirms cold timeout cleanup, a 553 ms `num_predict=1`/`keep_alive='2m'` response, and after the about-119.9 s expiry a 19:48:59 +09:00 `/api/ps` HTTP 200 / 45.8 ms `{models:[]}` observation with no intervening generate/unload/kill/retry; `/api/version` was HTTP 200 / 7.3 ms / `0.32.13`. This is raw API expiry/unload evidence, not app-restart or GUI/runtime proof (GAP-LLM-04). **2026-10-11 residency policy (supersedes 2m / later 30m):** single `LOCAL_LLM_KEEP_ALIVE='10m'` for every local request (`services/llm/model-residency.ts`), no boot warmup (first keystroke warms via `SuggestionService._keepWarm`), keep-warm refresh only when <4 min left, and `keep_alive: 0` unload of this app's resident models on quit (`LocalLLMService.unloadResidentModels`). Reason: gemma4:e4b holds ~11.6 GB RAM (5.9 GB pinned host buffer, no mmap on Windows CUDA) — boot warmup took free RAM 7.9 GB→32 MB within 20 s (GAP-PERF-01). | | AI-02 | Cloud LLM (Claude/OpenAI) | [x] | [x] | [x] | [x] | Desktop `PremiumLLMService`; web/mobile via `llm-proxy`; .NET `LlmProxyService` | | AI-03 | Auto Polish (cleanup/filler removal) | [x] | [~] | [~] | [x] | Desktop built-in; web/mobile via commands. Desktop Auto Polish is the plain `refine` action (`llm-prompts.ts:14`), not a custom instruction, so it was **not** affected by the 2026-09-21 instruction-prompt fix (AI-05); regression cases now pin `refine`/`summarize`/`grammar`/`expand` (`VoiceModeService.test.ts:435`, `llm-prompts.test.ts:153`) | | AI-04 | Translate / summarize / rephrase | [~] | [x] | [x] | [x] | Built-in instructions. **Desktop has two paths and only one of them worked.** The plain-action path (Settings → `defaultLLMAction`, `SettingsModal.tsx:653`) reads `BASE_SYSTEM_PROMPTS` directly and was always correct. The built-in *instruction* presets (`CustomInstructionService.ts:26/35/44/53/62`) ran through the custom-instruction path and inserted the instruction's own wording instead of the result — see AI-05. Fixed in `9c2b4d4` (2026-09-21), **not verified in a running app** (`11` GAP-LLM-02). Translate still always targets English: `AppConfig` has no target-language key and neither `language` (UI locale) nor `sttLanguage` (source language) can stand in (`llm-prompts.ts:37-52`, `11` GAP-LLM-01) | diff --git a/docs/map/11-gap-backlog.md b/docs/map/11-gap-backlog.md index 5c4c3fc..e0ddb2d 100644 --- a/docs/map/11-gap-backlog.md +++ b/docs/map/11-gap-backlog.md @@ -99,6 +99,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res | GAP-INPUT-04 | Input intelligence | **UIA 브리지가 Windows 전용이다.** `uiautomation` 은 Windows UI Automation 래퍼이므로 macOS 는 AX API, Linux 는 AT-SPI 구현이 따로 필요하다. 그래서 입력 인텔리전스는 카탈로그에서 데스크톱(`D`)만 표기하고 나머지 표면은 `[-]` 다. 또한 Chromium 138 미만 앱은 접근성 트리가 켜져 있으면 입력창 텍스트를 노출하지 않는데, 그 앱들을 `--force-renderer-accessibility` 로 켜도록 강제할 방법이 없다(우리 자신은 `app.setAccessibilitySupportEnabled(true)` 로 처리했다 — `bootstrap.ts`). | `apps/desktop/sidecar/uia_bridge.py`, `apps/desktop/src/main/bootstrap.ts`(`initInputIntelligence`) | macOS AX 경로를 붙일지 결정한다. 붙이지 않으면 카탈로그에서 macOS 를 명시적 N/A 로 유지한다. | | GAP-INPUT-05 | Input intelligence | **수락/닫기 키가 사용자 습관과 충돌할 수 있다.** 기본값을 `Alt+Shift+←/↓/↑` 로 둔 이유는 Tab·Escape·Ctrl+Space 같은 관례 키를 뺏지 않기 위해서다(우리는 키를 삼키지 않으므로 원래 동작이 함께 실행된다). 그 대가는 "Tab 으로 수락" 같은 자연스러운 조작이 아니라는 점이고, 인라인 컴플리션 도구 대부분(Tab)과 다르다. | `packages/core/src/keybinding.ts`(`suggestion-accept`/`next`/`dismiss`), `apps/desktop/src/main/bootstrap.ts`(트리거 구독) | 오버레이가 보일 때만 Tab 을 삼키는 경로(전역 후킹에서 조건부 suppress)를 검토한다. 지금은 불가능하지 않지만 포커스 없는 창에서 키를 가로채는 설계가 필요하다. | | GAP-LLM-03 | LLM | `[x]` **2026-09-22 코드 구현 완료.** 공유 `_abortController`를 요청별 controller로 대체하고 외부 signal을 각 요청에 연결/정리한다. generate/stream은 2048 tokens / 120 s, chat은 512 / 60 s로 제한하며, stream은 `done` frame 없이는 성공 처리하지 않고 불완전 응답을 정리한다. VoiceConversation은 single-flight와 request signal을 통해 local cancel을 실제 chat 취소로 전달한다. | `apps/desktop/src/main/services/LocalLLMService.ts`, `VoiceConversationService.ts` | 독립 표적 검증: 6 test files / 69 tests passed / 0 failed. 변경 코드·테스트 ESLint exit 0, `git diff --check` exit 0. 이는 전체 strict typecheck 또는 GUI 검증이 아니다. 앱 재시작 뒤 동시 제안·음성 요청의 요청별 취소와 `done` 누락 실패 처리는 GAP-LLM-04에서 계속 확인한다. | +| GAP-PERF-01 | Memory | `[~]` **2026-10-11 PC 전체 멈춤 = 누수가 아니라 모델 상주 정책.** HEAD 로컬 빌드 실측: 앱 기동 20초 만에 커밋 34.2→52.3 GB, 여유 RAM 7.9 GB→32 MB. 내역은 llama-server(gemma4:e4b) 11.4 GB(`CUDA_Host` pinned 5.9 GB + mmproj 1.1 GB, Ollama 가 Windows CUDA 에서 mmap 을 끈다), Whisper 사이드카(large-v3) 5.8 GB, Electron 8프로세스 약 400 MB(6분간 평탄). 실시간 자막의 보조 모델(large-v3-turbo)은 VRAM 11.8/12 GB 상태에서 로딩에 100.5 s 가 걸려 첫 전사가 타임아웃됐다. 부팅 워밍업·30m 상주는 9/22 에 한 번 제거됐다가 콜드 로딩 UX 때문에 되돌아온 이력이 있다(GAP-LLM-04, GAP-INPUT-06). | `services/llm/model-residency.ts`, `LocalLLMService.ts`, `SuggestionService.ts`, `bootstrap.ts`, `sidecar/main.py`(`/unload`), `LocalSTTService.releaseAuxModel`, `CaptionService.stop`, `VoiceModeService`(`tailAudio`), `VoiceConversationService`(5분 상한), `ipc/audio-handlers.ts`(세대 가드), `CloudSyncService.startRealtime`(단일 실행 + `removeChannel`), `MeetingModeService._saveWav` | 수정 완료(데스크톱 vitest 2545 passed): keep_alive 10m 단일화·부팅 워밍업 제거·종료 시 언로드·자막 종료 시 보조 STT 모델 언로드·부분 전사 끝부분만 복사·음성 대화 듣기 버퍼 5분 상한·마이크 테스트 재진입 고아 방지·Realtime 바인딩 중복 방지·회의 WAV 저장 concat 제거. **남은 일:** (1) 사이드카 재빌드 전까지 설치본 `sidecar.exe` 엔 `/unload` 가 없어 언로드가 HTTP 404 로 조용히 실패한다, (2) 기본 모델을 텍스트 전용 소형 모델로 바꾸거나 제안 전용으로 분리할지 결정(가장 큰 절감, 품질 확인 필요), (3) primary Whisper idle 언로드, (4) 회의 PCM 을 메모리 대신 디스크로 스트리밍(시간당 115 MB 상주), (5) 받아쓰기 녹음 길이 상한(UX 결정 필요), (6) 수정 후 앱 재시작·자막·타이핑 실측. | | GAP-LLM-04 | LLM | `[~]` **Gemma/Ollama residency·burst·unbounded chat root cause (2026-09-22).** 19:14:12 boot warmup의 `keep_alive: 30m`가 `gemma4:e4b`를 expiry 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 상주시켰다. Windows GPU Engine PID 표본에는 활성 Ollama compute가 없어 무한 추론이 아니라 강제 residency였다. 19:11:17–19:11:58 자동 제안 반복은 기존 900 ms / 12 per min / 5 candidates / 128 tokens / 1-char growth가 허용한 burst였다. 위험 경로는 chat의 무제한 `num_predict`(Ollama 기본 `-1`), timeout·외부 abort 부재, 공유 취소, `done` 없는 EOF 성공, voice cancel 미전파, watchdog의 비취소였다. | `apps/desktop/src/main/services/{LocalLLMService,SuggestionService,VoiceConversationService}.ts`, Ollama `/api/ps` and Windows GPU Engine observations | 구현 계약: boot warmup 제거, suggestion `keep_alive: 2m`; 600 ms debounce / 5 s interval / 6 per min (hard max 12) / 3 candidates / 64 tokens / 12-char growth / 8 s timeout; 요청별 cancellation, bounded requests, done/cleanup, voice single-flight, spawn/poll dedupe와 dispose. Raw Ollama 증거: cold bounded 요청은 client hard timeout 15.044 s에 취소된 뒤 `/api/ps` empty와 `/api/version` 80 ms 회복을 보였고, explicit warmup HTTP 200은 16.639 s, 후속 `num_predict=1` / `keep_alive='2m'` 요청은 553 ms HTTP 200 / `done:true` / `eval_count:1` / `response=OK` / `done_reason:length`였으며 `/api/ps` expiry는 약 119.9 s였다. 이어 19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 단일 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다. 이는 raw API 수준의 expiry 뒤 unload 확인이다. **남은 조건:** 앱 재시작·GUI·실제 자동제안 타이핑 증거는 아니므로 그 경로에서 rate limit, timeout/cancel, 2분 residency를 확인한다. | | GAP-INPUT-06 | Input intelligence | `[~]` **제안 폭주 상한 및 runtime 확인.** 이전 24.7 s / 4.9 s, boot warmup, `keep_alive: 30m`, 48/96/128 tokens 및 2/5 candidates 기록은 역사적 가설/완화 이력이며 현재 정책이 아니다. 현 정책은 600 ms debounce, 5 s minimum interval, 6 requests/min default (hard max 12), 3 candidates, 64 output tokens, 12-character growth, 8 s timeout, `keep_alive: 2m` 및 boot warmup 제거다. | `apps/desktop/src/main/services/SuggestionService.ts`, `packages/core/src/input-intelligence.ts`, `LocalLLMService.ts` | 표적 자동 검증은 6 files / 69 passed / 0 failed이며 raw Ollama의 15.044 s cold timeout cleanup, 약 119.9 s residency expiry, 그리고 19:48:59 +09:00에 새 generate/unload/kill/retry 없이 확인한 `/api/ps` HTTP 200 / 45.8 ms / `{models:[]}` (`/api/version` HTTP 200 / 7.3 ms / `0.32.13`)도 확인됐다. 전체 strict typecheck는 green이 아니며, 이 raw API unload 증거는 앱 재시작·GUI·실제 자동제안 타이핑 검증이 아니다. 그 경로에서 rate limit, 8 s abort, 3-candidate/64-token 상한을 확인한다. | | GAP-INPUT-08 | Input intelligence | `[~]` **오타 자동 교정(INPUT-19)·문맥 제안(INPUT-20) 실앱 확인 (2026-10-03).** 자동 테스트와 실제 `gemma4:e4b` 프롬프트 프로브는 통과했지만, 외부 앱에서 "백스페이스 N + 붙여넣기" 교체가 정확히 동작하는지는 GUI 로 확인하지 않았다. | `apps/desktop/src/main/services/{TypoCorrectionService,SuggestionService,PersonalGraphService,TextInsertService}.ts`, `packages/core/src/{typo-correction,writing-context,personal-graph}.ts` | `run-desktop.bat` 재시작 후 메모장·카톡·크롬 입력창에서: (1) `됬어요 ` 치고 멈추면 `됐어요 ` 로 바뀌는지, (2) 한글 문장 중 `dkssudgktpdy` 가 `안녕하세요` 로 바뀌는지, (3) 교체 도중 계속 치면 교체가 취소되고 글이 섞이지 않는지, (4) 고친 단어를 원래대로 되돌리면 다시 고치지 않는지, (5) 앱마다 백스페이스 한 번이 한 글자를 지우는지(리치 에디터·웹 에디터), (6) 교정 뒤 제안이 고친 문장 기준으로 뜨는지. 문제가 있는 앱은 제외 목록 또는 앱별 차단 규칙으로 다룬다. |