fix(desktop): stop pinning local models in memory and cap audio buffers
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Successful in 56s
ci / .NET API 서버 테스트 (push) Successful in 10s
deploy-site / deploy (push) Successful in 38s
ci / 모바일 린트·타입·Jest (push) Successful in 44s
ci / 워크스페이스 빌드 검증 (push) Successful in 54s
ci / Supabase Edge Functions + Cloudflare Worker (push) Successful in 22s
portable-unsigned / portable-windows (push) Failing after 35s
release / release-windows (push) Failing after 13s
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Successful in 56s
ci / .NET API 서버 테스트 (push) Successful in 10s
deploy-site / deploy (push) Successful in 38s
ci / 모바일 린트·타입·Jest (push) Successful in 44s
ci / 워크스페이스 빌드 검증 (push) Successful in 54s
ci / Supabase Edge Functions + Cloudflare Worker (push) Successful in 22s
portable-unsigned / portable-windows (push) Failing after 35s
release / release-windows (push) Failing after 13s
The PC-wide slowdown was not a leak but model residency: boot warmup loaded gemma4:e4b (~11.6 GB RAM incl. 5.9 GB pinned host buffer, no mmap on Windows CUDA) and kept it for 30m, next to the large-v3 sidecar. Measured on the HEAD build: free RAM 7.9 GB -> 32 MB within 20 s; after this change 10.8 GB with no Ollama model loaded until typing starts. - single LOCAL_LLM_KEEP_ALIVE (10m) for every local request; no boot warmup - unload this app's resident Ollama models (keep_alive 0) on quit - sidecar POST /unload for the aux slot; captions release it on stop - partial dictation copies only the tail window, not the whole recording - cap the voice-conversation listen buffer at 5 minutes - mic test: generation guard so re-entry cannot orphan lease/timers - startRealtime: single-flight and removeChannel to stop duplicate bindings - meeting WAV save writes header and PCM without a concat copy Docs: AI-01 policy note, GAP-PERF-01 with remaining work.
This commit is contained in:
parent
a7c0d6fb21
commit
d63854db67
19 changed files with 268 additions and 45 deletions
|
|
@ -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<void> {
|
|||
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<void> {
|
|||
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()
|
||||
|
||||
|
|
|
|||
|
|
@ -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 }) => {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<void> | 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<void> {
|
||||
startRealtime(): Promise<void> {
|
||||
// heartbeat·재시도 타이머·인증 처리가 동시에 부를 수 있다. 겹치면 realtime-js 가 같은 topic 의
|
||||
// 기존 채널 객체를 돌려줘 postgres_changes 바인딩이 호출마다 중복으로 쌓였다 — 한 번에 하나만 돈다.
|
||||
if (!this._realtimeStarting) {
|
||||
this._realtimeStarting = this._startRealtime().finally(() => {
|
||||
this._realtimeStarting = null
|
||||
})
|
||||
}
|
||||
return this._realtimeStarting
|
||||
}
|
||||
|
||||
private async _startRealtime(): Promise<void> {
|
||||
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 채널 종료')
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
||||
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<void> {
|
||||
if (!instance) return
|
||||
// 진행 중 요청을 먼저 끊어야 언로드 직후 그 요청이 모델을 다시 올리지 않는다
|
||||
instance.cancelGeneration()
|
||||
await instance.unloadResidentModels()
|
||||
instance.dispose()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -663,6 +663,32 @@ class LocalSTTService extends EventEmitter {
|
|||
this._auxModelId = modelId
|
||||
}
|
||||
|
||||
/**
|
||||
* 보조 자리 모델을 내린다 — 자막·회의가 끝나면 받아쓰기 모델만 남겨 VRAM/RAM 을 돌려준다.
|
||||
* 예전 사이드카(엔드포인트 없음)나 통신 실패여도 세션 종료를 막지 않는다.
|
||||
*/
|
||||
async releaseAuxModel(): Promise<void> {
|
||||
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<void> {
|
||||
logger.info(`모델 로딩 시작: ${modelId} (${slot})`)
|
||||
const startTime = Date.now()
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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 만료 직전 여유 — 경계에서 콜드 모델로 요청하지 않는다. */
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<VoiceLlmRoute, { kind: 'insert-raw' }>
|
||||
|
||||
|
|
@ -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<void> => {
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue