Compare commits
2 commits
3cac14f668
...
d63854db67
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d63854db67 | ||
|
|
a7c0d6fb21 |
23 changed files with 366 additions and 104 deletions
|
|
@ -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():
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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])
|
||||
})
|
||||
|
|
|
|||
|
|
@ -152,7 +152,6 @@ describe('VoiceConversationService local response ownership', () => {
|
|||
signal: expect.any(AbortSignal),
|
||||
maxTokens: 512,
|
||||
timeoutMs: 60_000,
|
||||
keepAlive: '2m',
|
||||
}),
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -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 }])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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 })),
|
||||
|
|
|
|||
|
|
@ -181,6 +181,7 @@ vi.mock('@supabase/supabase-js', () => {
|
|||
},
|
||||
from: () => query(),
|
||||
channel: () => channel,
|
||||
removeChannel: async () => "ok",
|
||||
realtime: { setAuth: async () => undefined },
|
||||
}),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,6 +102,23 @@ vi.mock('uiohook-napi', () => ({
|
|||
}),
|
||||
}))
|
||||
|
||||
// nut-js 도 같은 이유로 막는다. 네이티브 libnut 은 X 디스플레이가 없으면 "Could not open
|
||||
// main display" 를 찍고 워커 프로세스를 죽인다(Linux 러너에서 템플릿 결과 삽입 경로가 실측
|
||||
// "Worker exited unexpectedly"). nut-js 동작이 필요한 테스트는 파일에서 다시 vi.mock 한다.
|
||||
vi.mock('@nut-tree-fork/nut-js', () => ({
|
||||
keyboard: {
|
||||
config: { autoDelayMs: 0 },
|
||||
pressKey: vi.fn(async () => undefined),
|
||||
releaseKey: vi.fn(async () => undefined),
|
||||
type: vi.fn(async () => undefined),
|
||||
},
|
||||
providerRegistry: {
|
||||
hasKeyboard: vi.fn(() => false),
|
||||
getKeyboard: vi.fn(),
|
||||
},
|
||||
Key: new Proxy<Record<string, string>>({}, { get: (_target, property) => String(property) }),
|
||||
}))
|
||||
|
||||
// WindowManager 모킹 — VoiceModeService가 import하므로 필요
|
||||
vi.mock('../src/main/windows/WindowManager', () => ({
|
||||
showRecordingTip: vi.fn(),
|
||||
|
|
|
|||
|
|
@ -237,9 +237,11 @@ describe('knowledge edge contracts', () => {
|
|||
|
||||
// redteam r3-20: 필터가 걸린 postgres_changes 는 DELETE 를 보내지 않고, 필터 없는 DELETE 구독은 남의 행 id 를 흘린다.
|
||||
// 삭제는 knowledge-realtime 의 다른 경로로 받는다 — knowledge-realtime-redteam-r3-20.test.ts 와 같은 계약.
|
||||
it('subscribes to document inserts and updates through RLS realtime, never to DELETE', () => {
|
||||
subscribeToKnowledgeDocuments(jest.fn(), jest.fn())
|
||||
it('subscribes to document inserts and updates through RLS realtime, never to DELETE', async () => {
|
||||
const subscription = subscribeToKnowledgeDocuments(jest.fn(), jest.fn())
|
||||
const events = mockRealtimeOn.mock.calls.map((call) => (call[1] as { event: string }).event)
|
||||
expect(events).toEqual(['INSERT', 'UPDATE'])
|
||||
// 구독이 삭제 대조용 setInterval 을 켠다. 끄지 않으면 Jest 가 끝나지 않아 CI 잡이 멈춘다.
|
||||
await subscription.unsubscribe()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -137,7 +137,11 @@ Stages `validate → test → build → e2e → package → publish → deploy`.
|
|||
### Forgejo Actions (`.forgejo/workflows/`)
|
||||
`ci.yml` — CI is now Forgejo-only (`.github/workflows` deleted 2026-09-26, Wave 3, dc43884). Jobs: `quality` (`version:check`, `contract:check`, `release:metadata:test`, secret scan, mobile release/config/build-config self-tests, Play asset contract, lint, typecheck, Vitest), `build-validation`, `mobile-quality`, `edge-functions` (Deno), `api-server-tests`.
|
||||
|
||||
`payple-renew.yml` — daily cron (+ manual dispatch) → `payple-renew` edge function; ported from the never-run `.github/workflows/payple-renew.yml` because the repository has no GitHub remote. Requires Forgejo secrets `SUPABASE_URL`, `CRON_SECRET`.
|
||||
`payple-renew.yml` — daily cron (+ manual dispatch) → `payple-renew` edge function; ported from the never-run `.github/workflows/payple-renew.yml` because the repository has no GitHub remote. Requires Forgejo secrets `SUPABASE_URL`, `CRON_SECRET`. 2026-09-26~10-11 `SUPABASE_URL` 시크릿이 로컬 주소(`127.0.0.1:55321`)라 한 번도 성공하지 못했다(GAP-OPS-03).
|
||||
|
||||
**Forgejo 시크릿 정본 = 루트 `.env`.** 웹 UI에서 손으로 넣지 않는다. `.env`를 고친 뒤 `node scripts/ci/set-forgejo-secrets.mjs --check` → `--write [NAME…]`. 스크립트가 Forgejo 시크릿 이름 ↔ `.env` 키 표(SUPABASE_URL, CRON_SECRET, CF_API_TOKEN←CLOUDFLARE_API_TOKEN, CF_ACCOUNT_ID←CLOUDFLARE_ACCOUNT_ID, FORGEJO_TOKEN, WIN_CSC_*)를 갖고, URL 시크릿에 로컬 주소가 있으면 아무것도 쓰지 않는다.
|
||||
|
||||
**러너:** `linux-builder` 라벨은 러너 `kd-desktop` 하나뿐이고, 그 호스트는 노트북 `ChanpacaLaptop`(ssh `vd-linux`, systemd `forgejo-runner.service`, host executor)이다. 노트북이 꺼지면 CI·크론이 전부 멈추고 Forgejo가 대기 잡을 Canceled 처리한다(실측: 2026-09-29 13:24 ~ 10-09 08:30 KST 꺼짐 → run #128~#137 Canceled, `3cac14f` push CI 미실행). GAP-CI-02.
|
||||
|
||||
`portable.yml` — 태그/수동 실행으로 **서명 없이** portable 채널(95MiB 7z 분할 볼륨 + Scoop 매니페스트 + 설치 스크립트)을 게시한다. `WIN_CSC_*` 불필요, updater feed는 건드리지 않는다.
|
||||
|
||||
|
|
|
|||
|
|
@ -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) |
|
||||
|
|
|
|||
|
|
@ -32,6 +32,9 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
|
|||
| GAP-WEB-01 | Web | 웹앱(`apps/web`)이 공개되지 않았다(배포 경로가 없었음). | `apps/web/Dockerfile`, `docker-compose.nas.yml`, `server/cloudflare-site-bridge` | `[x]` 2026-09-26: `/app` basePath·NAS `d3ro_voice_web`(3002). 터널 `kd-nas` ingress에 `d3ro.chanpaca.net` path `^/app` → NAS 3002를 추가하고 브리지 워커가 `/app`·`/api`·`/health`를 도메인 원본(터널)으로 흘린다(4aadee8). Supabase `site_url`을 `https://d3ro.chanpaca.net/app`으로(기존 localhost:3000), 허용 목록에 `/app/**` 추가. 라이브 `/app/login` 200. 같은 수정으로 9/19부터 끊겨 있던 API(`/api`, 관리자 로그인·stt-proxy)도 복구. |
|
||||
| GAP-OPS-01 | Ops | NAS 운영 compose가 저장소와 어긋나 있었다(JWT 기본값 폴백, 법률 wwwroot 마운트, 필수 변수 4개 누락). | `docker-compose.nas.yml`, NAS `/volume1/docker/d3ro/.env` | `[x]` 2026-09-26: NAS `.env`에 `SUPABASE_URL`·`SUPABASE_SERVICE_ROLE_KEY`(운영 service_role)·`ADMIN_BOOTSTRAP_TOKEN`(신규)·`API_SERVER_URL` 추가, 저장소 compose로 교체 후 `docker compose up -d`. 4개 컨테이너 정상, 백업 `*.before-wave3-20260926`. |
|
||||
| GAP-OPS-02 | Ops | 관리자 주소가 두 개였다(`admin.chanpaca.net`, `d3ro-admin.chanpaca.net`). `admin.d3ro.chanpaca.net`은 2단계 서브도메인이라 고급 인증서(ACM, 월 $10)가 필요하다. | Cloudflare 터널 kd-nas ingress, chanpaca.net DNS | `[x]` 2026-09-26: 사용자 결정 — 관리자 주소는 `d3ro-admin.chanpaca.net` 하나(chanpaca.net에 다른 서비스가 많다). `admin.chanpaca.net` 터널 규칙·DNS 삭제로 이름을 풀었다. ACM은 지금 구독하지 않는다. 참고: `*.kite`·`*.voice` 고급 인증서는 ACM이 꺼져 2026-11-02 만료 후 갱신되지 않는다(다른 프로젝트). |
|
||||
| GAP-OPS-03 | Ops | **`payple-renew` 크론이 등록 이후 한 번도 성공하지 못했다.** Forgejo 시크릿 `SUPABASE_URL`이 로컬 Supabase 주소(`127.0.0.1:55321`)로 등록돼 매일 `curl: (7) Failed to connect`. Payple 계약 전이라 청구 대상 구독은 없다(GAP-BILL-02). | `.forgejo/workflows/payple-renew.yml`, `scripts/ci/set-forgejo-secrets.mjs` | `[~]` 2026-10-11: 시크릿을 `.env` 운영 값으로 교체, 스크립트를 `.env` 정본 동기화 + 로컬 주소 거부로 확장. 남은 확인: 다음 정기 실행(10:00 KST)이 HTTP 200인지(수동 dispatch는 실결제 경로라 보류). |
|
||||
| GAP-CI-02 | CI | `linux-builder` 러너가 노트북 한 대(`kd-desktop`)뿐이라 노트북이 꺼지면 CI·크론이 통째로 멈춘다(2026-09-29~10-09, run #128~#137 Canceled). | `.forgejo/workflows/*.yml` (`runs-on: linux-builder`) | `[ ]` 후보: 상시 켜진 NAS 러너에 `linux-builder`(또는 크론 전용) 라벨 추가, 최소한 `payple-renew`는 NAS로. |
|
||||
| GAP-CI-03 | CI | 9-28부터 `ci.yml`의 데스크톱 Vitest·모바일 Jest가 테스트 전부 통과인데도 실패했다. 데스크톱: 템플릿 테스트가 결과를 실제 TextInsertService로 넣다가 nut-js(libnut)가 X 디스플레이 없음(`Could not open main display`)으로 워커를 죽임. 모바일: `knowledge-service.test.ts`가 구독의 삭제 대조 setInterval을 끄지 않아 Jest가 끝나지 않음(잡 무한 대기). | `apps/desktop/tests/setup.ts`, `apps/mobile-rn/__tests__/knowledge-service.test.ts` | `[x]` 2026-10-11: setup.ts에 nut-js 공통 목, 테스트가 unsubscribe. 러너 호스트(vd-linux)에서 데스크톱 2539/2539 exit 0, 모바일 589/589 정상 종료 확인. |
|
||||
| GAP-CI-01 | CI | macOS 빌드·서명 러너가 없다. `.github`의 build-mac·release-signing-ca는 실행된 적 없이 삭제됐다. | `.forgejo/workflows/*`, `.gitlab-ci.yml` | `[!]` EXT: Mac 호스트에 Forgejo runner(`macos` 라벨)를 붙이거나 GitLab `package-macos` 사용. 서명된 Android 릴리스는 GitLab `mobile-production-release`가 정본. |
|
||||
| GAP-I18N-02 | Desktop | 녹음 캡슐의 "처리 중..."이 `recording-tip/index.html`에 한국어로 고정돼 앱 언어를 따르지 않는다. | `apps/desktop/src/renderer/popups/recording-tip/*`, `WindowManager.getPopupI18nStrings` | `[x]` 2026-09-28: 캡슐 문구는 main `_i18n`(popup.tip.*)으로, 오류는 `@d3ro/core/voice-error-message` 분류 → 사용자 언어 문구(bootstrap 이 error.code 를 넘기지 않던 버그 포함). 팝업 문서 lang 도 앱 언어. |
|
||||
| GAP-UX-01 | Desktop | 회의 "내 메모"(상세 탭)는 이 기기 localStorage 에만 저장된다 — 기기 간 동기화되지 않는다. 끝난 회의에는 addMemo 가 거부된다(`MeetingModeService.ts:383`). | `components/meeting/meeting-notepad-storage.ts`, `MeetingModeService` | `[ ]` 2026-09-28: 끝난 회의의 사용자 노트를 받을 필드(또는 종료 후 addMemo)와 동기화 어댑터가 필요. |
|
||||
|
|
@ -96,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) 교정 뒤 제안이 고친 문장 기준으로 뜨는지. 문제가 있는 앱은 제외 목록 또는 앱별 차단 규칙으로 다룬다. |
|
||||
|
|
|
|||
|
|
@ -1,13 +1,18 @@
|
|||
// scripts/ci/set-forgejo-secrets.mjs
|
||||
// Forgejo Actions 저장소 시크릿을 점검하거나 등록한다.
|
||||
// Forgejo Actions 저장소 시크릿을 루트 .env 기준으로 점검하거나 맞춘다.
|
||||
//
|
||||
// 배경: 데스크톱 릴리스 워크플로(.forgejo/workflows/release.yml)는 아래 시크릿이
|
||||
// 없으면 fail-closed로 중단한다. 저장소에 시크릿이 하나도 없으면 태그를 올려도
|
||||
// 설치본이 게시되지 않는다(실측: run 49/51 모두 서명 가드에서 실패).
|
||||
// 원칙: 시크릿 값의 정본은 루트 .env 다. Forgejo 웹 UI 에서 손으로 넣지 말고
|
||||
// .env 를 고친 뒤 --write 로 밀어 넣는다. Forgejo API 는 값을 돌려주지 않으므로
|
||||
// --write 는 .env 에 값이 있는 시크릿을 항상 덮어쓴다.
|
||||
//
|
||||
// 배경: 2026-09-26 SUPABASE_URL 시크릿에 로컬 Supabase 주소(127.0.0.1:55321)가
|
||||
// 들어가 payple-renew 크론이 한 번도 성공하지 못했다. 그래서 운영 시크릿에는
|
||||
// 로컬 주소를 거부하는 검사를 둔다.
|
||||
//
|
||||
// 사용:
|
||||
// node scripts/ci/set-forgejo-secrets.mjs --check # 현재 상태만 확인
|
||||
// node --env-file-if-exists=.env scripts/ci/set-forgejo-secrets.mjs --write
|
||||
// node scripts/ci/set-forgejo-secrets.mjs --check # 등록 여부 + .env 값 검사
|
||||
// node scripts/ci/set-forgejo-secrets.mjs --write # .env 값으로 등록/덮어쓰기
|
||||
// node scripts/ci/set-forgejo-secrets.mjs --write SUPABASE_URL CRON_SECRET # 일부만
|
||||
//
|
||||
// 값은 출력하지 않는다(이름/존재 여부/길이만). FORGEJO_TOKEN(쓰기 스코프 필요)은
|
||||
// .env 또는 환경변수에서 읽는다.
|
||||
|
|
@ -16,18 +21,26 @@ import { readFileSync, existsSync } from 'node:fs'
|
|||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const REQUIRED = [
|
||||
'WIN_CSC_LINK',
|
||||
'WIN_CSC_KEY_PASSWORD',
|
||||
'WIN_CSC_EXPECTED_SIGNER_SUBJECT',
|
||||
'FORGEJO_TOKEN',
|
||||
// Forgejo 시크릿 이름 → .env 키. required=false 는 값이 없으면 건너뛴다.
|
||||
const SECRETS = [
|
||||
{ name: 'SUPABASE_URL', envKey: 'SUPABASE_URL', required: true, url: true, usedBy: 'payple-renew.yml' },
|
||||
{ name: 'CRON_SECRET', envKey: 'CRON_SECRET', required: true, usedBy: 'payple-renew.yml' },
|
||||
{ name: 'CF_API_TOKEN', envKey: 'CLOUDFLARE_API_TOKEN', required: true, usedBy: 'deploy-site.yml' },
|
||||
{ name: 'CF_ACCOUNT_ID', envKey: 'CLOUDFLARE_ACCOUNT_ID', required: true, usedBy: 'deploy-site.yml' },
|
||||
{ name: 'FORGEJO_TOKEN', envKey: 'FORGEJO_TOKEN', required: true, usedBy: 'release.yml, portable.yml' },
|
||||
{ name: 'WIN_CSC_LINK', envKey: 'WIN_CSC_LINK', required: false, usedBy: 'release.yml' },
|
||||
{ name: 'WIN_CSC_KEY_PASSWORD', envKey: 'WIN_CSC_KEY_PASSWORD', required: false, usedBy: 'release.yml' },
|
||||
{ name: 'WIN_CSC_EXPECTED_SIGNER_SUBJECT', envKey: 'WIN_CSC_EXPECTED_SIGNER_SUBJECT', required: false, usedBy: 'release.yml' },
|
||||
]
|
||||
|
||||
const LOCAL_HOST = /^(https?:\/\/)?(localhost|127\.|0\.0\.0\.0|\[::1\]|host\.docker\.internal)/i
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const args = process.argv.slice(2)
|
||||
const write = args.includes('--write')
|
||||
const only = args.filter((arg) => !arg.startsWith('--'))
|
||||
|
||||
/** .env(있으면) + 환경변수에서 값 조회. 값은 로그에 절대 남기지 않는다. */
|
||||
/** .env(있으면) + 환경변수에서 값 조회. .env 가 우선이다(정본). 값은 로그에 남기지 않는다. */
|
||||
function readEnv() {
|
||||
const values = { ...process.env }
|
||||
const envPath = join(root, '.env')
|
||||
|
|
@ -35,14 +48,23 @@ function readEnv() {
|
|||
for (const line of readFileSync(envPath, 'utf8').split(/\r?\n/)) {
|
||||
if (!/^[A-Z0-9_]+=/.test(line)) continue
|
||||
const index = line.indexOf('=')
|
||||
const key = line.slice(0, index)
|
||||
if (values[key]) continue
|
||||
values[key] = line.slice(index + 1).trim()
|
||||
const value = line.slice(index + 1).trim().replace(/^(['"])(.*)\1$/, '$2')
|
||||
if (value) values[line.slice(0, index)] = value
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
/** 값이 운영 시크릿으로 쓸 수 있는지. 문제가 있으면 이유를, 없으면 null. */
|
||||
function validate(spec, value) {
|
||||
if (!value) return spec.required ? '.env 에 값 없음' : null
|
||||
if (spec.url) {
|
||||
if (LOCAL_HOST.test(value)) return '로컬 주소는 운영 시크릿이 될 수 없음'
|
||||
if (!/^https:\/\/[^/]+$/.test(value.replace(/\/$/, ''))) return 'https://<host> 형식이어야 함'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const env = readEnv()
|
||||
const token = env.FORGEJO_TOKEN?.trim()
|
||||
const server = (env.GIT_SERVER_URL?.trim() || 'https://git.chanpaca.net').replace(/\/$/, '')
|
||||
|
|
@ -72,60 +94,51 @@ async function putSecret(name, value) {
|
|||
headers: { ...headers, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ data: value }),
|
||||
})
|
||||
if (!response.ok && response.status !== 201 && response.status !== 204) {
|
||||
if (!response.ok) {
|
||||
throw new Error(`${name} 등록 실패: HTTP ${response.status}`)
|
||||
}
|
||||
}
|
||||
|
||||
const existing = await listSecrets()
|
||||
console.log(`저장소: ${owner}/${repo} (${server})`)
|
||||
console.log(`시크릿 API: ${apiBase}\n`)
|
||||
|
||||
let missing = 0
|
||||
for (const name of REQUIRED) {
|
||||
const present = existing.has(name)
|
||||
if (present) {
|
||||
console.log(` [x] ${name} — 등록됨`)
|
||||
continue
|
||||
}
|
||||
missing += 1
|
||||
const value = env[name]?.trim()
|
||||
console.log(` [ ] ${name} — 없음${value ? ` (환경/.env에 값 있음, 길이 ${value.length})` : ' (값 없음)'}`)
|
||||
const unknown = only.filter((name) => !SECRETS.some((spec) => spec.name === name))
|
||||
if (unknown.length) {
|
||||
console.error(`알 수 없는 시크릿: ${unknown.join(', ')}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const targets = only.length ? SECRETS.filter((spec) => only.includes(spec.name)) : SECRETS
|
||||
|
||||
if (missing === 0) {
|
||||
console.log('\n모든 릴리스 시크릿이 준비되었습니다.')
|
||||
process.exit(0)
|
||||
const existing = await listSecrets()
|
||||
console.log(`저장소: ${owner}/${repo} (${server})\n`)
|
||||
|
||||
let problems = 0
|
||||
for (const spec of targets) {
|
||||
const value = env[spec.envKey]?.trim()
|
||||
const issue = validate(spec, value)
|
||||
const registered = existing.has(spec.name) ? '등록됨' : '없음'
|
||||
const source = value ? `.env ${spec.envKey} 길이 ${value.length}` : `.env ${spec.envKey} 없음`
|
||||
if (issue && (spec.required || value)) problems += 1
|
||||
console.log(` [${issue ? '!' : 'x'}] ${spec.name} — ${registered}, ${source}${issue ? ` — ${issue}` : ''} (${spec.usedBy})`)
|
||||
}
|
||||
|
||||
if (!write) {
|
||||
console.log(
|
||||
[
|
||||
`\n누락 ${missing}건. 값이 준비되면 다음으로 등록한다:`,
|
||||
' node --env-file-if-exists=.env scripts/ci/set-forgejo-secrets.mjs --write',
|
||||
'',
|
||||
'WIN_CSC_LINK는 public-trust Authenticode PFX를 base64로 인코딩한 값이어야 하며,',
|
||||
'WIN_CSC_EXPECTED_SIGNER_SUBJECT는 그 인증서의 정확한 subject 문자열이어야 한다.',
|
||||
'(개발용 Everything2EverythingDev 인증서는 production으로 인정되지 않는다.)',
|
||||
].join('\n'),
|
||||
)
|
||||
process.exit(missing === 0 ? 0 : 2)
|
||||
console.log(problems ? `\n문제 ${problems}건.` : '\n.env 값 검사 통과. --write 로 Forgejo 에 반영한다.')
|
||||
process.exit(problems ? 2 : 0)
|
||||
}
|
||||
|
||||
if (problems) {
|
||||
console.error('\n.env 값에 문제가 있어 아무것도 쓰지 않았다. .env 를 고친 뒤 다시 실행한다.')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
let written = 0
|
||||
for (const name of REQUIRED) {
|
||||
if (existing.has(name)) continue
|
||||
const value = env[name]?.trim()
|
||||
if (!value) {
|
||||
console.log(` 건너뜀: ${name} (값 없음)`)
|
||||
continue
|
||||
}
|
||||
await putSecret(name, value)
|
||||
for (const spec of targets) {
|
||||
const value = env[spec.envKey]?.trim()
|
||||
if (!value) continue
|
||||
await putSecret(spec.name, value)
|
||||
written += 1
|
||||
console.log(` 등록: ${name}`)
|
||||
console.log(` 반영: ${spec.name}`)
|
||||
}
|
||||
|
||||
const after = await listSecrets()
|
||||
const stillMissing = REQUIRED.filter((name) => !after.has(name))
|
||||
console.log(`\n등록 ${written}건. 남은 누락: ${stillMissing.length ? stillMissing.join(', ') : '없음'}`)
|
||||
process.exit(stillMissing.length === 0 ? 0 : 2)
|
||||
const stillMissing = targets.filter((spec) => spec.required && !after.has(spec.name)).map((spec) => spec.name)
|
||||
console.log(`\n반영 ${written}건. 남은 누락: ${stillMissing.length ? stillMissing.join(', ') : '없음'}`)
|
||||
process.exit(stillMissing.length === 0 ? 0 : 2)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue