From 1d4f8d84010e63fb4853e8649e96b67d01bd37d0 Mon Sep 17 00:00:00 2001 From: Yun Chan Date: Sat, 31 Oct 2026 23:14:11 +0900 Subject: [PATCH] refactor(desktop): structure suggestion pipeline and restore test gates --- CHANGELOG.md | 14 + apps/desktop/package.json | 6 +- .../src/main/services/SuggestionService.ts | 923 ++++++++---------- .../suggestion/FirstCandidateRunner.ts | 104 ++ .../suggestion/SuggestionModelRequest.ts | 167 ++++ .../main/services/input-flow-services.test.ts | 30 +- .../input-telemetry-stale-snapshot.test.ts | 11 +- .../tests/main/sync/sync-redteam-r1-0.test.ts | 2 +- .../main/windows/popup-redteam-r2-3.test.ts | 40 + .../windows/popup-renderer-recovery.test.ts | 41 - .../tests/red/conversation.usecase.test.ts | 3 +- apps/desktop/tests/red/voice.usecase.test.ts | 3 +- apps/desktop/vitest.config.ts | 15 +- docs/map/00-index.md | 4 +- docs/map/02-infrastructure.md | 16 +- docs/map/04-desktop-app.md | 2 + docs/map/11-gap-backlog.md | 1 + 17 files changed, 813 insertions(+), 569 deletions(-) create mode 100644 apps/desktop/src/main/services/suggestion/FirstCandidateRunner.ts create mode 100644 apps/desktop/src/main/services/suggestion/SuggestionModelRequest.ts delete mode 100644 apps/desktop/tests/main/windows/popup-renderer-recovery.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 547f8cd..1da58a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Additional Whisper model management UI - Plugin system for custom pipelines +## [1.15.4] - 2026-10-31 + +> Published from an annotated tag. Installer and update metadata are served by the +> canonical Forgejo feed; no binaries are committed to this repository. + +### Changed +- **Suggestion generation pipeline modularization (`SuggestionService`).** + - Separates model-request construction, first-candidate retries, generation-session lifecycle, stale-result validation, failure fallback, and filled-candidate ranking/publication into named boundaries while preserving cancellation, timeout, personal-memory fallback, and candidate ordering behavior. + +### Fixed +- **Desktop test reliability and offline release gate.** + - Restores the 35 previously failing offline tests by preserving real STT exports in partial mocks, consolidating popup renderer recovery coverage, and aligning built-in instruction and synthetic Unicode input expectations with current behavior. + - Splits Vitest into explicit unit, service, integration, evaluation, and all scopes; the default desktop test gate now runs 2,764 deterministic offline tests with zero failures. + ## [1.15.3] - 2026-10-31 > Published from an annotated tag. Installer and update metadata are served by the diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c6cca64..31901d7 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -15,7 +15,11 @@ "lint": "eslint . --ext .ts,.tsx", "format": "prettier --write \"src/**/*.{ts,tsx,css}\"", "test": "vitest run --config vitest.config.ts", - "test:unit": "vitest run --config vitest.config.ts", + "test:all": "vitest run --config vitest.config.ts --mode all", + "test:unit": "vitest run --config vitest.config.ts --mode unit", + "test:service": "vitest run --config vitest.config.ts --mode service", + "test:integration": "vitest run --config vitest.config.ts --mode integration", + "test:eval": "vitest run --config vitest.config.ts --mode eval", "test:watch": "vitest --config vitest.config.ts", "test:e2e": "playwright test", "pack": "electron-vite build && electron-builder --dir", diff --git a/apps/desktop/src/main/services/SuggestionService.ts b/apps/desktop/src/main/services/SuggestionService.ts index 40a63a4..e2b06f9 100644 --- a/apps/desktop/src/main/services/SuggestionService.ts +++ b/apps/desktop/src/main/services/SuggestionService.ts @@ -25,12 +25,9 @@ import { matchesSessionPrefix, normalizeRequestPrefix, normalizeSessionPrefix, - parseSuggestionCandidates, - sanitizeSuggestionLine, selectPhraseHints, shouldPersistSuggestionPrefix, isTerminalApp, - extractContinuation, extractTerminalPromptPrefix, type AnchorKind, type PhysicalRect, @@ -42,17 +39,14 @@ import { type SuggestionState, type SuggestionStep } from '@d3ro/core/input-intelligence' -import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template' -import { buildQueryTerms, scoreCandidatePersonalization, splitSentences } from '@d3ro/core/personal-graph' -import { copiesContext } from '@d3ro/core/suggestion-confidence' +import { buildQueryTerms, scoreCandidatePersonalization } from '@d3ro/core/personal-graph' import { splitFirstWord } from '@d3ro/core/suggestion-text' import { predictPersonalContinuation } from '@d3ro/core/personal-ngram' -import { analyzeWritingContext, findUnsupportedFacts } from '@d3ro/core/writing-context' +import { analyzeWritingContext } from '@d3ro/core/writing-context' import { alignCorrectionToPrefix } from '@d3ro/core/typo-correction' import { configGet, configSet } from './ConfigService' import { getLogger } from './LoggerService' import { getLocalLLMService } from './LocalLLMService' -import { buildSuggestionPrompt } from './llm-prompts' import { getInputTelemetryService, type TypingContext } from './InputTelemetryService' import { getPersonalGraphService } from './PersonalGraphService' import { getTextInsertService } from './TextInsertService' @@ -66,6 +60,13 @@ import { import { SuggestionBudget } from './suggestion/SuggestionBudget' import { ModelWarmTracker } from './suggestion/ModelWarmTracker' import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex' +import { runFirstCandidateAttempts, type FirstCandidateAttemptResult } from './suggestion/FirstCandidateRunner' +import { + buildSuggestionModelRequest, + type LocalMemoryContext, + type SuggestionModelRequest, + type SuggestionModelRequestInput +} from './suggestion/SuggestionModelRequest' import { LOCAL_LLM_KEEP_ALIVE, LOCAL_LLM_KEEP_ALIVE_MS } from './llm/model-residency' import { getForegroundWindowInfo } from '../utils/win32-foreground' @@ -164,30 +165,72 @@ interface SuggestionEvents { 'state-changed': (state: SuggestionState) => void } -interface LocalMemoryContext { - continuationHints: string[] - /** 직전 문장 뒤에 사용자가 실제로 이어 쓴 문장 (그래프 follows) */ - followUpHints: string[] - relatedHints: string[] - /** 지금 글과 용어가 겹치는(또는 같은 앱) 개인 문구 — 프롬프트용 */ - phraseHints: string[] - /** 관련성과 무관한 자주 쓰는 문구 — 모델 없이 로컬 기억만으로 후보를 만들 때 뒤를 채운다 */ - fallbackPhraseHints: string[] - appPhraseCount: number +interface SuggestionGenerationRequest { + prefix: string + context: TypingContext + maxCandidates: number + maxChars: number } -/** 커서 뒤 텍스트 — 케어렛을 알 때만 (문서 중간에서 쓸 때 겹치지 않게). */ -function suffixAfterCaret(context: TypingContext): string | null { - if (context.caretOffset === null || context.caretOffset >= context.fullText.length) return null - const suffix = context.fullText.slice(context.caretOffset, context.caretOffset + 200).trim() - return suffix.length > 0 ? suffix : null +interface LocalMemoryPublication extends SuggestionGenerationRequest { + latencyMs: number + token: number | null + memory?: LocalMemoryContext | null } -/** 프롬프트의 [관련해서 사용자가 쓴 문장] — 그래프 관련 문장 먼저, 그다음 문맥과 겹치는 개인 문구. */ -function relatedPromptHints(memory: LocalMemoryContext): string[] { - return [...memory.relatedHints, ...memory.phraseHints] - .filter((value, index, list) => list.indexOf(value) === index && !memory.followUpHints.includes(value)) - .slice(0, 5) +interface GenerationFailureFallback extends SuggestionGenerationRequest { + model: string + startedAt: number + token: number + memory: LocalMemoryContext + fallbackLog?: string +} + +interface GenerationSession { + abort: AbortController + token: number + timeoutMs: number + timedOut: boolean +} + +interface GenerationTiming { + memoryMs: number + correctionMs: number + modelMs: number + attempts: number +} + +interface FirstCandidatePreparationInput { + prefix: string + context: TypingContext + maxChars: number + model: string + abort: AbortController +} + +interface FirstCandidatePreparation { + memory: LocalMemoryContext + timing: GenerationTiming + correction: SuggestionCorrection | null + promptContext: TypingContext + attemptResult: FirstCandidateAttemptResult +} + +interface FirstCandidatePreparationFailure { + memory: LocalMemoryContext + error: unknown +} + +interface FirstCandidatePublication extends SuggestionGenerationRequest { + model: string + startedAt: number + token: number + memory: LocalMemoryContext + correction: SuggestionCorrection | null + promptContext: TypingContext + spacedPreferred: boolean + candidate: SuggestionCandidate + timing: GenerationTiming } /** @@ -196,41 +239,12 @@ function relatedPromptHints(memory: LocalMemoryContext): string[] { */ const TERMINAL_TYPING_STEP_CHARS = 8 -/** 모델 출력의 모양 (길이·첫 글자 종류·줄 수) — 로그용, 내용은 담지 않는다. */ /** 공백·끝 문장부호를 무시하고 같은 후보인가 */ function sameCandidateText(a: string, b: string): boolean { const norm = (text: string) => text.replace(/\s+/gu, ' ').replace(/[.!?。!?…,]+$/u, '').trim() return norm(a) === norm(b) } -/** 접두 끝 글자 종류 — 진단용(글 내용은 남기지 않는다). */ -function describePrefixEnd(prefix: string): string { - if (/\s$/u.test(prefix)) return 'space' - const last = [...prefix].pop() ?? '' - if (!last) return 'empty' - if (/[\u3131-\u318e]/u.test(last)) return 'jamo' - if (/[가-힣]/u.test(last)) return 'hangul' - if (/[.!?。!?…~]/u.test(last)) return 'sentence-end' - if (/[,;:]/u.test(last)) return 'comma' - if (/[A-Za-z0-9]/u.test(last)) return 'ascii' - return 'other' -} - -function describeRawOutput(raw: string, prefill: boolean): string { - const first = raw.charAt(0) - const kind = - raw.length === 0 - ? 'empty' - : first === '\n' || first === '\r' - ? 'newline' - : /\s/u.test(first) - ? 'space' - : /[\p{L}\p{N}]/u.test(first) - ? 'letter' - : 'symbol' - return `mode=${prefill ? 'prefill' : 'instruct'} len=${raw.length} first=${kind} lines=${raw.split('\n').length}` -} - function commonPrefixLength(a: string, b: string): number { const max = Math.min(a.length, b.length) let index = 0 @@ -254,16 +268,6 @@ const FILL_TEMPERATURE = 1.0 /** 이어 쓰기 출력이 첫 문장(또는 첫 줄)을 끝내고 다음 글자를 쓰기 시작했는가. */ const FIRST_SENTENCE_DONE = /\S[\s\S]*?(?:[.!?。!?…]["'”’)\]]*\s+\S|\n\s*\S)/u -/** 모델 요청 하나 — 프롬프트, 전송 옵션, 출력 해석기. */ -interface ModelRequest { - prompt: string - systemPrompt?: string - raw: boolean - stop?: string[] - /** 완성된 출력 → 후보 (못 쓰면 null, 이유는 rejected) */ - parse(raw: string): { candidate: SuggestionCandidate | null; rejected: string | null } - /** 스트리밍 중간 표시용 텍스트 */ - partial(raw: string): string /** * 빈 출력일 때 다시 보낼 변형 — prefill 끝에 공백을 붙여 "다음 단어부터" 쓰게 한다. * @@ -271,8 +275,7 @@ interface ModelRequest { * prefill 은 모델이 곧바로 턴을 닫아 빈 출력이 됐다(첫 후보 18회 중 15회). 끝에 공백 하나를 붙이면 * 4문장 모두 이어 썼다. 출력 앞에 공백을 되돌려 붙여 해석하므로 이음새는 '띄어 쓰기' 가 된다. */ - spaced?: ModelRequest -} +type ModelRequest = SuggestionModelRequest /** * 모델을 메모리에 유지하는 시간 — 앱 공통 값(LOCAL_LLM_KEEP_ALIVE)을 그대로 쓴다. @@ -834,14 +837,14 @@ export class SuggestionService extends EventEmitter { if ( step.tryLocalMemory && - this._publishLocalMemory( - this._currentPrefix(context), + this._publishLocalMemory({ + prefix: this._currentPrefix(context), context, - config.maxCandidates, - config.maxChars, - 0, - null - ) + maxCandidates: config.maxCandidates, + maxChars: config.maxChars, + latencyMs: 0, + token: null + }) ) { return } @@ -1090,119 +1093,16 @@ export class SuggestionService extends EventEmitter { * 지시형 gemma 는 사용자 글에 "대답" 했다(실측 2026-10-17 이력: "혹시 어떤 기능을 염두에 두고 계신지 * 설명해 주실 수 있을까요?" — 사용자 신고 "내가 쓴 것에 대한 응답만 나온다"). 후보가 덜 다양한 편이 낫다. */ - private _buildModelRequest( - model: string, - prefix: string, - context: TypingContext, - memory: LocalMemoryContext, - maxChars: number, - options: { avoidCandidates?: readonly string[] } = {} - ): ModelRequest { + private _buildModelRequest(input: SuggestionModelRequestInput): ModelRequest { const now = Date.now() const recentWrites = getInputTelemetryService() .listRecentWrites({ - windowHandle: context.windowHandle ?? null, - appName: context.appName, - windowTitle: context.windowTitle + windowHandle: input.context.windowHandle ?? null, + appName: input.context.appName, + windowTitle: input.context.windowTitle }) .map((entry) => ({ text: entry.text, ageMs: now - entry.at })) - const promptInput = { - prefix, - documentText: context.documentBefore ?? null, - suffix: suffixAfterCaret(context), - appName: context.appName, - windowTitle: context.windowTitle, - recentWrites, - phraseHints: relatedPromptHints(memory), - continuationHints: memory.continuationHints, - followUpHints: memory.followUpHints, - avoidCandidates: options.avoidCandidates, - candidates: 1, - maxChars - } - - const prompt = buildSuggestionPrompt({ ...promptInput, prefill: true }) - const rawPrompt = renderRawChatPrompt(model, { - system: prompt.systemPrompt, - user: prompt.text, - assistantPrefix: prompt.assistantPrefix ?? '' - }) - - if (rawPrompt !== null) { - const written = splitSentences(context.documentBefore ?? prefix) - const extract = (raw: string) => - extractContinuation(raw, { - mode: prompt.writing.mode, - prefill: prompt.assistantPrefix ?? '', - writtenSentences: written, - wordFinished: prompt.wordFinished, - allowEmoji: prompt.allowEmoji, - maxChars - }) - const parse = (raw: string): { candidate: SuggestionCandidate | null; rejected: string | null } => { - const continuation = extract(raw) - if (!continuation) return { candidate: null, rejected: 'empty' } - // 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다. - const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource) - if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } - // 화면·앞 글을 그대로 베낀 후보는 버린다 (실측 2026-10-25: 앞 대화 문장이 그대로 제안됨) - if (copiesContext(continuation.text, prompt.factSource)) return { candidate: null, rejected: 'copied-context' } - return { - candidate: - continuation.joint === 'attach' - ? { text: continuation.text, rank: 0, joint: 'attach' } - : { text: continuation.text, rank: 0 }, - rejected: null - } - } - const stop = rawChatStopSequences(model) - const endsWithSpace = /\s$/u.test(prompt.assistantPrefix ?? '') - return { - prompt: rawPrompt, - raw: true, - stop, - spaced: endsWithSpace - ? undefined - : { - prompt: `${rawPrompt} `, - raw: true, - stop, - parse: (raw) => parse(` ${raw}`), - partial: (raw) => extract(` ${raw}`)?.text ?? '' - }, - parse: (raw) => { - const continuation = extract(raw) - if (!continuation) return { candidate: null, rejected: 'empty' } - // 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다. - const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource) - if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } - if (copiesContext(continuation.text, prompt.factSource)) return { candidate: null, rejected: 'copied-context' } - return { - candidate: - continuation.joint === 'attach' - ? { text: continuation.text, rank: 0, joint: 'attach' } - : { text: continuation.text, rank: 0 }, - rejected: null - } - }, - partial: (raw) => extract(raw)?.text ?? '' - } - } - - const legacy = buildSuggestionPrompt(promptInput) - return { - prompt: legacy.text, - systemPrompt: legacy.systemPrompt, - raw: false, - parse: (raw) => { - const text = parseSuggestionCandidates(raw, prefix, 1, maxChars)[0] - if (!text) return { candidate: null, rejected: 'empty' } - const unsupported = findUnsupportedFacts(text, legacy.factSource) - if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } - return { candidate: { text, rank: 0 }, rejected: null } - }, - partial: sanitizePartial - } + return buildSuggestionModelRequest({ ...input, recentWrites }) } private _isCurrentFallbackContext( @@ -1229,15 +1129,8 @@ export class SuggestionService extends EventEmitter { ) } - private _publishLocalMemory( - prefix: string, - context: TypingContext, - maxCandidates: number, - maxChars: number, - latencyMs: number, - token: number | null, - memory: LocalMemoryContext | null = null - ): boolean { + private _publishLocalMemory(publication: LocalMemoryPublication): boolean { + const { prefix, context, maxCandidates, maxChars, latencyMs, token, memory = null } = publication if (!this._isCurrentFallbackContext(prefix, context, token)) return false const trimmedPrefix = normalizeSessionPrefix(prefix) const localMemory = memory ?? this._collectMemoryHints(trimmedPrefix, context.appName) @@ -1333,8 +1226,236 @@ export class SuggestionService extends EventEmitter { return true } + private _handleGenerationFailure(failure: GenerationFailureFallback): void { + const { prefix, context, maxCandidates, maxChars, model, startedAt, token, memory, fallbackLog } = failure + this._lastSkipReason = 'generation-failed' + if (this._keepPersonalCandidate(prefix, model, startedAt)) return + if ( + this._publishLocalMemory({ + prefix, + context, + maxCandidates, + maxChars, + latencyMs: Date.now() - startedAt, + token, + memory + }) + ) { + if (fallbackLog) logger.warn(fallbackLog) + return + } + this.dismiss('generation-failed') + this.emit('state-changed', this.getState()) + } + + private _startGenerationSession(prefix: string, trimmedPrefix: string, context: TypingContext): GenerationSession { + this._abort?.abort() + const abort = new AbortController() + this._abort = abort + const token = (this._generationToken += 1) + + this._clearNotice() + this._inFlight = true + this._generating = true + this._lastRequestedPrefix = normalizeRequestPrefix(prefix) + this._warmingUp = false + this._provenance = null + this._budget.consume(Date.now()) + + this._candidates = [] + this._correction = null + this._promptContext = null + this._sessionRecordId = null + this._activeIndex = 0 + this._anchor = context.anchor + this._anchorKind = context.anchorKind + this._appName = context.appName + this._windowTitle = context.windowTitle + this._windowHandle = context.windowHandle ?? null + const instant = this._personalCandidate(context) + if (instant) { + this._candidates = [instant] + this._generatedForPrefix = trimmedPrefix + this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal + this._provenance = { mode: 'local-memory', continuationCount: 0, relatedCount: 0, phraseCount: 0, appPhraseCount: 0 } + } + this._armVisibleTtl() + this.emit('updated', this.getState()) + + const timeoutMs = this.readTimeoutMs() + const session: GenerationSession = { abort, token, timeoutMs, timedOut: false } + if (this._timeoutTimer) clearTimeout(this._timeoutTimer) + this._timeoutTimer = setTimeout(() => { + if (!abort.signal.aborted) { + session.timedOut = true + abort.abort() + } + }, timeoutMs) + this._timeoutTimer.unref?.() + return session + } + + private _publishFirstCandidate(publication: FirstCandidatePublication): void { + const { + prefix, + context, + maxChars, + model, + startedAt, + token, + memory, + correction, + promptContext, + spacedPreferred, + candidate, + timing + } = publication + const latencyMs = Date.now() - startedAt + this._lastLatencyMs = latencyMs + this._budget.noteSuccess() + this._partialText = '' + const personal = this._candidates.find((item) => item.source === 'personal') + this._candidates = + personal && !sameCandidateText(personal.text, candidate.text) + ? [{ ...personal, rank: 0 }, { ...candidate, rank: 1 }] + : [{ ...candidate, rank: 0 }] + this._correction = correction + this._promptContext = promptContext + this._spacedPreferred = spacedPreferred + this._activeIndex = 0 + this._anchor = context.anchor + this._anchorKind = context.anchorKind + this._appName = context.appName + this._windowTitle = context.windowTitle + this._windowHandle = context.windowHandle ?? null + this._generatedForPrefix = prefix + this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal + this._lastSkipReason = null + this._provenance = { + mode: 'local-model', + continuationCount: memory.continuationHints.length, + relatedCount: memory.relatedHints.length + memory.followUpHints.length, + phraseCount: memory.phraseHints.length, + appPhraseCount: memory.appPhraseCount + } + + this._recordSuggestion({ prefix, text: candidate.text, model, latencyMs, candidateCount: 1 }) + logger.info(`제안 첫 후보 생성 (${latencyMs}ms, model=${model}) — 최대 ${SUGGESTION_DEFAULTS.maxCandidatesTotal}개까지 순차로 채운다`) + logger.debug( + `제안 지연 분해: 기억 ${timing.memoryMs}ms, 교정 ${timing.correctionMs}ms, 모델 ${timing.modelMs}ms (시도 ${timing.attempts}회)` + ) + this._armVisibleTtl() + this.emit('updated', this.getState()) + + this._filling = true + void this._runFillLoop(token, context, maxChars).catch((error: unknown) => { + logger.warn(`제안 채우기 루프 예외: ${error instanceof Error ? error.message : String(error)}`) + this._filling = false + }) + } + // ── 생성 ────────────────────────────────────────────── + private _isGenerationResultCurrent(trimmedPrefix: string, token: number): boolean { + // 사용자가 그사이 닫았거나 새 요청이 시작됐다면 이 결과는 버린다. + if (token !== this._generationToken) { + logger.debug(`제안 결과 폐기 (세대 ${token} ≠ ${this._generationToken})`) + return false + } + + // 타이핑을 멈추고 자리를 뜬 뒤 도착한 결과는 화면에 띄우지 않는다. + // (아무것도 안 치는데 제안창이 뜨던 신고의 원인 중 하나) + const staleness = Date.now() - this._lastContextAt + if (this._lastContextAt > 0 && staleness > SUGGESTION_DEFAULTS.resultMaxStalenessMs) { + logger.debug(`제안 결과 폐기 (문맥이 ${staleness}ms 지났다)`) + this.dismiss('stale') + return false + } + + // 요청 뒤 사용자가 더 쳤다면 이 결과는 옛 접두용이다 — 게시하면 다음 스냅샷에서 곧바로 + // stale 로 닫히며(깜빡임) 채우기 요청만 낭비하고, 그사이 수락하면 방금 친 말이 빠진 + // 문장이 들어간다. 세션과 같은 기준(matchesSessionPrefix)으로 최신 문맥과 맞춰 본다. + const latest = this._lastContext + if (latest && !matchesSessionPrefix(trimmedPrefix, latest.prefix)) { + logger.debug('제안 결과 폐기 (요청 뒤 접두가 바뀌었다)') + this.dismiss('stale') + this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs) + this.emit('state-changed', this.getState()) + return false + } + return true + } + + private async _prepareFirstCandidate( + input: FirstCandidatePreparationInput + ): Promise { + const { prefix, context, maxChars, model, abort } = input + // 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장, + // (2) follows/용어공유 관계로 끌어온 관련 문장. + const memoryStartedAt = Date.now() + let memory = this._collectMemoryHints(prefix, context.appName) + // 지연 분해 진단 — 첫 후보까지의 시간이 기억 조회·오타 교정·모델 중 어디에 쓰이는지 남긴다. + const timing = { memoryMs: Date.now() - memoryStartedAt, correctionMs: 0, modelMs: 0, attempts: 0 } + let correction: SuggestionCorrection | null = null + let promptContext = context + + try { + const correctionStartedAt = Date.now() + correction = await this._proposeCorrection(context, abort.signal) + timing.correctionMs = Date.now() - correctionStartedAt + if (correction) { + promptContext = applyCorrectionToContext(context, correction) + memory = this._collectMemoryHints(normalizeSessionPrefix(promptContext.prefix), context.appName) + } + const request = this._buildModelRequest({ + model, + prefix: normalizeSessionPrefix(promptContext.prefix), + context: promptContext, + memory, + maxChars + }) + this._partialText = '' + const modelStartedAt = Date.now() + const attemptResult = await runFirstCandidateAttempts({ + request, + model, + initialTemperature: SUGGESTION_DEFAULTS.temperature, + retryTemperature: FILL_TEMPERATURE, + signal: abort.signal, + stream: (active, activeModel, temperature, signal, onPartial) => + this._streamModel(active, activeModel, temperature, signal, onPartial), + onPartial: (partial) => { + this._partialText = partial + const now = Date.now() + if (now - this._lastPartialEmitAt >= 120) { + this._lastPartialEmitAt = now + this.emit('updated', this.getState()) + } + }, + diagnostics: { + appName: context.appName, + prefix: promptContext.prefix, + composing: context.isComposing === true + }, + logger, + onRetry: () => { + this._partialText = '' + } + }) + timing.attempts = attemptResult.attempts + timing.modelMs = Date.now() - modelStartedAt + return { memory, timing, correction, promptContext, attemptResult } + } catch (error) { + return { memory, error } + } finally { + if (this._abort === abort) this._abort = null + if (this._timeoutTimer) { + clearTimeout(this._timeoutTimer) + this._timeoutTimer = null + } + } + } + private async _generate( prefix: string, context: TypingContext, @@ -1360,14 +1481,14 @@ export class SuggestionService extends EventEmitter { const config = this.readPolicyConfig() if ( this._canUseLocalMemory(context, config, startedAt) && - this._publishLocalMemory( - trimmedPrefix, + this._publishLocalMemory({ + prefix: trimmedPrefix, context, maxCandidates, maxChars, - Date.now() - startedAt, - null - ) + latencyMs: Date.now() - startedAt, + token: null + }) ) { return } @@ -1376,160 +1497,17 @@ export class SuggestionService extends EventEmitter { return } - this._abort?.abort() - const abort = new AbortController() - this._abort = abort - const token = (this._generationToken += 1) + const session = this._startGenerationSession(prefix, trimmedPrefix, context) + const { abort, token, timeoutMs } = session - this._clearNotice() - this._inFlight = true - this._generating = true - this._lastRequestedPrefix = normalizeRequestPrefix(prefix) - this._warmingUp = false - this._provenance = null - this._budget.consume(Date.now()) - - // 후보가 오기 전에 빈 화면으로 기다리게 하지 않는다 — 즉시 자리를 잡고 - // "생성 중" 을 보여준 뒤 내용으로 채운다. 실측 5초 지연에서 특히 중요하다. - this._candidates = [] - this._correction = null - this._promptContext = null - this._sessionRecordId = null - this._activeIndex = 0 - this._anchor = context.anchor - this._anchorKind = context.anchorKind - this._appName = context.appName - this._windowTitle = context.windowTitle - this._windowHandle = context.windowHandle ?? null - // 내 기록이 확신하는 이어쓰기가 있으면 모델을 기다리지 않고 1번 후보로 먼저 띄운다 — 모델 후보는 뒤에 붙는다. - // (2026-10-25: 모델을 "대신" 하면 제안이 너무 드물어졌다 — 이번엔 더하기만 한다) - const instant = this._personalCandidate(context) - if (instant) { - this._candidates = [instant] - this._generatedForPrefix = trimmedPrefix - this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal - this._provenance = { mode: 'local-memory', continuationCount: 0, relatedCount: 0, phraseCount: 0, appPhraseCount: 0 } - } - this._armVisibleTtl() - this.emit('updated', this.getState()) - - const timeoutMs = this.readTimeoutMs() - let timedOut = false - if (this._timeoutTimer) clearTimeout(this._timeoutTimer) - this._timeoutTimer = setTimeout(() => { - // 모델이 하드웨어보다 느릴 때 UI 를 붙잡지 않는다 (다음 타이핑 주기에 재시도). - if (!abort.signal.aborted) { - timedOut = true - abort.abort() - } - }, timeoutMs) - this._timeoutTimer.unref?.() - - // 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장, - // (2) follows/용어공유 관계로 끌어온 관련 문장. - const memoryStartedAt = Date.now() - let memory = this._collectMemoryHints(trimmedPrefix, context.appName) - // 지연 분해 진단 — 첫 후보까지의 시간이 기억 조회·오타 교정·모델 중 어디에 쓰이는지 남긴다. - const timing = { memoryMs: Date.now() - memoryStartedAt, correctionMs: 0, modelMs: 0, attempts: 0 } - let spacedPreferred = false - let correction: SuggestionCorrection | null = null - let promptContext = context - - let parsed: { candidate: SuggestionCandidate | null; rejected: string | null } = { candidate: null, rejected: 'empty' } - try { - // 오타가 있으면 고친 글로 이어 쓴다 — 낱자 잡음("안ㄴ뇽", "ㅇ다른")이 섞인 글을 그대로 주면 모델이 - // 그 잡음까지 되풀이했다(실측 이력: "아직 ㅇ" → "아직 ㅇ 기능도…"). 교정은 수락할 때만 적용한다. - const correctionStartedAt = Date.now() - correction = await this._proposeCorrection(context, abort.signal) - timing.correctionMs = Date.now() - correctionStartedAt - if (correction) { - promptContext = applyCorrectionToContext(context, correction) - memory = this._collectMemoryHints(normalizeSessionPrefix(promptContext.prefix), context.appName) - } - // 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자 - // 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다. - const request = this._buildModelRequest( - model, - normalizeSessionPrefix(promptContext.prefix), - promptContext, - memory, - maxChars - ) - this._partialText = '' - // 지어낸 사실(원문에 없는 날짜·이름·숫자)로 버린 첫 후보는 같은 시간 제한 안에서 한 번 더 뽑는다. - let active = request - let temperature: number = SUGGESTION_DEFAULTS.temperature - const modelStartedAt = Date.now() - for (let attempt = 0; attempt < 2; attempt += 1) { - timing.attempts = attempt + 1 - const raw = await this._streamModel(active, model, temperature, abort.signal, (partial) => { - // 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다. - // IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다. - this._partialText = partial - const now = Date.now() - if (now - this._lastPartialEmitAt >= 120) { - this._lastPartialEmitAt = now - this.emit('updated', this.getState()) - } - }) - if (abort.signal.aborted) break - parsed = active.parse(raw) - if (!parsed.candidate) { - // 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보. - logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`) - if (raw.trim().length === 0) { - // 첫 시도가 비는 조건을 찾는다(실사용 26% — 다시 뽑느라 ~250ms). 글 대신 끝 글자 종류만 남긴다. - logger.debug( - `제안 빈 출력 조건: app=${context.appName ?? '-'} end=${describePrefixEnd(promptContext.prefix)} ` + - `comp=${context.isComposing === true} spaced=${active !== request}` - ) - } - } - if (parsed.candidate) break - if (raw.trim().length === 0 && active.spaced) { - // 모델이 곧바로 턴을 닫았다 — prefill 끝에 공백을 붙여 다음 단어부터 쓰게 한다(같은 온도). - logger.debug('제안 빈 출력 — prefill 끝에 공백을 붙여 다시 뽑는다') - active = active.spaced - } else if (parsed.rejected?.startsWith('unsupported-facts')) { - logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`) - temperature = FILL_TEMPERATURE - } else { - break - } - this._partialText = '' - } - spacedPreferred = active !== request - timing.modelMs = Date.now() - modelStartedAt - } catch (error) { - if (!abort.signal.aborted) { - this._lastSkipReason = 'generation-failed' - this._noteFailure(error instanceof Error ? error.message : String(error)) - if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return - if ( - this._publishLocalMemory( - trimmedPrefix, - context, - maxCandidates, - maxChars, - Date.now() - startedAt, - token, - memory - ) - ) { - logger.warn(`모델 제안 실패 후 로컬 기억 제안으로 전환: ${error instanceof Error ? error.message : String(error)}`) - return - } - this.dismiss('generation-failed') - this.emit('state-changed', this.getState()) - return - } - } finally { - if (this._abort === abort) this._abort = null - if (this._timeoutTimer) { - clearTimeout(this._timeoutTimer) - this._timeoutTimer = null - } - } + const preparation = await this._prepareFirstCandidate({ + prefix: trimmedPrefix, + context, + maxChars, + model, + abort + }) + const { memory } = preparation if (abort.signal.aborted) { if (token !== this._generationToken) { @@ -1537,129 +1515,78 @@ export class SuggestionService extends EventEmitter { return } - if (!timedOut) return + if (!session.timedOut) return - this._lastSkipReason = 'generation-failed' // warm 이라 믿고 보낸 요청이 시간 초과했다면 모델은 이미 내려갔다(다른 기능의 짧은 keep_alive 등) // — 다음 멈춤은 같은 콜드 요청을 되풀이하지 말고 워밍업("준비 중")부터 한다. this._warmth.noteCold(model) this._noteFailure(`timeout ${timeoutMs}ms`) - if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return - if ( - this._publishLocalMemory( - trimmedPrefix, - context, - maxCandidates, - maxChars, - Date.now() - startedAt, - token, - memory - ) - ) { - logger.warn(`모델 제안 시간 초과 후 로컬 기억 제안으로 전환 (${timeoutMs}ms)`) - return - } - this.dismiss('generation-failed') - this.emit('state-changed', this.getState()) + this._handleGenerationFailure({ + prefix: trimmedPrefix, + context, + maxCandidates, + maxChars, + model, + startedAt, + token, + memory, + fallbackLog: `모델 제안 시간 초과 후 로컬 기억 제안으로 전환 (${timeoutMs}ms)` + }) return } - // 사용자가 그사이 닫았거나 새 요청이 시작됐다면 이 결과는 버린다. - if (token !== this._generationToken) { - logger.debug(`제안 결과 폐기 (세대 ${token} ≠ ${this._generationToken})`) + if ('error' in preparation) { + const message = preparation.error instanceof Error ? preparation.error.message : String(preparation.error) + this._noteFailure(message) + this._handleGenerationFailure({ + prefix: trimmedPrefix, + context, + maxCandidates, + maxChars, + model, + startedAt, + token, + memory, + fallbackLog: `모델 제안 실패 후 로컬 기억 제안으로 전환: ${message}` + }) return } - // 타이핑을 멈추고 자리를 뜬 뒤 도착한 결과는 화면에 띄우지 않는다. - // (아무것도 안 치는데 제안창이 뜨던 신고의 원인 중 하나) - const staleness = Date.now() - this._lastContextAt - if (this._lastContextAt > 0 && staleness > SUGGESTION_DEFAULTS.resultMaxStalenessMs) { - logger.debug(`제안 결과 폐기 (문맥이 ${staleness}ms 지났다)`) - this.dismiss('stale') - return - } - - // 요청 뒤 사용자가 더 쳤다면 이 결과는 옛 접두용이다 — 게시하면 다음 스냅샷에서 곧바로 - // stale 로 닫히며(깜빡임) 채우기 요청만 낭비하고, 그사이 수락하면 방금 친 말이 빠진 - // 문장이 들어간다. 세션과 같은 기준(matchesSessionPrefix)으로 최신 문맥과 맞춰 본다. - const latest = this._lastContext - if (latest && !matchesSessionPrefix(trimmedPrefix, latest.prefix)) { - logger.debug('제안 결과 폐기 (요청 뒤 접두가 바뀌었다)') - this.dismiss('stale') - this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs) - this.emit('state-changed', this.getState()) - return - } + const { timing, correction, promptContext, attemptResult } = preparation + const { parsed, spacedPreferred } = attemptResult + if (!this._isGenerationResultCurrent(trimmedPrefix, token)) return const first = parsed.candidate this._failedPrefix = first ? '' : this._lastRequestedPrefix if (!first) { - this._lastSkipReason = 'generation-failed' logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`) - if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return - if ( - this._publishLocalMemory( - trimmedPrefix, - context, - maxCandidates, - maxChars, - Date.now() - startedAt, - token, - memory - ) - ) { - return - } - this.dismiss('generation-failed') - this.emit('state-changed', this.getState()) + this._handleGenerationFailure({ + prefix: trimmedPrefix, + context, + maxCandidates, + maxChars, + model, + startedAt, + token, + memory + }) return } - const latencyMs = Date.now() - startedAt - this._lastLatencyMs = latencyMs - this._budget.noteSuccess() - this._partialText = '' - // 먼저 띄운 내 기록 후보가 있으면 그 뒤에 붙인다(같은 글이면 하나만). - const personal = this._candidates.find((candidate) => candidate.source === 'personal') - this._candidates = - personal && !sameCandidateText(personal.text, first.text) - ? [{ ...personal, rank: 0 }, { ...first, rank: 1 }] - : [{ ...first, rank: 0 }] - this._correction = correction - this._promptContext = promptContext - this._spacedPreferred = spacedPreferred - this._activeIndex = 0 - this._anchor = context.anchor - this._anchorKind = context.anchorKind - this._appName = context.appName - this._windowTitle = context.windowTitle - this._windowHandle = context.windowHandle ?? null - this._generatedForPrefix = trimmedPrefix - this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal - this._lastSkipReason = null - this._provenance = { - mode: 'local-model', - continuationCount: memory.continuationHints.length, - relatedCount: memory.relatedHints.length + memory.followUpHints.length, - phraseCount: memory.phraseHints.length, - appPhraseCount: memory.appPhraseCount - } - - this._recordSuggestion({ prefix: trimmedPrefix, text: first.text, model, latencyMs, candidateCount: 1 }) - logger.info(`제안 첫 후보 생성 (${latencyMs}ms, model=${model}) — 최대 ${SUGGESTION_DEFAULTS.maxCandidatesTotal}개까지 순차로 채운다`) - logger.debug( - `제안 지연 분해: 기억 ${timing.memoryMs}ms, 교정 ${timing.correctionMs}ms, 모델 ${timing.modelMs}ms (시도 ${timing.attempts}회)` - ) - this._armVisibleTtl() - this.emit('updated', this.getState()) - - // generating 은 계속 true 로 남는다 — 채우기 루프가 백그라운드에서 나머지를 - // 하나씩 청한다("더 온다" 를 UI 에 알린다). _releaseGeneration() 이 이를 - // 지우지 않도록 _filling 을 먼저 켠다. - this._filling = true - void this._runFillLoop(token, context, maxChars).catch((error: unknown) => { - logger.warn(`제안 채우기 루프 예외: ${error instanceof Error ? error.message : String(error)}`) - this._filling = false + this._publishFirstCandidate({ + prefix: trimmedPrefix, + context, + maxCandidates, + maxChars, + model, + startedAt, + token, + memory, + correction, + promptContext, + spacedPreferred, + candidate: first, + timing }) } finally { // 어떤 경로로 끝나든 진행 플래그를 해제한다 — @@ -1762,7 +1689,7 @@ export class SuggestionService extends EventEmitter { const prefix = normalizeSessionPrefix(promptContext.prefix) const memory = this._collectMemoryHints(prefix, context.appName) const avoidCandidates = this._candidates.map((candidate) => candidate.text) - const built = this._buildModelRequest(model, prefix, promptContext, memory, maxChars, { avoidCandidates }) + const built = this._buildModelRequest({ model, prefix, context: promptContext, memory, maxChars, avoidCandidates }) const request = this._spacedPreferred && built.spaced ? built.spaced : built const raw = await this._streamModel(request, model, FILL_TEMPERATURE, abort.signal) if (abort.signal.aborted || token !== this._generationToken) return false @@ -1775,40 +1702,7 @@ export class SuggestionService extends EventEmitter { const candidate = parsed.candidate if (token !== this._generationToken || this._isDuplicateCandidate(candidate.text)) return false - this._candidates.push({ ...candidate, rank: this._candidates.length }) - if (this._activeIndex === 0 && this._candidates.length >= 2) { - const personalContext = { - prefix, - continuationHints: memory.continuationHints, - followUpHints: memory.followUpHints, - relatedHints: memory.relatedHints, - phraseHints: memory.phraseHints - } - const newScore = scoreCandidatePersonalization(candidate.text, personalContext) - if (newScore >= 1.5) { - const personalItems = this._candidates.filter((item) => item.source === 'personal') - const modelItems = this._candidates - .filter((item) => item.source !== 'personal') - .map((item, idx) => ({ - item, - idx, - score: scoreCandidatePersonalization(item.text, personalContext) - })) - .sort((a, b) => (Math.abs(b.score - a.score) >= 0.8 ? b.score - a.score : a.idx - b.idx)) - .map((entry) => entry.item) - this._candidates = [...personalItems, ...modelItems].map((item, index) => ({ - ...item, - rank: index - })) - } - } - logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`) - this._armVisibleTtl() - this.emit('updated', this.getState()) - // 채우기 후보는 새 행이 아니다 — 세션 행의 후보 수만 늘린다(지연 0 행이 평균·수락률을 망쳤다). - if (this._sessionRecordId) { - this._repository.updateSessionCandidates?.(this._sessionRecordId, this._candidates.length) - } + this._appendFilledCandidate(candidate, prefix, memory) return true } catch (error) { if (!abort.signal.aborted) { @@ -1823,6 +1717,43 @@ export class SuggestionService extends EventEmitter { } } + private _appendFilledCandidate(candidate: SuggestionCandidate, prefix: string, memory: LocalMemoryContext): void { + this._candidates.push({ ...candidate, rank: this._candidates.length }) + if (this._activeIndex === 0 && this._candidates.length >= 2) { + const personalContext = { + prefix, + continuationHints: memory.continuationHints, + followUpHints: memory.followUpHints, + relatedHints: memory.relatedHints, + phraseHints: memory.phraseHints + } + const newScore = scoreCandidatePersonalization(candidate.text, personalContext) + if (newScore >= 1.5) { + const personalItems = this._candidates.filter((item) => item.source === 'personal') + const modelItems = this._candidates + .filter((item) => item.source !== 'personal') + .map((item, idx) => ({ + item, + idx, + score: scoreCandidatePersonalization(item.text, personalContext) + })) + .sort((a, b) => (Math.abs(b.score - a.score) >= 0.8 ? b.score - a.score : a.idx - b.idx)) + .map((entry) => entry.item) + this._candidates = [...personalItems, ...modelItems].map((item, index) => ({ + ...item, + rank: index + })) + } + } + logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`) + this._armVisibleTtl() + this.emit('updated', this.getState()) + // 채우기 후보는 새 행이 아니다 — 세션 행의 후보 수만 늘린다(지연 0 행이 평균·수락률을 망쳤다). + if (this._sessionRecordId) { + this._repository.updateSessionCandidates?.(this._sessionRecordId, this._candidates.length) + } + } + /** * 모델 요청 하나를 스트리밍으로 받는다. * @@ -2443,18 +2374,6 @@ export class SuggestionService extends EventEmitter { } } -/** - * 스트리밍 중간 텍스트 정제 — 번호/불릿/따옴표와 지시문 누출을 화면에 잠깐 - * 보여주지 않도록 줄 단위로 다듬는다. - */ -function sanitizePartial(raw: string): string { - const lines = raw - .split(/\r?\n/u) - .map((line) => sanitizeSuggestionLine(line, SUGGESTION_MAX_OUTPUT_CHARS) ?? line.trim()) - .filter((line) => line.length > 0) - return lines.slice(0, 2).join(' ').slice(0, SUGGESTION_MAX_OUTPUT_CHARS) -} - /** 입력 텔레메트리가 맥락을 보낼 수 있는 상태인가 (수집 동의 + 일시정지 아님). */ export function hasInputContextConsent(): boolean { return configGet('inputTelemetryEnabled') === true && configGet('inputTelemetryPaused') !== true diff --git a/apps/desktop/src/main/services/suggestion/FirstCandidateRunner.ts b/apps/desktop/src/main/services/suggestion/FirstCandidateRunner.ts new file mode 100644 index 0000000..400a0f4 --- /dev/null +++ b/apps/desktop/src/main/services/suggestion/FirstCandidateRunner.ts @@ -0,0 +1,104 @@ +import type { SuggestionCandidateParseResult, SuggestionModelRequest } from './SuggestionModelRequest' + +export interface FirstCandidateDiagnostics { + appName: string | null + prefix: string + composing: boolean +} + +export interface FirstCandidateLogger { + debug(message: string): void + info(message: string): void +} + +export interface FirstCandidateAttemptInput { + request: SuggestionModelRequest + model: string + initialTemperature: number + retryTemperature: number + signal: AbortSignal + diagnostics: FirstCandidateDiagnostics + logger: FirstCandidateLogger + stream( + request: SuggestionModelRequest, + model: string, + temperature: number, + signal: AbortSignal, + onPartial: (partial: string) => void + ): Promise + onPartial(partial: string): void + onRetry(): void +} + +export interface FirstCandidateAttemptResult { + parsed: SuggestionCandidateParseResult + spacedPreferred: boolean + attempts: number +} + +function describeRawOutput(raw: string, prefill: boolean): string { + const first = raw.charAt(0) + const kind = + raw.length === 0 + ? 'empty' + : first === '\n' || first === '\r' + ? 'newline' + : /\s/u.test(first) + ? 'space' + : /[\p{L}\p{N}]/u.test(first) + ? 'letter' + : 'symbol' + return `mode=${prefill ? 'prefill' : 'instruct'} len=${raw.length} first=${kind} lines=${raw.split('\n').length}` +} + +function describePrefixEnd(prefix: string): string { + if (/\s$/u.test(prefix)) return 'space' + const last = [...prefix].pop() ?? '' + if (!last) return 'empty' + if (/[\u3131-\u318e]/u.test(last)) return 'jamo' + if (/[가-힣]/u.test(last)) return 'hangul' + if (/[.!?。!?…~]/u.test(last)) return 'sentence-end' + if (/[,;:]/u.test(last)) return 'comma' + if (/[A-Za-z0-9]/u.test(last)) return 'ascii' + return 'other' +} + +export async function runFirstCandidateAttempts( + input: FirstCandidateAttemptInput +): Promise { + let active = input.request + let temperature = input.initialTemperature + let parsed: SuggestionCandidateParseResult = { candidate: null, rejected: 'empty' } + let attempts = 0 + + for (let attempt = 0; attempt < 2; attempt += 1) { + attempts = attempt + 1 + const raw = await input.stream(active, input.model, temperature, input.signal, input.onPartial) + if (input.signal.aborted) break + parsed = active.parse(raw) + if (!parsed.candidate) { + input.logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`) + if (raw.trim().length === 0) { + input.logger.debug( + `제안 빈 출력 조건: app=${input.diagnostics.appName ?? '-'} end=${describePrefixEnd(input.diagnostics.prefix)} ` + + `comp=${input.diagnostics.composing} spaced=${active !== input.request}` + ) + } + } + if (parsed.candidate) break + + if (raw.trim().length === 0 && active.spaced) { + input.logger.debug('제안 빈 출력 — prefill 끝에 공백을 붙여 다시 뽑는다') + input.onRetry() + active = active.spaced + } else if (parsed.rejected?.startsWith('unsupported-facts')) { + input.logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`) + input.onRetry() + temperature = input.retryTemperature + } else { + break + } + } + + return { parsed, spacedPreferred: active !== input.request, attempts } +} diff --git a/apps/desktop/src/main/services/suggestion/SuggestionModelRequest.ts b/apps/desktop/src/main/services/suggestion/SuggestionModelRequest.ts new file mode 100644 index 0000000..580feb3 --- /dev/null +++ b/apps/desktop/src/main/services/suggestion/SuggestionModelRequest.ts @@ -0,0 +1,167 @@ +import { + SUGGESTION_MAX_OUTPUT_CHARS, + extractContinuation, + parseSuggestionCandidates, + sanitizeSuggestionLine, + type SuggestionCandidate +} from '@d3ro/core/input-intelligence' +import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template' +import { splitSentences } from '@d3ro/core/personal-graph' +import { copiesContext } from '@d3ro/core/suggestion-confidence' +import { findUnsupportedFacts } from '@d3ro/core/writing-context' +import type { TypingContext } from '../InputTelemetryService' +import { buildSuggestionPrompt, type RecentWriteHint } from '../llm-prompts' + +export interface LocalMemoryContext { + continuationHints: string[] + followUpHints: string[] + relatedHints: string[] + phraseHints: string[] + fallbackPhraseHints: string[] + appPhraseCount: number +} + +export interface SuggestionCandidateParseResult { + candidate: SuggestionCandidate | null + rejected: string | null +} + +export interface SuggestionModelRequest { + prompt: string + systemPrompt?: string + raw: boolean + stop?: string[] + parse(raw: string): SuggestionCandidateParseResult + partial(raw: string): string + /** 빈 prefill 출력일 때 끝 공백을 붙여 다시 볼 요청. */ + spaced?: SuggestionModelRequest +} + +export interface SuggestionModelRequestInput { + model: string + prefix: string + context: TypingContext + memory: LocalMemoryContext + maxChars: number + recentWrites?: readonly RecentWriteHint[] + avoidCandidates?: readonly string[] +} + +function suffixAfterCaret(context: TypingContext): string | null { + if (context.caretOffset === null || context.caretOffset >= context.fullText.length) return null + const suffix = context.fullText.slice(context.caretOffset, context.caretOffset + 200).trim() + return suffix.length > 0 ? suffix : null +} + +function relatedPromptHints(memory: LocalMemoryContext): string[] { + return [...memory.relatedHints, ...memory.phraseHints] + .filter( + (value, index, list) => list.indexOf(value) === index && !memory.followUpHints.includes(value) + ) + .slice(0, 5) +} + +function parsePrefillCandidate( + raw: string, + extract: (value: string) => ReturnType, + factSource: string +): SuggestionCandidateParseResult { + const continuation = extract(raw) + if (!continuation) return { candidate: null, rejected: 'empty' } + const unsupported = findUnsupportedFacts(continuation.text, factSource) + if (unsupported.length > 0) + return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } + if (copiesContext(continuation.text, factSource)) + return { candidate: null, rejected: 'copied-context' } + return { + candidate: + continuation.joint === 'attach' + ? { text: continuation.text, rank: 0, joint: 'attach' } + : { text: continuation.text, rank: 0 }, + rejected: null + } +} + +export function buildSuggestionModelRequest( + input: SuggestionModelRequestInput +): SuggestionModelRequest { + const { model, prefix, context, memory, maxChars, recentWrites = [], avoidCandidates } = input + const promptInput = { + prefix, + documentText: context.documentBefore ?? null, + suffix: suffixAfterCaret(context), + appName: context.appName, + windowTitle: context.windowTitle, + recentWrites, + phraseHints: relatedPromptHints(memory), + continuationHints: memory.continuationHints, + followUpHints: memory.followUpHints, + avoidCandidates, + candidates: 1, + maxChars + } + + const prompt = buildSuggestionPrompt({ ...promptInput, prefill: true }) + const rawPrompt = renderRawChatPrompt(model, { + system: prompt.systemPrompt, + user: prompt.text, + assistantPrefix: prompt.assistantPrefix ?? '' + }) + + if (rawPrompt !== null) { + const written = splitSentences(context.documentBefore ?? prefix) + const extract = (raw: string) => + extractContinuation(raw, { + mode: prompt.writing.mode, + prefill: prompt.assistantPrefix ?? '', + writtenSentences: written, + wordFinished: prompt.wordFinished, + allowEmoji: prompt.allowEmoji, + maxChars + }) + const parse = (raw: string): SuggestionCandidateParseResult => + parsePrefillCandidate(raw, extract, prompt.factSource) + const stop = rawChatStopSequences(model) + const endsWithSpace = /\s$/u.test(prompt.assistantPrefix ?? '') + return { + prompt: rawPrompt, + raw: true, + stop, + spaced: endsWithSpace + ? undefined + : { + prompt: `${rawPrompt} `, + raw: true, + stop, + parse: (raw) => parse(` ${raw}`), + partial: (raw) => extract(` ${raw}`)?.text ?? '' + }, + parse, + partial: (raw) => extract(raw)?.text ?? '' + } + } + + const legacy = buildSuggestionPrompt(promptInput) + return { + prompt: legacy.text, + systemPrompt: legacy.systemPrompt, + raw: false, + parse: (raw) => { + const text = parseSuggestionCandidates(raw, prefix, 1, maxChars)[0] + if (!text) return { candidate: null, rejected: 'empty' } + const unsupported = findUnsupportedFacts(text, legacy.factSource) + if (unsupported.length > 0) + return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } + return { candidate: { text, rank: 0 }, rejected: null } + }, + partial: sanitizePartial + } +} + +function sanitizePartial(raw: string): string { + const lines = raw + .split(/\r?\n/u) + .map((line) => sanitizeSuggestionLine(line, SUGGESTION_MAX_OUTPUT_CHARS) ?? line.trim()) + .filter((line) => line.length > 0) + return lines.slice(0, 2).join(' ').slice(0, SUGGESTION_MAX_OUTPUT_CHARS) +} diff --git a/apps/desktop/tests/main/services/input-flow-services.test.ts b/apps/desktop/tests/main/services/input-flow-services.test.ts index d03abee..9528847 100644 --- a/apps/desktop/tests/main/services/input-flow-services.test.ts +++ b/apps/desktop/tests/main/services/input-flow-services.test.ts @@ -559,30 +559,30 @@ describe('입력 플로우 서비스', () => { it('세대가 달라진 로컬 후보는 게시하지 않아 명시 취소 뒤 되살아나지 않는다', () => { const service = getSuggestionService() as unknown as { _generationToken: number - _publishLocalMemory: ( - prefix: string, - context: Parameters['handleTypingContext']>[0], - maxCandidates: number, - maxChars: number, - latencyMs: number, + _publishLocalMemory: (publication: { + prefix: string + context: Parameters['handleTypingContext']>[0] + maxCandidates: number + maxChars: number + latencyMs: number token: number - ) => boolean + }) => boolean } service._generationToken = 2 expect( - service._publishLocalMemory( - '오늘 회의 결과를', - { + service._publishLocalMemory({ + prefix: '오늘 회의 결과를', + context: { prefix: '오늘 회의 결과를', fullText: '', caretOffset: null, anchor: null, anchorKind: null, isPassword: false, isEditable: true, isComposing: false, hasSelection: false, available: true, appName: 'Notion.exe', windowTitle: null, idleMs: 300, capturedAt: now, editedSinceFocus: true, typedRecently: true }, - 3, - 160, - 0, - 1 - ) + maxCandidates: 3, + maxChars: 160, + latencyMs: 0, + token: 1 + }) ).toBe(false) expect(getSuggestionService().getState().visible).toBe(false) }) diff --git a/apps/desktop/tests/main/services/input-telemetry-stale-snapshot.test.ts b/apps/desktop/tests/main/services/input-telemetry-stale-snapshot.test.ts index 1110264..39bcb70 100644 --- a/apps/desktop/tests/main/services/input-telemetry-stale-snapshot.test.ts +++ b/apps/desktop/tests/main/services/input-telemetry-stale-snapshot.test.ts @@ -133,8 +133,7 @@ describe('입력 중 늦게 도착하는 UIA 스냅샷', () => { it.each([ ['마우스 클릭', (value: Internal) => value._handleMouseDown({ x: 2, y: 3, button: 1 })], ['선택 드래그 끝', (value: Internal) => value._handleMouseUp({ x: 2, y: 3 })], - ['스크롤', (value: Internal) => value._handleWheel({ rotation: 1 })], - ['합성 유니코드 키', (value: Internal) => value._handleKeyDown({ keycode: 0 })] + ['스크롤', (value: Internal) => value._handleWheel({ rotation: 1 })] ] as const)('%s 중 도착한 응답은 버린다', async (_name, change) => { const delayed = pending() change(internal) @@ -143,6 +142,14 @@ describe('입력 중 늦게 도착하는 UIA 스냅샷', () => { expect(publish).not.toHaveBeenCalled() }) + it('합성 유니코드 키는 사용자 입력으로 오인하지 않고 진행 중 응답을 유지한다', async () => { + const delayed = pending() + internal._handleKeyDown({ keycode: 0 }) + delayed.resolve(snapshot()) + expect((await delayed.request)?.prefix).toBe('안녕하세요') + expect(publish).toHaveBeenCalledTimes(1) + }) + it('통계에서 제외한 프로그램 백스페이스도 스냅샷을 무효화한다', async () => { service.expectProgrammaticKeys(1) const delayed = pending() diff --git a/apps/desktop/tests/main/sync/sync-redteam-r1-0.test.ts b/apps/desktop/tests/main/sync/sync-redteam-r1-0.test.ts index a9e036b..61af460 100644 --- a/apps/desktop/tests/main/sync/sync-redteam-r1-0.test.ts +++ b/apps/desktop/tests/main/sync/sync-redteam-r1-0.test.ts @@ -243,7 +243,7 @@ describe('계정별 명령·템플릿', () => { expect(remote.find('custom_instructions', mine.id)).toBeUndefined() expect(remote.find('user_templates', dictation.id)).toBeUndefined() expect(remote.find('user_templates', meetingTpl.id)).toBeUndefined() - expect(getCustomInstructionService().getAll().filter((i) => i.isBuiltin)).toHaveLength(5) + expect(getCustomInstructionService().getAll().filter((i) => i.isBuiltin)).toHaveLength(6) // A 다시 로그인: A의 항목이 돌아온다 openDb(USER) diff --git a/apps/desktop/tests/main/windows/popup-redteam-r2-3.test.ts b/apps/desktop/tests/main/windows/popup-redteam-r2-3.test.ts index db58598..7f0ccb0 100644 --- a/apps/desktop/tests/main/windows/popup-redteam-r2-3.test.ts +++ b/apps/desktop/tests/main/windows/popup-redteam-r2-3.test.ts @@ -387,3 +387,43 @@ describe('createElectronScreenGeometry — 좌표 공간 변환은 어댑터 한 expect(port.workAreaNear(port.cursor())).toEqual({ x: 0, y: 0, width: 1280, height: 680 }) }) }) + +describe('recoverPopupRenderer', () => { + function fakeWindow(): { + win: Parameters[0] + reload: ReturnType + } { + const reload = vi.fn() + const win = { + isDestroyed: () => false, + webContents: { isDestroyed: () => false, reload }, + } + return { win: win as never, reload } + } + + it('크래시면 렌더러를 다시 불러온다', async () => { + const { recoverPopupRenderer } = await import('../../../src/main/windows/popup-window-factory') + const { win, reload } = fakeWindow() + expect(recoverPopupRenderer(win, 'tip', 'crashed', 1_000)).toBe(true) + expect(reload).toHaveBeenCalledTimes(1) + }) + + it('정상 종료·강제 종료(앱 종료 중)는 다시 불러오지 않는다', async () => { + const { recoverPopupRenderer } = await import('../../../src/main/windows/popup-window-factory') + const { win, reload } = fakeWindow() + expect(recoverPopupRenderer(win, 'tip', 'clean-exit', 1_000)).toBe(false) + expect(recoverPopupRenderer(win, 'tip', 'killed', 1_000)).toBe(false) + expect(reload).not.toHaveBeenCalled() + }) + + it('간격 안에 또 죽으면 다시 불러오지 않고, 간격이 지나면 다시 불러온다', async () => { + const { POPUP_RENDERER_RELOAD_INTERVAL_MS, recoverPopupRenderer } = await import( + '../../../src/main/windows/popup-window-factory' + ) + const { win, reload } = fakeWindow() + recoverPopupRenderer(win, 'tip', 'oom', 1_000) + expect(recoverPopupRenderer(win, 'tip', 'oom', 1_000 + POPUP_RENDERER_RELOAD_INTERVAL_MS - 1)).toBe(false) + expect(recoverPopupRenderer(win, 'tip', 'oom', 1_000 + POPUP_RENDERER_RELOAD_INTERVAL_MS)).toBe(true) + expect(reload).toHaveBeenCalledTimes(2) + }) +}) diff --git a/apps/desktop/tests/main/windows/popup-renderer-recovery.test.ts b/apps/desktop/tests/main/windows/popup-renderer-recovery.test.ts deleted file mode 100644 index 1c0a706..0000000 --- a/apps/desktop/tests/main/windows/popup-renderer-recovery.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -// tests/main/windows/popup-renderer-recovery.test.ts -// 팝업 렌더러가 죽으면 다시 불러온다(창이 살아 있어 다시 만들어지지 않으므로). 연속 크래시는 반복하지 않는다. - -import { describe, expect, it, vi } from 'vitest' -import type { BrowserWindow } from 'electron' -import { - POPUP_RENDERER_RELOAD_INTERVAL_MS, - recoverPopupRenderer, -} from '../../../src/main/windows/popup-window-factory' - -function fakeWindow(): { win: BrowserWindow; reload: ReturnType } { - const reload = vi.fn() - const win = { - isDestroyed: () => false, - webContents: { isDestroyed: () => false, reload }, - } as unknown as BrowserWindow - return { win, reload } -} - -describe('recoverPopupRenderer', () => { - it('크래시면 렌더러를 다시 불러온다', () => { - const { win, reload } = fakeWindow() - expect(recoverPopupRenderer(win, 'tip', 'crashed', 1_000)).toBe(true) - expect(reload).toHaveBeenCalledTimes(1) - }) - - it('정상 종료·강제 종료(앱 종료 중)는 다시 불러오지 않는다', () => { - const { win, reload } = fakeWindow() - expect(recoverPopupRenderer(win, 'tip', 'clean-exit', 1_000)).toBe(false) - expect(recoverPopupRenderer(win, 'tip', 'killed', 1_000)).toBe(false) - expect(reload).not.toHaveBeenCalled() - }) - - it('간격 안에 또 죽으면 다시 불러오지 않고, 간격이 지나면 다시 불러온다', () => { - const { win, reload } = fakeWindow() - recoverPopupRenderer(win, 'tip', 'oom', 1_000) - expect(recoverPopupRenderer(win, 'tip', 'oom', 1_000 + POPUP_RENDERER_RELOAD_INTERVAL_MS - 1)).toBe(false) - expect(recoverPopupRenderer(win, 'tip', 'oom', 1_000 + POPUP_RENDERER_RELOAD_INTERVAL_MS)).toBe(true) - expect(reload).toHaveBeenCalledTimes(2) - }) -}) diff --git a/apps/desktop/tests/red/conversation.usecase.test.ts b/apps/desktop/tests/red/conversation.usecase.test.ts index 0112dd3..c7c8dc2 100644 --- a/apps/desktop/tests/red/conversation.usecase.test.ts +++ b/apps/desktop/tests/red/conversation.usecase.test.ts @@ -18,7 +18,8 @@ vi.mock('../../src/main/services/AudioCaptureService', () => ({ calculateRMS: () => 0, })) -vi.mock('../../src/main/services/LocalSTTService', () => ({ +vi.mock('../../src/main/services/LocalSTTService', async (importOriginal) => ({ + ...(await importOriginal()), getLocalSTTService: () => ({ initialize: vi.fn(async () => undefined), transcribe: vi.fn(async () => ({ diff --git a/apps/desktop/tests/red/voice.usecase.test.ts b/apps/desktop/tests/red/voice.usecase.test.ts index ee3282b..bcac1dc 100644 --- a/apps/desktop/tests/red/voice.usecase.test.ts +++ b/apps/desktop/tests/red/voice.usecase.test.ts @@ -61,7 +61,8 @@ vi.mock('../../src/main/services/AudioCaptureService', () => ({ calculateRMS: () => 0.1, })) -vi.mock('../../src/main/services/LocalSTTService', () => ({ +vi.mock('../../src/main/services/LocalSTTService', async (importOriginal) => ({ + ...(await importOriginal()), getLocalSTTService: () => mockSTT, resetLocalSTTServiceForTests: () => undefined, })) diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts index 9f92061..debc16c 100644 --- a/apps/desktop/vitest.config.ts +++ b/apps/desktop/vitest.config.ts @@ -1,11 +1,20 @@ import { defineConfig } from 'vitest/config' import { resolve } from 'path' -export default defineConfig({ +const TEST_INCLUDE: Record = { + all: ['tests/**/*.{test,spec}.ts'], + integration: ['tests/integration/**/*.{test,spec}.ts'], + eval: ['tests/eval/**/*.{test,spec}.ts'], + unit: ['tests/unit/**/*.{test,spec}.ts'], + service: ['tests/{main,red}/**/*.{test,spec}.ts'], + offline: ['tests/{unit,main,red}/**/*.{test,spec}.ts'] +} + +export default defineConfig(({ mode }) => ({ test: { globals: true, environment: 'node', - include: ['tests/**/*.{test,spec}.ts'], + include: TEST_INCLUDE[mode] ?? TEST_INCLUDE.offline, exclude: ['tests/e2e/**'], setupFiles: ['tests/setup.ts'], testTimeout: 10000, @@ -22,4 +31,4 @@ export default defineConfig({ '@d3ro/i18n': resolve(__dirname, '../../packages/i18n/src/index.tsx') } } -}) +})) diff --git a/docs/map/00-index.md b/docs/map/00-index.md index 28be13e..7d96dce 100644 --- a/docs/map/00-index.md +++ b/docs/map/00-index.md @@ -2,7 +2,9 @@ > Status: ACTIVE > Last full audit: 2026-09-13 -> Last update: 2026-10-31 — **v1.15.2 릴리스 + `Ctrl+Alt+Enter` 제안 수락 불발 근본 해결 + 터미널·xterm.js 한글 씹힘 및 UIA·LLM 캐시 최적화(`INPUT-04`, `INPUT-06`, `INPUT-19`, `GAP-INPUT-08`, `GAP-INPUT-11`).** (1) **`Ctrl+Alt+Enter` 제안 수락 근본 해결:** ① `classifyKeyStroke`가 수정자 VK(`0x10..0x12`, `0x5b..0x5c`, `0xa0..0xa5`)보다 수정자 플래그를 먼저 검사해 `Ctrl`/`Alt`를 누르는 순간 `'shortcut'`(`key=shortcut+C+A`)으로 분류되어 `TerminalKeystrokeTracker` 버퍼가 `prefixLen=0`으로 초기화되고 `Enter`를 누르기 전에 제안 창이 닫히던 버그 수정, ② `ChordStateMachine.keyUp`에서 `Ctrl` 또는 `RightAlt`를 먼저 놓았을 때 `command`(`Ctrl+RightAlt`)만 해제하고 `break`/`return`으로 빠져나가 `suggestion-accept`(`Ctrl+Alt+Enter`)가 `_isDown`에 영구 고착되어 이후 입력이 auto-repeat으로 무시되던 버그 수정, ③ `KeyBindingService`에 `UiohookKey.NumpadEnter` 매핑 및 OS `globalShortcut` 캡처 25ms 폴백 트리거 추가, ④ `"생성 중..."` 또는 첫 후보 스트리밍 중 `Ctrl+Alt+Enter`를 누르면 무시하지 않고 첫 후보 완성(최대 2.5s) 즉시 수락(`_waitForFirstCandidate`)하도록 개선, ⑤ 터미널(`terminalMode` / `isTerminalApp`) 수락 시 클립보드 `Ctrl+V` 경합 대신 `KEYEVENTF_UNICODE` 직접 주입 및 백그라운드 채우기 루프 즉시 중단. (2) **UIA·Ollama 최적화:** 비타이핑 키 및 짧은 입력에서 780ms 중복 `_settleTimer` 스냅샷을 취소하고, `TypoCorrectionService.propose`가 이미 검사 완료된 구간(`_isRegionChecked`)에 대해 336토큰 오타 LLM 호출을 중복 실행해 제안 KV 캐시를 밀어내던 문제를 제거했다. (3) 직전 `v1.15.1`: 터미널 `WM_IME_CONTROL` 키다운 호출 제거 및 `uia_bridge.py` `xterm-helper-textarea` 고속 경로 적용. +> Last update: 2026-10-31 — **데스크톱 테스트 녹색 기준선 복구 및 제안 파이프라인 구조화.** 기본 `npm test`는 오프라인 단위·서비스 테스트 2,764개가 전부 통과하고, `test:all`은 2,788개 통과·10개 환경 의존 테스트 skip·0 실패다. `test:unit`·`test:service`·`test:integration`·`test:eval`을 하나의 Vitest 설정으로 분리하고, 제안 첫 후보 준비·stale 검증·후속 후보 게시 책임을 분리했다 (`GAP-QA-03`, `02` §3, `04` 입력 인텔리전스). +> +> Previous update: 2026-10-31 — **v1.15.2 릴리스 + `Ctrl+Alt+Enter` 제안 수락 불발 근본 해결 + 터미널·xterm.js 한글 씹힘 및 UIA·LLM 캐시 최적화(`INPUT-04`, `INPUT-06`, `INPUT-19`, `GAP-INPUT-08`, `GAP-INPUT-11`).** (1) **`Ctrl+Alt+Enter` 제안 수락 근본 해결:** ① `classifyKeyStroke`가 수정자 VK(`0x10..0x12`, `0x5b..0x5c`, `0xa0..0xa5`)보다 수정자 플래그를 먼저 검사해 `Ctrl`/`Alt`를 누르는 순간 `'shortcut'`(`key=shortcut+C+A`)으로 분류되어 `TerminalKeystrokeTracker` 버퍼가 `prefixLen=0`으로 초기화되고 `Enter`를 누르기 전에 제안 창이 닫히던 버그 수정, ② `ChordStateMachine.keyUp`에서 `Ctrl` 또는 `RightAlt`를 먼저 놓았을 때 `command`(`Ctrl+RightAlt`)만 해제하고 `break`/`return`으로 빠져나가 `suggestion-accept`(`Ctrl+Alt+Enter`)가 `_isDown`에 영구 고착되어 이후 입력이 auto-repeat으로 무시되던 버그 수정, ③ `KeyBindingService`에 `UiohookKey.NumpadEnter` 매핑 및 OS `globalShortcut` 캡처 25ms 폴백 트리거 추가, ④ `"생성 중..."` 또는 첫 후보 스트리밍 중 `Ctrl+Alt+Enter`를 누르면 무시하지 않고 첫 후보 완성(최대 2.5s) 즉시 수락(`_waitForFirstCandidate`)하도록 개선, ⑤ 터미널(`terminalMode` / `isTerminalApp`) 수락 시 클립보드 `Ctrl+V` 경합 대신 `KEYEVENTF_UNICODE` 직접 주입 및 백그라운드 채우기 루프 즉시 중단. (2) **UIA·Ollama 최적화:** 비타이핑 키 및 짧은 입력에서 780ms 중복 `_settleTimer` 스냅샷을 취소하고, `TypoCorrectionService.propose`가 이미 검사 완료된 구간(`_isRegionChecked`)에 대해 336토큰 오타 LLM 호출을 중복 실행해 제안 KV 캐시를 밀어내던 문제를 제거했다. (3) 직전 `v1.15.1`: 터미널 `WM_IME_CONTROL` 키다운 호출 제거 및 `uia_bridge.py` `xterm-helper-textarea` 고속 경로 적용. > > Previous update: 2026-10-30 — **백로그 26건 일괄 해소 (`GAP-INPUT-03`, `GAP-LLM-01`, `GAP-UX-01/02/03/05/06/07`, `GAP-I18N-01`, `GAP-REL-11/14/15`, `GAP-INFRA-01/02/04/06`, `GAP-OPS-01`, `GAP-QA-02`, `GAP-KEY-01/03`, `GAP-ADS-02`, `GAP-ID-01/02`, `GAP-TEAM-02`, `GAP-SHELL-01`, `GAP-PUSH-03`, `GAP-MTG-01`, `DOC-01`) + 입력 누락 검증 인프라 및 서비스 결함 재현(`INPUT-04/19`, `INFRA-20`, `GAP-INPUT-11`).** (1) **백로그 26건 해소:** CJK 무공백 어절 집계(`countWords`), 12개 번역 대상 언어 설정(`targetLanguage`), 12개 로케일 2,716개 키 100% 동기화(`sync-i18n-locales.mjs`), 데스크톱 strict 타입체크 0 에러(`tsconfig.node.json` + `tsconfig.web.json`), Forgejo 릴리스 태그 푸시 순서·SHA 고정(`GAP-REL-14`), 포터블 워크플로 매니페스트 검증(`GAP-REL-11`), 네이티브 ABI 스위처(`rebuild:app`/`rebuild:test`), Supabase 마이그레이션 정합성 검사기(`check:migrations`), NAS 배포 런북(`nas-deploy-runbook.md`), 오프라인 격리 테스트 하네스(`GAP-QA-02`), `KeyBindingService` 단위 테스트·`command` 전용 액션 핸들러, 데스크톱 광고 보상 쿼터 연동(`grantRewardQuota`), 회의 종료 후 메모 추가·노트패드 동기화, 이력 SQLite 커서 페이지네이션·인라인 편집·전체 내보내기, 회의 요약 `[MM:SS]` 타임스탬프 인용·클릭 시크 연동(데스크톱·웹·모바일), `resolveEntitlement` 정본 통일, 통합 검색(`UnifiedSearchService`) 취소·세그먼트 검색·페이로드 경량화, 웹 팀 초대 수락(`/app/accept-invite`), 관리자 고객지원 콘솔(`/support`), Web Push 서비스워커(`sw.js`)·iOS APNs 토큰 등록을 완료했다. (2) **입력 누락 검증 인프라(`GAP-INPUT-11`):** `typing-race-proof.mjs`가 체크아웃을 바꾸지 않고 3개 서비스만 HEAD `f49acf0`와 수정본으로 바꿔 같은 현재 의존성·시험에서 비교했다: HEAD 1/17, 수정본 17/17. 3개 문자열 손상 사례와 13개 스냅샷·메타데이터·조회 병합 계약 실패를 구분했고, 정상 교정 대조군은 양쪽 모두 통과했다. `typing-fixture`(scan-code·IME·CPU 부하)와 `typing-runtime`(별도 로컬 프로필·실제 제품 번들)을 준비했으며, 실제 GUI·IME·CPU·모델 cold/warm 시험은 아직 미실행이다. 증거: `test-results/typing-load/race-proof-2026-10-30T00-50-32-284Z/report.json`; 실행 명령은 `02` §3, 검증 경계는 `04` §6과 `11` GAP-INPUT-11. > diff --git a/docs/map/02-infrastructure.md b/docs/map/02-infrastructure.md index ac4f0db..57a2870 100644 --- a/docs/map/02-infrastructure.md +++ b/docs/map/02-infrastructure.md @@ -1,7 +1,7 @@ # 02 — Repository & Infrastructure Map > Surface: whole repo -> Last updated: 2026-10-30 — desktop typing race/load verification tools (INFRA-20) +> Last updated: 2026-10-31 — desktop Vitest green baseline and unit/service/integration/eval tiers (GAP-QA-03) > Source of truth for: layout, workspaces, build/test commands, CI/CD, Docker, deploy, scripts, resources --- @@ -111,6 +111,20 @@ Per-app commands that matter: | web | `next build`, playwright e2e in `apps/web/e2e` | | admin | `next build` (`build:admin`) | +Desktop Vitest uses one `apps/desktop/vitest.config.ts` SSOT with mode-specific include globs: + +| Command (`npm --prefix apps/desktop run …`) | Scope | +|---|---| +| `test` | Deterministic offline unit + service tests (default gate) | +| `test:unit` | `tests/unit` only | +| `test:service` | `tests/main` + `tests/red` with process/network/model doubles | +| `test:integration` | Real Ollama/Supabase tests; requires their documented environment variables | +| `test:eval` | Suggestion quality/latency evaluation and pure replay metrics | +| `test:all` | All Vitest scopes (external tests skip when their environment is absent) | +| `test:e2e` | Playwright GUI tests | + +2026-10-31 baseline (GAP-QA-03): `test:unit` 286 passed; `test:service` 2478 passed; default `test` 2764 passed; `test:all` 2788 passed / 10 skipped / 0 failed. External Ollama/Supabase tests were not run because their environment variables were absent. Run the full test gate separately from other CPU-heavy checks because voice timing suites can contend for resources. + Desktop GUI execution rule (from `CLAUDE.md` / `.agents/rules/`): run via `run-desktop.bat` or an external terminal; do not background-launch GUI from an agent subshell. Desktop input verification (2026-10-30, INFRA-20): diff --git a/docs/map/04-desktop-app.md b/docs/map/04-desktop-app.md index 64ca9ca..a0114c6 100644 --- a/docs/map/04-desktop-app.md +++ b/docs/map/04-desktop-app.md @@ -91,6 +91,8 @@ Singleton + `EventEmitter` pattern (`getXService()` accessors). | `utils/win32-foreground.ts` | Foreground window title/pid/exe/bounds and active thread Korean IME state (`isForegroundKoreanIme` via `GetGUIThreadInfo` + `ImmGetDefaultIMEWnd` + `SendMessageTimeoutW(WM_IME_CONTROL)`) via `koffi` FFI into user32/kernel32/imm32 (chosen over `get-windows`, which needs an install script this repo does not run). | | `sidecar/uia_bridge.py` | Windows UIA snapshot (`uiautomation` 2.0.29, comtypes) on a dedicated COM-initialised thread with a 1.5 s budget; never walks the UIA tree (Chrome/VS Code tree walks take 10-30 s). Uses `GetVisibleRanges()` / tail slicing `[-MAX_TEXT_CHARS:]` for large terminal scrollback buffers and `ExpandToEnclosingUnit(..., waitTime=0)` to avoid `uiautomation.py`'s default 500 ms sleep on Windows Terminal. Warm calls measure 0-15 ms. | +**2026-10-31 구조 경계:** `suggestion/SuggestionModelRequest.ts`가 prefill/지시형 모델 요청 구성, 후보 파싱, 지어낸 사실·문맥 복사 검증을 소유한다. `suggestion/FirstCandidateRunner.ts`는 첫 후보의 최대 2회 요청, 빈 prefill·사실 검증 재시도와 내용을 노출하지 않는 진단 로그를 담당한다. `_handleGenerationFailure`는 오류·시간 초과·빈 후보의 개인 후보 유지 → 로컬 기억 폭백 → 실패 종료 순서를 한 곳에서 보장한다. `_startGenerationSession`은 취소기·세대 토큰·타임아웃을 포함한 `GenerationSession`을 반환하고, `_prepareFirstCandidate`는 기억 수집·오타 교정·모델 요청과 첫 응답을 `FirstCandidatePreparation`으로 반환하며 실패 시에도 폭백용 기억 문맥을 보존한다. `_isGenerationResultCurrent`는 세대 불일치·문맥 경과·접두 변경을 순서대로 검사하고, `_publishFirstCandidate`는 개인 후보 병합·성공 기록·후속 채우기 시작을 담당하고, `_appendFilledCandidate`는 후속 후보의 추가·개인화 재정렬·표시·세션 행 후보 수 갱신을 한 곳에서 처리한다. `SuggestionService`는 입력 정책, 세대/취소, 표시, 수락만 조율한다. 모델 요청과 로컬 기억 게시는 각각 `SuggestionModelRequestInput`·`LocalMemoryPublication` 객체를 사용하며, 동작 변경 없는 순수 리팩토링이다. + The existing `input-telemetry-handlers` and `suggestion-handlers` IPC extensions expose the receipt and the flow/suggestion summaries. Receipt reads or deletes report an IPC error when storage access fails; they do not return invented counts or claim a purge succeeded. The receipt is local-only: `input_activity`, `typing_samples`, and `suggestions` retain 30 days; `personal_phrases` has no age-based automatic expiry and is removed by individual deletion, delete-all, or consent withdrawal. Smart Exclusion never records password evidence and recommends only the current app after at least four observations, zero readable results, and a problematic ratio of at least 75%; its one-click action adds an exclusion and never auto-excludes. Shortcut Safety Audit is core `auditKeyBindingMap` applied by the Settings UI; it surfaces invalid/conflict issues while preserving the existing hold/double-press exceptions. ### Account / infra / monetization diff --git a/docs/map/11-gap-backlog.md b/docs/map/11-gap-backlog.md index 7967fd7..6b1f097 100644 --- a/docs/map/11-gap-backlog.md +++ b/docs/map/11-gap-backlog.md @@ -86,6 +86,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res | GAP-KEY-02 | Key bindings | 마우스 버튼 지원이 **Windows 기준으로만** 설계·확인됐다. `KeyBindingService` 에는 마우스 관련 플랫폼 분기가 없고(`process.platform` 은 meta 수정자 라벨 표기에만 쓰인다), macOS/Linux 에서 uiohook 이 보고하는 X1/X2 버튼 번호와 OS 기본 "뒤로/앞으로" 동작과의 간섭은 확인하지 않았다. 마우스 이벤트는 suppress 가 불가능하므로 원래 동작이 항상 함께 실행된다. | `KeyBindingService.ts:235`(`readMouseButton`), `:301`(meta 라벨 분기), `packages/core/src/keybinding.ts:561-612`(마우스 카탈로그 5종). 2026-09-21 실앱 검증(GAP-KEY-01)은 **Windows 에서만** 이뤄졌고 거기서는 MB4/MB5 가 정상 동작했다. | macOS/Linux 에서 MB2~MB5 수신 여부와 버튼 번호 매핑을 확인하고, 다르면 카탈로그를 플랫폼별로 분기한다. | | GAP-KEY-03 | Key bindings | `command` 액션에 전용 핸들러가 없다. 이번에 처음으로 설정 UI 에 노출됐지만, 트리거되면 dictation 파이프라인으로 fallback 하며 `KEYBINDING_ACTIONS` 의 `holdMode:false` 대신 dictation 과 같은 hold-to-talk 로 강제된다. 개편 이전부터 같은 동작이었고 이번 작업은 그 사실을 코드에 명시화만 했다(기능 변화 없음). | `apps/desktop/src/main/services/voice-intent.ts`, `VoiceModeService.ts`, `tests/main/services/voice-intent.test.ts` | `[x]` 2026-10-30: `resolveGestureHoldMode` 및 `VoiceModeService`에서 `command` 액션이 `KEYBINDING_ACTIONS`의 `holdMode: false`(토글)와 hold-to-talk를 모두 지원하도록 예외 강제를 제거하고, `actionId === 'command'` 세션에서는 일반 받아쓰기 설정과 무관하게 음성 명령 매칭(`VoiceCommandService.match`) 및 LLM 후처리(`defaultLLMAction === 'none'`일 때 `'refine'` 폴백)를 수행하도록 전용 경로를 구현했다 (`voice-intent.test.ts` 19/19 통과). | | GAP-QA-02 | Quality | 캡션 테스트 2건이 **개발 머신에 사이드카 venv 가 있는지에 따라 결과가 갈린다**. `LocalSTTService.initialize()`(`:239`) → `_ensureSidecarRunning()`(`:583`) → `_spawnSidecar()`(`:650`) → `_waitForHealth()`(`:794`) 경로에서 venv 가 존재하면 실제 Python 프로세스를 띄우고 health 폴링이 vitest 기본 타임아웃 10초를 넘긴다. venv 가 없으면 `getSidecarCommand()`(`apps/desktop/src/main/utils/paths.ts:174`)가 즉시 throw 해서 같은 테스트가 빠르게 통과한다. 테스트가 로컬 환경을 격리하지 못한 것이 결함이다. | `apps/desktop/tests/red/harness.ts`, `tests/red/{ipc-surfaces,silent-errors,rag}.usecase.test.ts`, `tests/main/utils/paths.test.ts` | `[x]` 2026-10-30: `tests/red/harness.ts`의 `useRedHarness()`에서 `LocalSTTService.prototype.initialize`/`ensureSidecar` 및 오프라인 `fetch`를 기본 스텁 처리해 로컬 Python venv·임베딩 서버 유무와 무관하게 결정론적으로 실행되게 격리했고, `paths.test.ts`의 에러 문구 정규식도 일치시켰다 (`paths.test.ts`, `ipc-surfaces.usecase.test.ts`, `silent-errors.usecase.test.ts`, `rag.usecase.test.ts` 총 60개 테스트 1.8초 내 전수 통과). | +| GAP-QA-03 | Quality | 데스크톱 `test`와 `test:unit`이 같은 전체 Vitest 를 실행하고, STT export 모의 누락·Electron 모의 중복·오래된 built-in/UIA 기대값으로 35개가 상시 실패해 전체 테스트가 게이트 역할을 하지 못했다. | `apps/desktop/vitest.config.ts`, `apps/desktop/package.json`, `tests/red/{voice,conversation}.usecase.test.ts`, `tests/main/windows/popup-redteam-r2-3.test.ts`, `tests/main/services/input-telemetry-stale-snapshot.test.ts`, `tests/main/sync/sync-redteam-r1-0.test.ts` | `[x]` 2026-10-31: STT 부분 모의가 실제 export 를 보존하고, 팝업 복구 테스트를 기존 팝업 하네스로 통합했으며, built-in 6개와 합성 유니코드 키 무시 계약을 기대값에 반영했다. 하나의 Vitest 설정에 `unit`/`service`/`integration`/`eval`/`all` mode 를 두고 기본 `test`는 오프라인 `unit`+`service`만 실행한다. 검증: `test:unit` 286, `test:service` 2478, 기본 `test` 2764 전부 통과; `test:all` 2788 통과·10개 환경 의존 테스트 skip·0 실패; typecheck·변경 파일 ESLint·build·`git diff --check` 통과. 외부 Ollama/Supabase 실행은 환경 변수가 없어 미검증이다. | | GAP-I18N-01 | i18n | 로케일별 키 수가 크게 어긋난다. 2026-09-21 실측: `ko` 1716 / `en` 1709 / 나머지 10개 로케일 각 327. `keybinding.*` 55개는 12개 로케일 전부에 동일하게 들어갔지만, 그 밖 약 1,380개 키가 비영어 로케일에 없어 폴백 체인(locale → `en` → `ko`)으로 표시된다. 키바인딩 작업 이전부터 있던 부채이며 그 작업 범위 밖이었다. | `packages/i18n/src/locales/*.json`, `scripts/ci/sync-i18n-locales.mjs`, `apps/desktop/tests/main/services/i18n-locale-parity.test.ts` | `[x]` 2026-10-30: `scripts/ci/sync-i18n-locales.mjs`로 12개 로케일(`ko`, `en`, `ja`, `zh`, `zh-TW`, `es`, `fr`, `de`, `pt`, `ru`, `vi`, `th`) 전체를 2,716개 마스터 키로 100% 동기화하고, `i18n-locale-parity.test.ts`(15/15 통과)로 키 누락 회귀를 차단했다. | | GAP-I18N-02 | i18n | 렌더러가 `ko.json` 에 없는 `license.*` 키를 쓴다. `TranslationKey` 가 `ko.json` 에서 파생되므로 누락은 타입 에러로 드러난다. 타입 에러로만 끝나지 않는다 — 폴백 체인이 `locale → en → ko → 키 문자열` 이므로 마스터 로케일에도 없으면 **`license.team` 같은 키가 화면에 그대로 노출된다**. 2026-09-21 실측: `license.feature.premium_llm`·`license.team`·`license.enterprise` 가 없고 이로 인한 TS2345 가 4건이다. HEAD 에서도 없던 키이므로 선재 결함이며 키바인딩 작업과 무관하다. | `apps/desktop/src/renderer/components/UpgradePromptModal.tsx:47`·`:192`, `apps/desktop/src/renderer/pages/DashboardPage.tsx:481`·`:529`, `packages/i18n/src/locales/ko.json` | `[x]` 2026-09-28: 세 키 + `license.feature.cloud_sync`·`team_workspace` 를 ko·en 에 추가하고, 문자열 조립 대신 `renderer/utils/display-labels.ts`(featureLabelKey·tierLabelKey) 타입 매핑으로 바꿔 누락이 컴파일 오류가 되게 했다. `LicenseTab`·`LicenseModal` 의 TFunction TS2322 와 `currentTier` 미정의(팀·엔터프라이즈에서 설정 화면이 멈추던 결함)도 수정. 12개 로케일 전체 동기화 완료(GAP-UX-07, GAP-I18N-01). | | GAP-LLM-01 | LLM | **번역 대상 언어를 사용자가 고를 수 없다.** 항상 `English` 고정이다. `AppConfig` 에 대상 언어 키가 없고, 기존 두 키 모두 대용할 수 없다 — `language` 는 UI 로케일이라 `'ko'` 같은 코드가 프롬프트에 그대로 들어가 문장이 깨지고, `sttLanguage` 는 입력(원문) 언어라 그 값으로 번역하면 원문이 그대로 나온다. 2026-09-21 LLM 수정(`9c2b4d4`)은 대상 언어가 호출 프레임 두 단계 밖의 기본값에 의존하던 것을 명시 인자로 바로잡았을 뿐, 선택지를 만들지는 않았다(설정 키 + 설정 UI + i18n 이 필요해 patch 범위 밖으로 뒀다). | `packages/core/src/types.ts`(`AppConfig.targetLanguage`), `ConfigService.ts`, `llm-prompts.ts`(`SUPPORTED_TARGET_LANGUAGES`, `resolveTargetLanguage`), `SettingsModal.tsx`, `tests/main/services/llm-prompts.test.ts` | `[x]` 2026-10-30: `AppConfig.targetLanguage`(기본값 `'English'`)를 추가하고, `resolveTargetLanguage(explicit)`가 설정값을 읽도록 연결했으며, `SettingsModal.tsx` 후처리 섹션에 12개 번역 대상 언어 선택 드롭다운과 12개 로케일 번역 키(`settings.targetLanguage.*`)를 추가했다 (`llm-prompts.test.ts` 43/43, `i18n-locale-parity.test.ts` 15/15 통과). |